1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * Copyright (C) 1993 Linus Torvalds 4 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999 5 * SMP-safe vmalloc/vfree/ioremap, Tigran Aivazian <tigran@veritas.com>, May 2000 6 * Major rework to support vmap/vunmap, Christoph Hellwig, SGI, August 2002 7 * Numa awareness, Christoph Lameter, SGI, June 2005 8 * Improving global KVA allocator, Uladzislau Rezki, Sony, May 2019 9 */ 10 11 #include <linux/vmalloc.h> 12 #include <linux/mm.h> 13 #include <linux/module.h> 14 #include <linux/highmem.h> 15 #include <linux/sched/signal.h> 16 #include <linux/slab.h> 17 #include <linux/spinlock.h> 18 #include <linux/interrupt.h> 19 #include <linux/proc_fs.h> 20 #include <linux/seq_file.h> 21 #include <linux/set_memory.h> 22 #include <linux/debugobjects.h> 23 #include <linux/kallsyms.h> 24 #include <linux/list.h> 25 #include <linux/notifier.h> 26 #include <linux/rbtree.h> 27 #include <linux/xarray.h> 28 #include <linux/io.h> 29 #include <linux/rcupdate.h> 30 #include <linux/pfn.h> 31 #include <linux/kmemleak.h> 32 #include <linux/atomic.h> 33 #include <linux/compiler.h> 34 #include <linux/memcontrol.h> 35 #include <linux/llist.h> 36 #include <linux/uio.h> 37 #include <linux/bitops.h> 38 #include <linux/rbtree_augmented.h> 39 #include <linux/overflow.h> 40 #include <linux/pgtable.h> 41 #include <linux/hugetlb.h> 42 #include <linux/sched/mm.h> 43 #include <asm/tlbflush.h> 44 #include <asm/shmparam.h> 45 #include <linux/page_owner.h> 46 #include <linux/cleanup.h> 47 48 #define CREATE_TRACE_POINTS 49 #include <trace/events/vmalloc.h> 50 51 #include "internal.h" 52 #include "pgalloc-track.h" 53 #include "vmalloc.h" 54 55 #ifdef CONFIG_HAVE_ARCH_HUGE_VMAP 56 static unsigned int __ro_after_init ioremap_max_page_shift = BITS_PER_LONG - 1; 57 58 static int __init set_nohugeiomap(char *str) 59 { 60 ioremap_max_page_shift = PAGE_SHIFT; 61 return 0; 62 } 63 early_param("nohugeiomap", set_nohugeiomap); 64 #else /* CONFIG_HAVE_ARCH_HUGE_VMAP */ 65 static const unsigned int ioremap_max_page_shift = PAGE_SHIFT; 66 #endif /* CONFIG_HAVE_ARCH_HUGE_VMAP */ 67 68 #ifdef CONFIG_HAVE_ARCH_HUGE_VMALLOC 69 static bool __ro_after_init vmap_allow_huge = true; 70 71 static int __init set_nohugevmalloc(char *str) 72 { 73 vmap_allow_huge = false; 74 return 0; 75 } 76 early_param("nohugevmalloc", set_nohugevmalloc); 77 #else /* CONFIG_HAVE_ARCH_HUGE_VMALLOC */ 78 static const bool vmap_allow_huge = false; 79 #endif /* CONFIG_HAVE_ARCH_HUGE_VMALLOC */ 80 81 bool is_vmalloc_addr(const void *x) 82 { 83 unsigned long addr = (unsigned long)kasan_reset_tag(x); 84 85 return addr >= VMALLOC_START && addr < VMALLOC_END; 86 } 87 EXPORT_SYMBOL(is_vmalloc_addr); 88 89 struct vfree_deferred { 90 struct llist_head list; 91 struct work_struct wq; 92 }; 93 static DEFINE_PER_CPU(struct vfree_deferred, vfree_deferred); 94 95 /*** Page table manipulation functions ***/ 96 static int vmap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, 97 phys_addr_t phys_addr, pgprot_t prot, 98 unsigned int max_page_shift, pgtbl_mod_mask *mask) 99 { 100 pte_t *pte; 101 u64 pfn; 102 struct page *page; 103 unsigned long size = PAGE_SIZE; 104 105 if (WARN_ON_ONCE(!PAGE_ALIGNED(end - addr))) 106 return -EINVAL; 107 108 pfn = phys_addr >> PAGE_SHIFT; 109 pte = pte_alloc_kernel_track(pmd, addr, mask); 110 if (!pte) 111 return -ENOMEM; 112 113 lazy_mmu_mode_enable(); 114 115 do { 116 if (unlikely(!pte_none(ptep_get(pte)))) { 117 if (pfn_valid(pfn)) { 118 page = pfn_to_page(pfn); 119 dump_page(page, "remapping already mapped page"); 120 } 121 BUG(); 122 } 123 124 #ifdef CONFIG_HUGETLB_PAGE 125 size = arch_vmap_pte_range_map_size(addr, end, pfn, max_page_shift); 126 if (size != PAGE_SIZE) { 127 pte_t entry = pfn_pte(pfn, prot); 128 129 entry = arch_make_huge_pte(entry, ilog2(size), 0); 130 set_huge_pte_at(&init_mm, addr, pte, entry, size); 131 pfn += PFN_DOWN(size); 132 continue; 133 } 134 #endif 135 set_pte_at(&init_mm, addr, pte, pfn_pte(pfn, prot)); 136 pfn++; 137 } while (pte += PFN_DOWN(size), addr += size, addr != end); 138 139 lazy_mmu_mode_disable(); 140 *mask |= PGTBL_PTE_MODIFIED; 141 return 0; 142 } 143 144 static int vmap_try_huge_pmd(pmd_t *pmd, unsigned long addr, unsigned long end, 145 phys_addr_t phys_addr, pgprot_t prot, 146 unsigned int max_page_shift) 147 { 148 if (max_page_shift < PMD_SHIFT) 149 return 0; 150 151 if (!arch_vmap_pmd_supported(prot)) 152 return 0; 153 154 if ((end - addr) != PMD_SIZE) 155 return 0; 156 157 if (!IS_ALIGNED(addr, PMD_SIZE)) 158 return 0; 159 160 if (!IS_ALIGNED(phys_addr, PMD_SIZE)) 161 return 0; 162 163 if (!pmd_present(*pmd)) 164 return pmd_set_huge(pmd, phys_addr, prot); 165 166 /* 167 * Acquire the mmap read lock to exclude ptdump, which walks 168 * kernel page tables it does not own under the mmap write lock. 169 * 170 * Concurrent read lock holders are safe: each exclusively owns 171 * the range it operates on and cannot reach this page table. 172 */ 173 scoped_cond_guard(mmap_read_lock_try, return 0, &init_mm) { 174 if (!pmd_free_pte_page(pmd, addr)) 175 return 0; 176 return pmd_set_huge(pmd, phys_addr, prot); 177 } 178 } 179 180 static int vmap_pmd_range(pud_t *pud, unsigned long addr, unsigned long end, 181 phys_addr_t phys_addr, pgprot_t prot, 182 unsigned int max_page_shift, pgtbl_mod_mask *mask) 183 { 184 pmd_t *pmd; 185 unsigned long next; 186 int err = 0; 187 188 pmd = pmd_alloc_track(&init_mm, pud, addr, mask); 189 if (!pmd) 190 return -ENOMEM; 191 do { 192 next = pmd_addr_end(addr, end); 193 194 if (vmap_try_huge_pmd(pmd, addr, next, phys_addr, prot, 195 max_page_shift)) { 196 *mask |= PGTBL_PMD_MODIFIED; 197 continue; 198 } 199 200 err = vmap_pte_range(pmd, addr, next, phys_addr, prot, max_page_shift, mask); 201 if (err) 202 break; 203 } while (pmd++, phys_addr += (next - addr), addr = next, addr != end); 204 return err; 205 } 206 207 static int vmap_try_huge_pud(pud_t *pud, unsigned long addr, unsigned long end, 208 phys_addr_t phys_addr, pgprot_t prot, 209 unsigned int max_page_shift) 210 { 211 if (max_page_shift < PUD_SHIFT) 212 return 0; 213 214 if (!arch_vmap_pud_supported(prot)) 215 return 0; 216 217 if ((end - addr) != PUD_SIZE) 218 return 0; 219 220 if (!IS_ALIGNED(addr, PUD_SIZE)) 221 return 0; 222 223 if (!IS_ALIGNED(phys_addr, PUD_SIZE)) 224 return 0; 225 226 if (!pud_present(*pud)) 227 return pud_set_huge(pud, phys_addr, prot); 228 229 /* See comment in vmap_try_huge_pmd(). */ 230 scoped_cond_guard(mmap_read_lock_try, return 0, &init_mm) { 231 if (!pud_free_pmd_page(pud, addr)) 232 return 0; 233 return pud_set_huge(pud, phys_addr, prot); 234 } 235 } 236 237 static int vmap_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end, 238 phys_addr_t phys_addr, pgprot_t prot, 239 unsigned int max_page_shift, pgtbl_mod_mask *mask) 240 { 241 pud_t *pud; 242 unsigned long next; 243 int err = 0; 244 245 pud = pud_alloc_track(&init_mm, p4d, addr, mask); 246 if (!pud) 247 return -ENOMEM; 248 do { 249 next = pud_addr_end(addr, end); 250 251 if (vmap_try_huge_pud(pud, addr, next, phys_addr, prot, 252 max_page_shift)) { 253 *mask |= PGTBL_PUD_MODIFIED; 254 continue; 255 } 256 257 err = vmap_pmd_range(pud, addr, next, phys_addr, prot, max_page_shift, mask); 258 if (err) 259 break; 260 } while (pud++, phys_addr += (next - addr), addr = next, addr != end); 261 return err; 262 } 263 264 static int vmap_try_huge_p4d(p4d_t *p4d, unsigned long addr, unsigned long end, 265 phys_addr_t phys_addr, pgprot_t prot, 266 unsigned int max_page_shift) 267 { 268 if (max_page_shift < P4D_SHIFT) 269 return 0; 270 271 if (!arch_vmap_p4d_supported(prot)) 272 return 0; 273 274 if ((end - addr) != P4D_SIZE) 275 return 0; 276 277 if (!IS_ALIGNED(addr, P4D_SIZE)) 278 return 0; 279 280 if (!IS_ALIGNED(phys_addr, P4D_SIZE)) 281 return 0; 282 283 if (!p4d_present(*p4d)) 284 return p4d_set_huge(p4d, phys_addr, prot); 285 286 /* See comment in vmap_try_huge_pmd(). */ 287 scoped_cond_guard(mmap_read_lock_try, return 0, &init_mm) { 288 if (!p4d_free_pud_page(p4d, addr)) 289 return 0; 290 return p4d_set_huge(p4d, phys_addr, prot); 291 } 292 } 293 294 static int vmap_p4d_range(pgd_t *pgd, unsigned long addr, unsigned long end, 295 phys_addr_t phys_addr, pgprot_t prot, 296 unsigned int max_page_shift, pgtbl_mod_mask *mask) 297 { 298 p4d_t *p4d; 299 unsigned long next; 300 int err = 0; 301 302 p4d = p4d_alloc_track(&init_mm, pgd, addr, mask); 303 if (!p4d) 304 return -ENOMEM; 305 do { 306 next = p4d_addr_end(addr, end); 307 308 if (vmap_try_huge_p4d(p4d, addr, next, phys_addr, prot, 309 max_page_shift)) { 310 *mask |= PGTBL_P4D_MODIFIED; 311 continue; 312 } 313 314 err = vmap_pud_range(p4d, addr, next, phys_addr, prot, max_page_shift, mask); 315 if (err) 316 break; 317 } while (p4d++, phys_addr += (next - addr), addr = next, addr != end); 318 return err; 319 } 320 321 static int vmap_range_noflush(unsigned long addr, unsigned long end, 322 phys_addr_t phys_addr, pgprot_t prot, 323 unsigned int max_page_shift) 324 { 325 pgd_t *pgd; 326 unsigned long start; 327 unsigned long next; 328 int err; 329 pgtbl_mod_mask mask = 0; 330 331 /* 332 * Might allocate pagetables (for most archs a more precise annotation 333 * would be might_alloc(GFP_PGTABLE_KERNEL)). Also might shootdown TLB 334 * (requires IRQs enabled on x86). 335 */ 336 might_sleep(); 337 BUG_ON(addr >= end); 338 339 start = addr; 340 pgd = pgd_offset_k(addr); 341 do { 342 next = pgd_addr_end(addr, end); 343 err = vmap_p4d_range(pgd, addr, next, phys_addr, prot, 344 max_page_shift, &mask); 345 if (err) 346 break; 347 } while (pgd++, phys_addr += (next - addr), addr = next, addr != end); 348 349 if (mask & ARCH_PAGE_TABLE_SYNC_MASK) 350 arch_sync_kernel_mappings(start, end); 351 352 return err; 353 } 354 355 int vmap_page_range(unsigned long addr, unsigned long end, 356 phys_addr_t phys_addr, pgprot_t prot) 357 { 358 int err; 359 360 err = vmap_range_noflush(addr, end, phys_addr, pgprot_nx(prot), 361 ioremap_max_page_shift); 362 flush_cache_vmap(addr, end); 363 if (!err) 364 err = kmsan_ioremap_page_range(addr, end, phys_addr, prot, 365 ioremap_max_page_shift); 366 return err; 367 } 368 369 int ioremap_page_range(unsigned long addr, unsigned long end, 370 phys_addr_t phys_addr, pgprot_t prot) 371 { 372 struct vm_struct *area; 373 374 area = find_vm_area((void *)addr); 375 if (!area || !(area->flags & VM_IOREMAP)) { 376 WARN_ONCE(1, "vm_area at addr %lx is not marked as VM_IOREMAP\n", addr); 377 return -EINVAL; 378 } 379 if (addr != (unsigned long)area->addr || 380 (void *)end != area->addr + get_vm_area_size(area)) { 381 WARN_ONCE(1, "ioremap request [%lx,%lx) doesn't match vm_area [%lx, %lx)\n", 382 addr, end, (long)area->addr, 383 (long)area->addr + get_vm_area_size(area)); 384 return -ERANGE; 385 } 386 return vmap_page_range(addr, end, phys_addr, prot); 387 } 388 389 static void vunmap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, 390 pgtbl_mod_mask *mask) 391 { 392 pte_t *pte; 393 pte_t ptent; 394 unsigned long size = PAGE_SIZE; 395 396 pte = pte_offset_kernel(pmd, addr); 397 lazy_mmu_mode_enable(); 398 399 do { 400 #ifdef CONFIG_HUGETLB_PAGE 401 size = arch_vmap_pte_range_unmap_size(addr, pte); 402 if (size != PAGE_SIZE) { 403 if (WARN_ON(!IS_ALIGNED(addr, size))) { 404 addr = ALIGN_DOWN(addr, size); 405 pte = PTR_ALIGN_DOWN(pte, sizeof(*pte) * (size >> PAGE_SHIFT)); 406 } 407 ptent = huge_ptep_get_and_clear(&init_mm, addr, pte, size); 408 if (WARN_ON(end - addr < size)) 409 size = end - addr; 410 } else 411 #endif 412 ptent = ptep_get_and_clear(&init_mm, addr, pte); 413 WARN_ON(!pte_none(ptent) && !pte_present(ptent)); 414 } while (pte += (size >> PAGE_SHIFT), addr += size, addr != end); 415 416 lazy_mmu_mode_disable(); 417 *mask |= PGTBL_PTE_MODIFIED; 418 } 419 420 static void vunmap_pmd_range(pud_t *pud, unsigned long addr, unsigned long end, 421 pgtbl_mod_mask *mask) 422 { 423 pmd_t *pmd; 424 unsigned long next; 425 int cleared; 426 427 pmd = pmd_offset(pud, addr); 428 do { 429 next = pmd_addr_end(addr, end); 430 431 cleared = pmd_clear_huge(pmd); 432 if (cleared || pmd_bad(*pmd)) 433 *mask |= PGTBL_PMD_MODIFIED; 434 435 if (cleared) { 436 WARN_ON(next - addr < PMD_SIZE); 437 continue; 438 } 439 if (pmd_none_or_clear_bad(pmd)) 440 continue; 441 vunmap_pte_range(pmd, addr, next, mask); 442 443 cond_resched(); 444 } while (pmd++, addr = next, addr != end); 445 } 446 447 static void vunmap_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end, 448 pgtbl_mod_mask *mask) 449 { 450 pud_t *pud; 451 unsigned long next; 452 int cleared; 453 454 pud = pud_offset(p4d, addr); 455 do { 456 next = pud_addr_end(addr, end); 457 458 cleared = pud_clear_huge(pud); 459 if (cleared || pud_bad(*pud)) 460 *mask |= PGTBL_PUD_MODIFIED; 461 462 if (cleared) { 463 WARN_ON(next - addr < PUD_SIZE); 464 continue; 465 } 466 if (pud_none_or_clear_bad(pud)) 467 continue; 468 vunmap_pmd_range(pud, addr, next, mask); 469 } while (pud++, addr = next, addr != end); 470 } 471 472 static void vunmap_p4d_range(pgd_t *pgd, unsigned long addr, unsigned long end, 473 pgtbl_mod_mask *mask) 474 { 475 p4d_t *p4d; 476 unsigned long next; 477 478 p4d = p4d_offset(pgd, addr); 479 do { 480 next = p4d_addr_end(addr, end); 481 482 p4d_clear_huge(p4d); 483 if (p4d_bad(*p4d)) 484 *mask |= PGTBL_P4D_MODIFIED; 485 486 if (p4d_none_or_clear_bad(p4d)) 487 continue; 488 vunmap_pud_range(p4d, addr, next, mask); 489 } while (p4d++, addr = next, addr != end); 490 } 491 492 /* 493 * vunmap_range_noflush is similar to vunmap_range, but does not 494 * flush caches or TLBs. 495 * 496 * The caller is responsible for calling flush_cache_vmap() before calling 497 * this function, and flush_tlb_kernel_range after it has returned 498 * successfully (and before the addresses are expected to cause a page fault 499 * or be re-mapped for something else, if TLB flushes are being delayed or 500 * coalesced). 501 * 502 * This is an internal function only. Do not use outside mm/. 503 */ 504 void __vunmap_range_noflush(unsigned long start, unsigned long end) 505 { 506 unsigned long next; 507 pgd_t *pgd; 508 unsigned long addr = start; 509 pgtbl_mod_mask mask = 0; 510 511 BUG_ON(addr >= end); 512 pgd = pgd_offset_k(addr); 513 do { 514 next = pgd_addr_end(addr, end); 515 if (pgd_bad(*pgd)) 516 mask |= PGTBL_PGD_MODIFIED; 517 if (pgd_none_or_clear_bad(pgd)) 518 continue; 519 vunmap_p4d_range(pgd, addr, next, &mask); 520 } while (pgd++, addr = next, addr != end); 521 522 if (mask & ARCH_PAGE_TABLE_SYNC_MASK) 523 arch_sync_kernel_mappings(start, end); 524 } 525 526 void vunmap_range_noflush(unsigned long start, unsigned long end) 527 { 528 kmsan_vunmap_range_noflush(start, end); 529 __vunmap_range_noflush(start, end); 530 } 531 532 /** 533 * vunmap_range - unmap kernel virtual addresses 534 * @addr: start of the VM area to unmap 535 * @end: end of the VM area to unmap (non-inclusive) 536 * 537 * Clears any present PTEs in the virtual address range, flushes TLBs and 538 * caches. Any subsequent access to the address before it has been re-mapped 539 * is a kernel bug. 540 */ 541 void vunmap_range(unsigned long addr, unsigned long end) 542 { 543 flush_cache_vunmap(addr, end); 544 vunmap_range_noflush(addr, end); 545 flush_tlb_kernel_range(addr, end); 546 } 547 548 static int vmap_pages_pte_range(pmd_t *pmd, unsigned long addr, 549 unsigned long end, pgprot_t prot, struct page **pages, int *nr, 550 pgtbl_mod_mask *mask) 551 { 552 int err = 0; 553 pte_t *pte; 554 555 /* 556 * nr is a running index into the array which helps higher level 557 * callers keep track of where we're up to. 558 */ 559 560 pte = pte_alloc_kernel_track(pmd, addr, mask); 561 if (!pte) 562 return -ENOMEM; 563 564 lazy_mmu_mode_enable(); 565 566 do { 567 struct page *page = pages[*nr]; 568 569 if (WARN_ON(!pte_none(ptep_get(pte)))) { 570 err = -EBUSY; 571 break; 572 } 573 if (WARN_ON(!page)) { 574 err = -ENOMEM; 575 break; 576 } 577 if (WARN_ON(!pfn_valid(page_to_pfn(page)))) { 578 err = -EINVAL; 579 break; 580 } 581 582 set_pte_at(&init_mm, addr, pte, mk_pte(page, prot)); 583 (*nr)++; 584 } while (pte++, addr += PAGE_SIZE, addr != end); 585 586 lazy_mmu_mode_disable(); 587 *mask |= PGTBL_PTE_MODIFIED; 588 589 return err; 590 } 591 592 static int vmap_pages_pmd_range(pud_t *pud, unsigned long addr, 593 unsigned long end, pgprot_t prot, struct page **pages, int *nr, 594 pgtbl_mod_mask *mask) 595 { 596 pmd_t *pmd; 597 unsigned long next; 598 599 pmd = pmd_alloc_track(&init_mm, pud, addr, mask); 600 if (!pmd) 601 return -ENOMEM; 602 do { 603 next = pmd_addr_end(addr, end); 604 if (vmap_pages_pte_range(pmd, addr, next, prot, pages, nr, mask)) 605 return -ENOMEM; 606 } while (pmd++, addr = next, addr != end); 607 return 0; 608 } 609 610 static int vmap_pages_pud_range(p4d_t *p4d, unsigned long addr, 611 unsigned long end, pgprot_t prot, struct page **pages, int *nr, 612 pgtbl_mod_mask *mask) 613 { 614 pud_t *pud; 615 unsigned long next; 616 617 pud = pud_alloc_track(&init_mm, p4d, addr, mask); 618 if (!pud) 619 return -ENOMEM; 620 do { 621 next = pud_addr_end(addr, end); 622 if (vmap_pages_pmd_range(pud, addr, next, prot, pages, nr, mask)) 623 return -ENOMEM; 624 } while (pud++, addr = next, addr != end); 625 return 0; 626 } 627 628 static int vmap_pages_p4d_range(pgd_t *pgd, unsigned long addr, 629 unsigned long end, pgprot_t prot, struct page **pages, int *nr, 630 pgtbl_mod_mask *mask) 631 { 632 p4d_t *p4d; 633 unsigned long next; 634 635 p4d = p4d_alloc_track(&init_mm, pgd, addr, mask); 636 if (!p4d) 637 return -ENOMEM; 638 do { 639 next = p4d_addr_end(addr, end); 640 if (vmap_pages_pud_range(p4d, addr, next, prot, pages, nr, mask)) 641 return -ENOMEM; 642 } while (p4d++, addr = next, addr != end); 643 return 0; 644 } 645 646 static int vmap_small_pages_range_noflush(unsigned long addr, unsigned long end, 647 pgprot_t prot, struct page **pages) 648 { 649 unsigned long start = addr; 650 pgd_t *pgd; 651 unsigned long next; 652 int err = 0; 653 int nr = 0; 654 pgtbl_mod_mask mask = 0; 655 656 BUG_ON(addr >= end); 657 pgd = pgd_offset_k(addr); 658 do { 659 next = pgd_addr_end(addr, end); 660 if (pgd_bad(*pgd)) 661 mask |= PGTBL_PGD_MODIFIED; 662 err = vmap_pages_p4d_range(pgd, addr, next, prot, pages, &nr, &mask); 663 if (err) 664 break; 665 } while (pgd++, addr = next, addr != end); 666 667 if (mask & ARCH_PAGE_TABLE_SYNC_MASK) 668 arch_sync_kernel_mappings(start, end); 669 670 return err; 671 } 672 673 /* 674 * vmap_pages_range_noflush is similar to vmap_pages_range, but does not 675 * flush caches. 676 * 677 * The caller is responsible for calling flush_cache_vmap() after this 678 * function returns successfully and before the addresses are accessed. 679 * 680 * This is an internal function only. Do not use outside mm/. 681 */ 682 int __vmap_pages_range_noflush(unsigned long addr, unsigned long end, 683 pgprot_t prot, struct page **pages, unsigned int page_shift) 684 { 685 unsigned int i, nr = (end - addr) >> PAGE_SHIFT; 686 687 WARN_ON(page_shift < PAGE_SHIFT); 688 689 if (!IS_ENABLED(CONFIG_HAVE_ARCH_HUGE_VMALLOC) || 690 page_shift == PAGE_SHIFT) 691 return vmap_small_pages_range_noflush(addr, end, prot, pages); 692 693 for (i = 0; i < nr; i += 1U << (page_shift - PAGE_SHIFT)) { 694 int err; 695 696 err = vmap_range_noflush(addr, addr + (1UL << page_shift), 697 page_to_phys(pages[i]), prot, 698 page_shift); 699 if (err) 700 return err; 701 702 addr += 1UL << page_shift; 703 } 704 705 return 0; 706 } 707 708 int vmap_pages_range_noflush(unsigned long addr, unsigned long end, 709 pgprot_t prot, struct page **pages, unsigned int page_shift, 710 gfp_t gfp_mask) 711 { 712 int ret = kmsan_vmap_pages_range_noflush(addr, end, prot, pages, 713 page_shift, gfp_mask); 714 715 if (ret) 716 return ret; 717 return __vmap_pages_range_noflush(addr, end, prot, pages, page_shift); 718 } 719 720 static int __vmap_pages_range(unsigned long addr, unsigned long end, 721 pgprot_t prot, struct page **pages, unsigned int page_shift, 722 gfp_t gfp_mask) 723 { 724 int err; 725 726 err = vmap_pages_range_noflush(addr, end, prot, pages, page_shift, gfp_mask); 727 flush_cache_vmap(addr, end); 728 return err; 729 } 730 731 /** 732 * vmap_pages_range - map pages to a kernel virtual address 733 * @addr: start of the VM area to map 734 * @end: end of the VM area to map (non-inclusive) 735 * @prot: page protection flags to use 736 * @pages: pages to map (always PAGE_SIZE pages) 737 * @page_shift: maximum shift that the pages may be mapped with, @pages must 738 * be aligned and contiguous up to at least this shift. 739 * 740 * RETURNS: 741 * 0 on success, -errno on failure. 742 */ 743 int vmap_pages_range(unsigned long addr, unsigned long end, 744 pgprot_t prot, struct page **pages, unsigned int page_shift) 745 { 746 return __vmap_pages_range(addr, end, prot, pages, page_shift, GFP_KERNEL); 747 } 748 749 static int check_sparse_vm_area(struct vm_struct *area, unsigned long start, 750 unsigned long end) 751 { 752 might_sleep(); 753 if (WARN_ON_ONCE(area->flags & VM_FLUSH_RESET_PERMS)) 754 return -EINVAL; 755 if (WARN_ON_ONCE(area->flags & VM_NO_GUARD)) 756 return -EINVAL; 757 if (WARN_ON_ONCE(!(area->flags & VM_SPARSE))) 758 return -EINVAL; 759 if ((end - start) >> PAGE_SHIFT > totalram_pages()) 760 return -E2BIG; 761 if (start < (unsigned long)area->addr || 762 (void *)end > area->addr + get_vm_area_size(area)) 763 return -ERANGE; 764 return 0; 765 } 766 767 /** 768 * vm_area_map_pages - map pages inside given sparse vm_area 769 * @area: vm_area 770 * @start: start address inside vm_area 771 * @end: end address inside vm_area 772 * @pages: pages to map (always PAGE_SIZE pages) 773 */ 774 int vm_area_map_pages(struct vm_struct *area, unsigned long start, 775 unsigned long end, struct page **pages) 776 { 777 int err; 778 779 err = check_sparse_vm_area(area, start, end); 780 if (err) 781 return err; 782 783 return vmap_pages_range(start, end, PAGE_KERNEL, pages, PAGE_SHIFT); 784 } 785 786 /** 787 * vm_area_unmap_pages - unmap pages inside given sparse vm_area 788 * @area: vm_area 789 * @start: start address inside vm_area 790 * @end: end address inside vm_area 791 */ 792 void vm_area_unmap_pages(struct vm_struct *area, unsigned long start, 793 unsigned long end) 794 { 795 if (check_sparse_vm_area(area, start, end)) 796 return; 797 798 vunmap_range(start, end); 799 } 800 801 int is_vmalloc_or_module_addr(const void *x) 802 { 803 /* 804 * ARM, x86-64 and sparc64 put modules in a special place, 805 * and fall back on vmalloc() if that fails. Others 806 * just put it in the vmalloc space. 807 */ 808 #if defined(CONFIG_EXECMEM) && defined(MODULES_VADDR) 809 unsigned long addr = (unsigned long)kasan_reset_tag(x); 810 if (addr >= MODULES_VADDR && addr < MODULES_END) 811 return 1; 812 #endif 813 return is_vmalloc_addr(x); 814 } 815 EXPORT_SYMBOL_GPL(is_vmalloc_or_module_addr); 816 817 /* 818 * Walk a vmap address to the struct page it maps. Huge vmap mappings will 819 * return the tail page that corresponds to the base page address, which 820 * matches small vmap mappings. 821 */ 822 struct page *vmalloc_to_page(const void *vmalloc_addr) 823 { 824 unsigned long addr = (unsigned long) vmalloc_addr; 825 struct page *page = NULL; 826 pgd_t *pgd = pgd_offset_k(addr); 827 p4d_t *p4d; 828 pud_t *pud; 829 pmd_t *pmd; 830 pte_t *ptep, pte; 831 832 /* 833 * XXX we might need to change this if we add VIRTUAL_BUG_ON for 834 * architectures that do not vmalloc module space 835 */ 836 VIRTUAL_BUG_ON(!is_vmalloc_or_module_addr(vmalloc_addr)); 837 838 if (pgd_none(*pgd)) 839 return NULL; 840 if (WARN_ON_ONCE(pgd_leaf(*pgd))) 841 return NULL; /* XXX: no allowance for huge pgd */ 842 if (WARN_ON_ONCE(pgd_bad(*pgd))) 843 return NULL; 844 845 p4d = p4d_offset(pgd, addr); 846 if (p4d_none(*p4d)) 847 return NULL; 848 if (p4d_leaf(*p4d)) 849 return p4d_page(*p4d) + ((addr & ~P4D_MASK) >> PAGE_SHIFT); 850 if (WARN_ON_ONCE(p4d_bad(*p4d))) 851 return NULL; 852 853 pud = pud_offset(p4d, addr); 854 if (pud_none(*pud)) 855 return NULL; 856 if (pud_leaf(*pud)) 857 return pud_page(*pud) + ((addr & ~PUD_MASK) >> PAGE_SHIFT); 858 if (WARN_ON_ONCE(pud_bad(*pud))) 859 return NULL; 860 861 pmd = pmd_offset(pud, addr); 862 if (pmd_none(*pmd)) 863 return NULL; 864 if (pmd_leaf(*pmd)) 865 return pmd_page(*pmd) + ((addr & ~PMD_MASK) >> PAGE_SHIFT); 866 if (WARN_ON_ONCE(pmd_bad(*pmd))) 867 return NULL; 868 869 ptep = pte_offset_kernel(pmd, addr); 870 pte = ptep_get(ptep); 871 if (pte_present(pte)) 872 page = pte_page(pte); 873 874 return page; 875 } 876 EXPORT_SYMBOL(vmalloc_to_page); 877 878 /* 879 * Map a vmalloc()-space virtual address to the physical page frame number. 880 */ 881 unsigned long vmalloc_to_pfn(const void *vmalloc_addr) 882 { 883 return page_to_pfn(vmalloc_to_page(vmalloc_addr)); 884 } 885 EXPORT_SYMBOL(vmalloc_to_pfn); 886 887 888 /*** Global kva allocator ***/ 889 890 #define DEBUG_AUGMENT_PROPAGATE_CHECK 0 891 #define DEBUG_AUGMENT_LOWEST_MATCH_CHECK 0 892 893 894 static DEFINE_SPINLOCK(free_vmap_area_lock); 895 static bool vmap_initialized __read_mostly; 896 897 /* 898 * This kmem_cache is used for vmap_area objects. Instead of 899 * allocating from slab we reuse an object from this cache to 900 * make things faster. Especially in "no edge" splitting of 901 * free block. 902 */ 903 static struct kmem_cache *vmap_area_cachep; 904 905 /* 906 * This linked list is used in pair with free_vmap_area_root. 907 * It gives O(1) access to prev/next to perform fast coalescing. 908 */ 909 static LIST_HEAD(free_vmap_area_list); 910 911 /* 912 * This augment red-black tree represents the free vmap space. 913 * All vmap_area objects in this tree are sorted by va->va_start 914 * address. It is used for allocation and merging when a vmap 915 * object is released. 916 * 917 * Each vmap_area node contains a maximum available free block 918 * of its sub-tree, right or left. Therefore it is possible to 919 * find a lowest match of free area. 920 */ 921 static struct rb_root free_vmap_area_root = RB_ROOT; 922 923 /* 924 * Preload a CPU with one object for "no edge" split case. The 925 * aim is to get rid of allocations from the atomic context, thus 926 * to use more permissive allocation masks. 927 */ 928 static DEFINE_PER_CPU(struct vmap_area *, ne_fit_preload_node); 929 930 /* 931 * This structure defines a single, solid model where a list and 932 * rb-tree are part of one entity protected by the lock. Nodes are 933 * sorted in ascending order, thus for O(1) access to left/right 934 * neighbors a list is used as well as for sequential traversal. 935 */ 936 struct rb_list { 937 struct rb_root root; 938 struct list_head head; 939 spinlock_t lock; 940 }; 941 942 /* 943 * A fast size storage contains VAs up to 1M size. A pool consists 944 * of linked between each other ready to go VAs of certain sizes. 945 * An index in the pool-array corresponds to number of pages + 1. 946 */ 947 #define MAX_VA_SIZE_PAGES 256 948 949 struct vmap_pool { 950 struct list_head head; 951 unsigned long len; 952 }; 953 954 /* 955 * An effective vmap-node logic. Users make use of nodes instead 956 * of a global heap. It allows to balance an access and mitigate 957 * contention. 958 */ 959 static struct vmap_node { 960 /* Simple size segregated storage. */ 961 struct vmap_pool pool[MAX_VA_SIZE_PAGES]; 962 spinlock_t pool_lock; 963 bool skip_populate; 964 965 /* Bookkeeping data of this node. */ 966 struct rb_list busy; 967 struct rb_list lazy; 968 969 /* 970 * Ready-to-free areas. 971 */ 972 struct list_head purge_list; 973 struct work_struct purge_work; 974 unsigned long nr_purged; 975 } single; 976 977 /* 978 * Initial setup consists of one single node, i.e. a balancing 979 * is fully disabled. Later on, after vmap is initialized these 980 * parameters are updated based on a system capacity. 981 */ 982 static struct vmap_node *vmap_nodes = &single; 983 static __read_mostly unsigned int nr_vmap_nodes = 1; 984 static __read_mostly unsigned int vmap_zone_size = 1; 985 986 /* A simple iterator over all vmap-nodes. */ 987 #define for_each_vmap_node(vn) \ 988 for ((vn) = &vmap_nodes[0]; \ 989 (vn) < &vmap_nodes[nr_vmap_nodes]; (vn)++) 990 991 static inline unsigned int 992 addr_to_node_id(unsigned long addr) 993 { 994 return (addr / vmap_zone_size) % nr_vmap_nodes; 995 } 996 997 static inline struct vmap_node * 998 addr_to_node(unsigned long addr) 999 { 1000 return &vmap_nodes[addr_to_node_id(addr)]; 1001 } 1002 1003 static inline struct vmap_node * 1004 id_to_node(unsigned int id) 1005 { 1006 return &vmap_nodes[id % nr_vmap_nodes]; 1007 } 1008 1009 static inline unsigned int 1010 node_to_id(struct vmap_node *node) 1011 { 1012 /* Pointer arithmetic. */ 1013 unsigned int id = node - vmap_nodes; 1014 1015 if (likely(id < nr_vmap_nodes)) 1016 return id; 1017 1018 WARN_ONCE(1, "An address 0x%p is out-of-bounds.\n", node); 1019 return 0; 1020 } 1021 1022 /* 1023 * We use the value 0 to represent "no node", that is why 1024 * an encoded value will be the node-id incremented by 1. 1025 * It is always greater then 0. A valid node_id which can 1026 * be encoded is [0:nr_vmap_nodes - 1]. If a passed node_id 1027 * is not valid 0 is returned. 1028 */ 1029 static unsigned int 1030 encode_vn_id(unsigned int node_id) 1031 { 1032 /* Can store U8_MAX [0:254] nodes. */ 1033 if (node_id < nr_vmap_nodes) 1034 return (node_id + 1) << BITS_PER_BYTE; 1035 1036 /* Warn and no node encoded. */ 1037 WARN_ONCE(1, "Encode wrong node id (%u)\n", node_id); 1038 return 0; 1039 } 1040 1041 /* 1042 * Returns an encoded node-id, the valid range is within 1043 * [0:nr_vmap_nodes-1] values. Otherwise nr_vmap_nodes is 1044 * returned if extracted data is wrong. 1045 */ 1046 static unsigned int 1047 decode_vn_id(unsigned int val) 1048 { 1049 unsigned int node_id = (val >> BITS_PER_BYTE) - 1; 1050 1051 /* Can store U8_MAX [0:254] nodes. */ 1052 if (node_id < nr_vmap_nodes) 1053 return node_id; 1054 1055 /* If it was _not_ zero, warn. */ 1056 WARN_ONCE(node_id != UINT_MAX, 1057 "Decode wrong node id (%d)\n", node_id); 1058 1059 return nr_vmap_nodes; 1060 } 1061 1062 static bool 1063 is_vn_id_valid(unsigned int node_id) 1064 { 1065 if (node_id < nr_vmap_nodes) 1066 return true; 1067 1068 return false; 1069 } 1070 1071 static __always_inline unsigned long 1072 va_size(struct vmap_area *va) 1073 { 1074 return (va->va_end - va->va_start); 1075 } 1076 1077 static __always_inline unsigned long 1078 get_subtree_max_size(struct rb_node *node) 1079 { 1080 struct vmap_area *va; 1081 1082 va = rb_entry_safe(node, struct vmap_area, rb_node); 1083 return va ? va->subtree_max_size : 0; 1084 } 1085 1086 RB_DECLARE_CALLBACKS_MAX(static, free_vmap_area_rb_augment_cb, 1087 struct vmap_area, rb_node, unsigned long, subtree_max_size, va_size) 1088 1089 static void reclaim_and_purge_vmap_areas(void); 1090 static BLOCKING_NOTIFIER_HEAD(vmap_notify_list); 1091 static void drain_vmap_area_work(struct work_struct *work); 1092 static DECLARE_WORK(drain_vmap_work, drain_vmap_area_work); 1093 1094 static __cacheline_aligned_in_smp atomic_long_t vmap_lazy_nr; 1095 1096 static struct vmap_area *__find_vmap_area(unsigned long addr, struct rb_root *root) 1097 { 1098 struct rb_node *n = root->rb_node; 1099 1100 addr = (unsigned long)kasan_reset_tag((void *)addr); 1101 1102 while (n) { 1103 struct vmap_area *va; 1104 1105 va = rb_entry(n, struct vmap_area, rb_node); 1106 if (addr < va->va_start) 1107 n = n->rb_left; 1108 else if (addr >= va->va_end) 1109 n = n->rb_right; 1110 else 1111 return va; 1112 } 1113 1114 return NULL; 1115 } 1116 1117 /* Look up the first VA which satisfies addr < va_end, NULL if none. */ 1118 static struct vmap_area * 1119 __find_vmap_area_exceed_addr(unsigned long addr, struct rb_root *root) 1120 { 1121 struct vmap_area *va = NULL; 1122 struct rb_node *n = root->rb_node; 1123 1124 addr = (unsigned long)kasan_reset_tag((void *)addr); 1125 1126 while (n) { 1127 struct vmap_area *tmp; 1128 1129 tmp = rb_entry(n, struct vmap_area, rb_node); 1130 if (tmp->va_end > addr) { 1131 va = tmp; 1132 if (tmp->va_start <= addr) 1133 break; 1134 1135 n = n->rb_left; 1136 } else 1137 n = n->rb_right; 1138 } 1139 1140 return va; 1141 } 1142 1143 /* 1144 * Returns a node where a first VA, that satisfies addr < va_end, resides. 1145 * If success, a node is locked. A user is responsible to unlock it when a 1146 * VA is no longer needed to be accessed. 1147 * 1148 * Returns NULL if nothing found. 1149 */ 1150 static struct vmap_node * 1151 find_vmap_area_exceed_addr_lock(unsigned long addr, struct vmap_area **va) 1152 { 1153 unsigned long va_start_lowest; 1154 struct vmap_node *vn; 1155 1156 repeat: 1157 va_start_lowest = 0; 1158 1159 for_each_vmap_node(vn) { 1160 spin_lock(&vn->busy.lock); 1161 *va = __find_vmap_area_exceed_addr(addr, &vn->busy.root); 1162 1163 if (*va) 1164 if (!va_start_lowest || (*va)->va_start < va_start_lowest) 1165 va_start_lowest = (*va)->va_start; 1166 spin_unlock(&vn->busy.lock); 1167 } 1168 1169 /* 1170 * Check if found VA exists, it might have gone away. In this case we 1171 * repeat the search because a VA has been removed concurrently and we 1172 * need to proceed to the next one, which is a rare case. 1173 */ 1174 if (va_start_lowest) { 1175 vn = addr_to_node(va_start_lowest); 1176 1177 spin_lock(&vn->busy.lock); 1178 *va = __find_vmap_area(va_start_lowest, &vn->busy.root); 1179 1180 if (*va) 1181 return vn; 1182 1183 spin_unlock(&vn->busy.lock); 1184 goto repeat; 1185 } 1186 1187 return NULL; 1188 } 1189 1190 /* 1191 * This function returns back addresses of parent node 1192 * and its left or right link for further processing. 1193 * 1194 * Otherwise NULL is returned. In that case all further 1195 * steps regarding inserting of conflicting overlap range 1196 * have to be declined and actually considered as a bug. 1197 */ 1198 static __always_inline struct rb_node ** 1199 find_va_links(struct vmap_area *va, 1200 struct rb_root *root, struct rb_node *from, 1201 struct rb_node **parent) 1202 { 1203 struct vmap_area *tmp_va; 1204 struct rb_node **link; 1205 1206 if (root) { 1207 link = &root->rb_node; 1208 if (unlikely(!*link)) { 1209 *parent = NULL; 1210 return link; 1211 } 1212 } else { 1213 link = &from; 1214 } 1215 1216 /* 1217 * Go to the bottom of the tree. When we hit the last point 1218 * we end up with parent rb_node and correct direction, i name 1219 * it link, where the new va->rb_node will be attached to. 1220 */ 1221 do { 1222 tmp_va = rb_entry(*link, struct vmap_area, rb_node); 1223 1224 /* 1225 * During the traversal we also do some sanity check. 1226 * Trigger the BUG() if there are sides(left/right) 1227 * or full overlaps. 1228 */ 1229 if (va->va_end <= tmp_va->va_start) 1230 link = &(*link)->rb_left; 1231 else if (va->va_start >= tmp_va->va_end) 1232 link = &(*link)->rb_right; 1233 else { 1234 WARN(1, "vmalloc bug: 0x%lx-0x%lx overlaps with 0x%lx-0x%lx\n", 1235 va->va_start, va->va_end, tmp_va->va_start, tmp_va->va_end); 1236 1237 return NULL; 1238 } 1239 } while (*link); 1240 1241 *parent = &tmp_va->rb_node; 1242 return link; 1243 } 1244 1245 static __always_inline struct list_head * 1246 get_va_next_sibling(struct rb_node *parent, struct rb_node **link) 1247 { 1248 struct list_head *list; 1249 1250 if (unlikely(!parent)) 1251 /* 1252 * The red-black tree where we try to find VA neighbors 1253 * before merging or inserting is empty, i.e. it means 1254 * there is no free vmap space. Normally it does not 1255 * happen but we handle this case anyway. 1256 */ 1257 return NULL; 1258 1259 list = &rb_entry(parent, struct vmap_area, rb_node)->list; 1260 return (&parent->rb_right == link ? list->next : list); 1261 } 1262 1263 static __always_inline void 1264 __link_va(struct vmap_area *va, struct rb_root *root, 1265 struct rb_node *parent, struct rb_node **link, 1266 struct list_head *head, bool augment) 1267 { 1268 /* 1269 * VA is still not in the list, but we can 1270 * identify its future previous list_head node. 1271 */ 1272 if (likely(parent)) { 1273 head = &rb_entry(parent, struct vmap_area, rb_node)->list; 1274 if (&parent->rb_right != link) 1275 head = head->prev; 1276 } 1277 1278 /* Insert to the rb-tree */ 1279 rb_link_node(&va->rb_node, parent, link); 1280 if (augment) { 1281 /* 1282 * Some explanation here. Just perform simple insertion 1283 * to the tree. We do not set va->subtree_max_size to 1284 * its current size before calling rb_insert_augmented(). 1285 * It is because we populate the tree from the bottom 1286 * to parent levels when the node _is_ in the tree. 1287 * 1288 * Therefore we set subtree_max_size to zero after insertion, 1289 * to let __augment_tree_propagate_from() puts everything to 1290 * the correct order later on. 1291 */ 1292 rb_insert_augmented(&va->rb_node, 1293 root, &free_vmap_area_rb_augment_cb); 1294 va->subtree_max_size = 0; 1295 } else { 1296 rb_insert_color(&va->rb_node, root); 1297 } 1298 1299 /* Address-sort this list */ 1300 list_add(&va->list, head); 1301 } 1302 1303 static __always_inline void 1304 link_va(struct vmap_area *va, struct rb_root *root, 1305 struct rb_node *parent, struct rb_node **link, 1306 struct list_head *head) 1307 { 1308 __link_va(va, root, parent, link, head, false); 1309 } 1310 1311 static __always_inline void 1312 link_va_augment(struct vmap_area *va, struct rb_root *root, 1313 struct rb_node *parent, struct rb_node **link, 1314 struct list_head *head) 1315 { 1316 __link_va(va, root, parent, link, head, true); 1317 } 1318 1319 static __always_inline void 1320 __unlink_va(struct vmap_area *va, struct rb_root *root, bool augment) 1321 { 1322 if (WARN_ON(RB_EMPTY_NODE(&va->rb_node))) 1323 return; 1324 1325 if (augment) 1326 rb_erase_augmented(&va->rb_node, 1327 root, &free_vmap_area_rb_augment_cb); 1328 else 1329 rb_erase(&va->rb_node, root); 1330 1331 list_del_init(&va->list); 1332 RB_CLEAR_NODE(&va->rb_node); 1333 } 1334 1335 static __always_inline void 1336 unlink_va(struct vmap_area *va, struct rb_root *root) 1337 { 1338 __unlink_va(va, root, false); 1339 } 1340 1341 static __always_inline void 1342 unlink_va_augment(struct vmap_area *va, struct rb_root *root) 1343 { 1344 __unlink_va(va, root, true); 1345 } 1346 1347 #if DEBUG_AUGMENT_PROPAGATE_CHECK 1348 /* 1349 * Gets called when remove the node and rotate. 1350 */ 1351 static __always_inline unsigned long 1352 compute_subtree_max_size(struct vmap_area *va) 1353 { 1354 return max3(va_size(va), 1355 get_subtree_max_size(va->rb_node.rb_left), 1356 get_subtree_max_size(va->rb_node.rb_right)); 1357 } 1358 1359 static void 1360 augment_tree_propagate_check(void) 1361 { 1362 struct vmap_area *va; 1363 unsigned long computed_size; 1364 1365 list_for_each_entry(va, &free_vmap_area_list, list) { 1366 computed_size = compute_subtree_max_size(va); 1367 if (computed_size != va->subtree_max_size) 1368 pr_emerg("tree is corrupted: %lu, %lu\n", 1369 va_size(va), va->subtree_max_size); 1370 } 1371 } 1372 #endif 1373 1374 /* 1375 * This function populates subtree_max_size from bottom to upper 1376 * levels starting from VA point. The propagation must be done 1377 * when VA size is modified by changing its va_start/va_end. Or 1378 * in case of newly inserting of VA to the tree. 1379 * 1380 * It means that __augment_tree_propagate_from() must be called: 1381 * - After VA has been inserted to the tree(free path); 1382 * - After VA has been shrunk(allocation path); 1383 * - After VA has been increased(merging path). 1384 * 1385 * Please note that, it does not mean that upper parent nodes 1386 * and their subtree_max_size are recalculated all the time up 1387 * to the root node. 1388 * 1389 * 4--8 1390 * /\ 1391 * / \ 1392 * / \ 1393 * 2--2 8--8 1394 * 1395 * For example if we modify the node 4, shrinking it to 2, then 1396 * no any modification is required. If we shrink the node 2 to 1 1397 * its subtree_max_size is updated only, and set to 1. If we shrink 1398 * the node 8 to 6, then its subtree_max_size is set to 6 and parent 1399 * node becomes 4--6. 1400 */ 1401 static __always_inline void 1402 augment_tree_propagate_from(struct vmap_area *va) 1403 { 1404 /* 1405 * Populate the tree from bottom towards the root until 1406 * the calculated maximum available size of checked node 1407 * is equal to its current one. 1408 */ 1409 free_vmap_area_rb_augment_cb_propagate(&va->rb_node, NULL); 1410 1411 #if DEBUG_AUGMENT_PROPAGATE_CHECK 1412 augment_tree_propagate_check(); 1413 #endif 1414 } 1415 1416 static void 1417 insert_vmap_area(struct vmap_area *va, 1418 struct rb_root *root, struct list_head *head) 1419 { 1420 struct rb_node **link; 1421 struct rb_node *parent; 1422 1423 link = find_va_links(va, root, NULL, &parent); 1424 if (link) 1425 link_va(va, root, parent, link, head); 1426 } 1427 1428 static void 1429 insert_vmap_area_augment(struct vmap_area *va, 1430 struct rb_node *from, struct rb_root *root, 1431 struct list_head *head) 1432 { 1433 struct rb_node **link; 1434 struct rb_node *parent; 1435 1436 if (from) 1437 link = find_va_links(va, NULL, from, &parent); 1438 else 1439 link = find_va_links(va, root, NULL, &parent); 1440 1441 if (link) { 1442 link_va_augment(va, root, parent, link, head); 1443 augment_tree_propagate_from(va); 1444 } 1445 } 1446 1447 /* 1448 * Merge de-allocated chunk of VA memory with previous 1449 * and next free blocks. If coalesce is not done a new 1450 * free area is inserted. If VA has been merged, it is 1451 * freed. 1452 * 1453 * Please note, it can return NULL in case of overlap 1454 * ranges, followed by WARN() report. Despite it is a 1455 * buggy behaviour, a system can be alive and keep 1456 * ongoing. 1457 */ 1458 static __always_inline struct vmap_area * 1459 __merge_or_add_vmap_area(struct vmap_area *va, 1460 struct rb_root *root, struct list_head *head, bool augment) 1461 { 1462 struct vmap_area *sibling; 1463 struct list_head *next; 1464 struct rb_node **link; 1465 struct rb_node *parent; 1466 bool merged = false; 1467 1468 /* 1469 * Find a place in the tree where VA potentially will be 1470 * inserted, unless it is merged with its sibling/siblings. 1471 */ 1472 link = find_va_links(va, root, NULL, &parent); 1473 if (!link) 1474 return NULL; 1475 1476 /* 1477 * Get next node of VA to check if merging can be done. 1478 */ 1479 next = get_va_next_sibling(parent, link); 1480 if (unlikely(next == NULL)) 1481 goto insert; 1482 1483 /* 1484 * start end 1485 * | | 1486 * |<------VA------>|<-----Next----->| 1487 * | | 1488 * start end 1489 */ 1490 if (next != head) { 1491 sibling = list_entry(next, struct vmap_area, list); 1492 if (sibling->va_start == va->va_end) { 1493 sibling->va_start = va->va_start; 1494 1495 /* Free vmap_area object. */ 1496 kmem_cache_free(vmap_area_cachep, va); 1497 1498 /* Point to the new merged area. */ 1499 va = sibling; 1500 merged = true; 1501 } 1502 } 1503 1504 /* 1505 * start end 1506 * | | 1507 * |<-----Prev----->|<------VA------>| 1508 * | | 1509 * start end 1510 */ 1511 if (next->prev != head) { 1512 sibling = list_entry(next->prev, struct vmap_area, list); 1513 if (sibling->va_end == va->va_start) { 1514 /* 1515 * If both neighbors are coalesced, it is important 1516 * to unlink the "next" node first, followed by merging 1517 * with "previous" one. Otherwise the tree might not be 1518 * fully populated if a sibling's augmented value is 1519 * "normalized" because of rotation operations. 1520 */ 1521 if (merged) 1522 __unlink_va(va, root, augment); 1523 1524 sibling->va_end = va->va_end; 1525 1526 /* Free vmap_area object. */ 1527 kmem_cache_free(vmap_area_cachep, va); 1528 1529 /* Point to the new merged area. */ 1530 va = sibling; 1531 merged = true; 1532 } 1533 } 1534 1535 insert: 1536 if (!merged) 1537 __link_va(va, root, parent, link, head, augment); 1538 1539 return va; 1540 } 1541 1542 static __always_inline struct vmap_area * 1543 merge_or_add_vmap_area(struct vmap_area *va, 1544 struct rb_root *root, struct list_head *head) 1545 { 1546 return __merge_or_add_vmap_area(va, root, head, false); 1547 } 1548 1549 static __always_inline struct vmap_area * 1550 merge_or_add_vmap_area_augment(struct vmap_area *va, 1551 struct rb_root *root, struct list_head *head) 1552 { 1553 va = __merge_or_add_vmap_area(va, root, head, true); 1554 if (va) 1555 augment_tree_propagate_from(va); 1556 1557 return va; 1558 } 1559 1560 static __always_inline bool 1561 is_within_this_va(struct vmap_area *va, unsigned long size, 1562 unsigned long align, unsigned long vstart) 1563 { 1564 unsigned long nva_start_addr; 1565 1566 if (va->va_start > vstart) 1567 nva_start_addr = ALIGN(va->va_start, align); 1568 else 1569 nva_start_addr = ALIGN(vstart, align); 1570 1571 /* Can be overflowed due to big size or alignment. */ 1572 if (nva_start_addr + size < nva_start_addr || 1573 nva_start_addr < vstart) 1574 return false; 1575 1576 return (nva_start_addr + size <= va->va_end); 1577 } 1578 1579 /* 1580 * Find the first free block(lowest start address) in the tree, 1581 * that will accomplish the request corresponding to passing 1582 * parameters. Please note, with an alignment bigger than PAGE_SIZE, 1583 * a search length is adjusted to account for worst case alignment 1584 * overhead. 1585 */ 1586 static __always_inline struct vmap_area * 1587 find_vmap_lowest_match(struct rb_root *root, unsigned long size, 1588 unsigned long align, unsigned long vstart, bool adjust_search_size) 1589 { 1590 struct vmap_area *va; 1591 struct rb_node *node; 1592 unsigned long length; 1593 1594 /* Start from the root. */ 1595 node = root->rb_node; 1596 1597 /* Adjust the search size for alignment overhead. */ 1598 length = adjust_search_size ? size + align - 1 : size; 1599 1600 while (node) { 1601 va = rb_entry(node, struct vmap_area, rb_node); 1602 1603 if (get_subtree_max_size(node->rb_left) >= length && 1604 vstart < va->va_start) { 1605 node = node->rb_left; 1606 } else { 1607 if (is_within_this_va(va, size, align, vstart)) 1608 return va; 1609 1610 /* 1611 * Does not make sense to go deeper towards the right 1612 * sub-tree if it does not have a free block that is 1613 * equal or bigger to the requested search length. 1614 */ 1615 if (get_subtree_max_size(node->rb_right) >= length) { 1616 node = node->rb_right; 1617 continue; 1618 } 1619 1620 /* 1621 * OK. We roll back and find the first right sub-tree, 1622 * that will satisfy the search criteria. It can happen 1623 * due to "vstart" restriction or an alignment overhead 1624 * that is bigger then PAGE_SIZE. 1625 */ 1626 while ((node = rb_parent(node))) { 1627 va = rb_entry(node, struct vmap_area, rb_node); 1628 if (is_within_this_va(va, size, align, vstart)) 1629 return va; 1630 1631 if (get_subtree_max_size(node->rb_right) >= length && 1632 vstart <= va->va_start) { 1633 /* 1634 * Shift the vstart forward. Please note, we update it with 1635 * parent's start address adding "1" because we do not want 1636 * to enter same sub-tree after it has already been checked 1637 * and no suitable free block found there. 1638 */ 1639 vstart = va->va_start + 1; 1640 node = node->rb_right; 1641 break; 1642 } 1643 } 1644 } 1645 } 1646 1647 return NULL; 1648 } 1649 1650 #if DEBUG_AUGMENT_LOWEST_MATCH_CHECK 1651 #include <linux/random.h> 1652 1653 static struct vmap_area * 1654 find_vmap_lowest_linear_match(struct list_head *head, unsigned long size, 1655 unsigned long align, unsigned long vstart) 1656 { 1657 struct vmap_area *va; 1658 1659 list_for_each_entry(va, head, list) { 1660 if (!is_within_this_va(va, size, align, vstart)) 1661 continue; 1662 1663 return va; 1664 } 1665 1666 return NULL; 1667 } 1668 1669 static void 1670 find_vmap_lowest_match_check(struct rb_root *root, struct list_head *head, 1671 unsigned long size, unsigned long align) 1672 { 1673 struct vmap_area *va_1, *va_2; 1674 unsigned long vstart; 1675 unsigned int rnd; 1676 1677 get_random_bytes(&rnd, sizeof(rnd)); 1678 vstart = VMALLOC_START + rnd; 1679 1680 va_1 = find_vmap_lowest_match(root, size, align, vstart, false); 1681 va_2 = find_vmap_lowest_linear_match(head, size, align, vstart); 1682 1683 if (va_1 != va_2) 1684 pr_emerg("not lowest: t: 0x%p, l: 0x%p, v: 0x%lx\n", 1685 va_1, va_2, vstart); 1686 } 1687 #endif 1688 1689 enum fit_type { 1690 NOTHING_FIT = 0, 1691 FL_FIT_TYPE = 1, /* full fit */ 1692 LE_FIT_TYPE = 2, /* left edge fit */ 1693 RE_FIT_TYPE = 3, /* right edge fit */ 1694 NE_FIT_TYPE = 4 /* no edge fit */ 1695 }; 1696 1697 static __always_inline enum fit_type 1698 classify_va_fit_type(struct vmap_area *va, 1699 unsigned long nva_start_addr, unsigned long size) 1700 { 1701 enum fit_type type; 1702 1703 /* Check if it is within VA. */ 1704 if (nva_start_addr < va->va_start || 1705 nva_start_addr + size > va->va_end) 1706 return NOTHING_FIT; 1707 1708 /* Now classify. */ 1709 if (va->va_start == nva_start_addr) { 1710 if (va->va_end == nva_start_addr + size) 1711 type = FL_FIT_TYPE; 1712 else 1713 type = LE_FIT_TYPE; 1714 } else if (va->va_end == nva_start_addr + size) { 1715 type = RE_FIT_TYPE; 1716 } else { 1717 type = NE_FIT_TYPE; 1718 } 1719 1720 return type; 1721 } 1722 1723 static __always_inline int 1724 va_clip(struct rb_root *root, struct list_head *head, 1725 struct vmap_area *va, unsigned long nva_start_addr, 1726 unsigned long size) 1727 { 1728 struct vmap_area *lva = NULL; 1729 enum fit_type type = classify_va_fit_type(va, nva_start_addr, size); 1730 1731 if (type == FL_FIT_TYPE) { 1732 /* 1733 * No need to split VA, it fully fits. 1734 * 1735 * | | 1736 * V NVA V 1737 * |---------------| 1738 */ 1739 unlink_va_augment(va, root); 1740 kmem_cache_free(vmap_area_cachep, va); 1741 } else if (type == LE_FIT_TYPE) { 1742 /* 1743 * Split left edge of fit VA. 1744 * 1745 * | | 1746 * V NVA V R 1747 * |-------|-------| 1748 */ 1749 va->va_start += size; 1750 } else if (type == RE_FIT_TYPE) { 1751 /* 1752 * Split right edge of fit VA. 1753 * 1754 * | | 1755 * L V NVA V 1756 * |-------|-------| 1757 */ 1758 va->va_end = nva_start_addr; 1759 } else if (type == NE_FIT_TYPE) { 1760 /* 1761 * Split no edge of fit VA. 1762 * 1763 * | | 1764 * L V NVA V R 1765 * |---|-------|---| 1766 */ 1767 lva = __this_cpu_xchg(ne_fit_preload_node, NULL); 1768 if (unlikely(!lva)) { 1769 /* 1770 * For percpu allocator we do not do any pre-allocation 1771 * and leave it as it is. The reason is it most likely 1772 * never ends up with NE_FIT_TYPE splitting. In case of 1773 * percpu allocations offsets and sizes are aligned to 1774 * fixed align request, i.e. RE_FIT_TYPE and FL_FIT_TYPE 1775 * are its main fitting cases. 1776 * 1777 * There are a few exceptions though, as an example it is 1778 * a first allocation (early boot up) when we have "one" 1779 * big free space that has to be split. 1780 * 1781 * Also we can hit this path in case of regular "vmap" 1782 * allocations, if "this" current CPU was not preloaded. 1783 * See the comment in alloc_vmap_area() why. If so, then 1784 * GFP_NOWAIT is used instead to get an extra object for 1785 * split purpose. That is rare and most time does not 1786 * occur. 1787 * 1788 * What happens if an allocation gets failed. Basically, 1789 * an "overflow" path is triggered to purge lazily freed 1790 * areas to free some memory, then, the "retry" path is 1791 * triggered to repeat one more time. See more details 1792 * in alloc_vmap_area() function. 1793 */ 1794 lva = kmem_cache_alloc(vmap_area_cachep, GFP_NOWAIT); 1795 if (!lva) 1796 return -ENOMEM; 1797 } 1798 1799 /* 1800 * Build the remainder. 1801 */ 1802 lva->va_start = va->va_start; 1803 lva->va_end = nva_start_addr; 1804 1805 /* 1806 * Shrink this VA to remaining size. 1807 */ 1808 va->va_start = nva_start_addr + size; 1809 } else { 1810 return -EINVAL; 1811 } 1812 1813 if (type != FL_FIT_TYPE) { 1814 augment_tree_propagate_from(va); 1815 1816 if (lva) /* type == NE_FIT_TYPE */ 1817 insert_vmap_area_augment(lva, &va->rb_node, root, head); 1818 } 1819 1820 return 0; 1821 } 1822 1823 static unsigned long 1824 va_alloc(struct vmap_area *va, 1825 struct rb_root *root, struct list_head *head, 1826 unsigned long size, unsigned long align, 1827 unsigned long vstart, unsigned long vend) 1828 { 1829 unsigned long nva_start_addr; 1830 int ret; 1831 1832 if (va->va_start > vstart) 1833 nva_start_addr = ALIGN(va->va_start, align); 1834 else 1835 nva_start_addr = ALIGN(vstart, align); 1836 1837 /* Check the "vend" restriction. */ 1838 if (nva_start_addr + size > vend) 1839 return -ERANGE; 1840 1841 /* Update the free vmap_area. */ 1842 ret = va_clip(root, head, va, nva_start_addr, size); 1843 if (WARN_ON_ONCE(ret)) 1844 return ret; 1845 1846 return nva_start_addr; 1847 } 1848 1849 /* 1850 * Returns a start address of the newly allocated area, if success. 1851 * Otherwise an error value is returned that indicates failure. 1852 */ 1853 static __always_inline unsigned long 1854 __alloc_vmap_area(struct rb_root *root, struct list_head *head, 1855 unsigned long size, unsigned long align, 1856 unsigned long vstart, unsigned long vend) 1857 { 1858 bool adjust_search_size = true; 1859 unsigned long nva_start_addr; 1860 struct vmap_area *va; 1861 1862 /* 1863 * Do not adjust when: 1864 * a) align <= PAGE_SIZE, because it does not make any sense. 1865 * All blocks(their start addresses) are at least PAGE_SIZE 1866 * aligned anyway; 1867 * b) a short range where a requested size corresponds to exactly 1868 * specified [vstart:vend] interval and an alignment > PAGE_SIZE. 1869 * With adjusted search length an allocation would not succeed. 1870 */ 1871 if (align <= PAGE_SIZE || (align > PAGE_SIZE && (vend - vstart) == size)) 1872 adjust_search_size = false; 1873 1874 va = find_vmap_lowest_match(root, size, align, vstart, adjust_search_size); 1875 if (unlikely(!va)) 1876 return -ENOENT; 1877 1878 nva_start_addr = va_alloc(va, root, head, size, align, vstart, vend); 1879 1880 #if DEBUG_AUGMENT_LOWEST_MATCH_CHECK 1881 if (!IS_ERR_VALUE(nva_start_addr)) 1882 find_vmap_lowest_match_check(root, head, size, align); 1883 #endif 1884 1885 return nva_start_addr; 1886 } 1887 1888 /* 1889 * Free a region of KVA allocated by alloc_vmap_area 1890 */ 1891 static void free_vmap_area(struct vmap_area *va) 1892 { 1893 struct vmap_node *vn = addr_to_node(va->va_start); 1894 1895 /* 1896 * Remove from the busy tree/list. 1897 */ 1898 spin_lock(&vn->busy.lock); 1899 unlink_va(va, &vn->busy.root); 1900 spin_unlock(&vn->busy.lock); 1901 1902 /* 1903 * Insert/Merge it back to the free tree/list. 1904 */ 1905 spin_lock(&free_vmap_area_lock); 1906 merge_or_add_vmap_area_augment(va, &free_vmap_area_root, &free_vmap_area_list); 1907 spin_unlock(&free_vmap_area_lock); 1908 } 1909 1910 static inline void 1911 preload_this_cpu_lock(spinlock_t *lock, gfp_t gfp_mask, int node) 1912 { 1913 struct vmap_area *va = NULL, *tmp; 1914 1915 /* 1916 * Preload this CPU with one extra vmap_area object. It is used 1917 * when fit type of free area is NE_FIT_TYPE. It guarantees that 1918 * a CPU that does an allocation is preloaded. 1919 * 1920 * We do it in non-atomic context, thus it allows us to use more 1921 * permissive allocation masks to be more stable under low memory 1922 * condition and high memory pressure. 1923 */ 1924 if (!this_cpu_read(ne_fit_preload_node)) 1925 va = kmem_cache_alloc_node(vmap_area_cachep, gfp_mask, node); 1926 1927 spin_lock(lock); 1928 1929 tmp = NULL; 1930 if (va && !__this_cpu_try_cmpxchg(ne_fit_preload_node, &tmp, va)) 1931 kmem_cache_free(vmap_area_cachep, va); 1932 } 1933 1934 static struct vmap_pool * 1935 size_to_va_pool(struct vmap_node *vn, unsigned long size) 1936 { 1937 unsigned int idx = (size - 1) / PAGE_SIZE; 1938 1939 if (idx < MAX_VA_SIZE_PAGES) 1940 return &vn->pool[idx]; 1941 1942 return NULL; 1943 } 1944 1945 static bool 1946 node_pool_add_va(struct vmap_node *n, struct vmap_area *va) 1947 { 1948 struct vmap_pool *vp; 1949 1950 vp = size_to_va_pool(n, va_size(va)); 1951 if (!vp) 1952 return false; 1953 1954 spin_lock(&n->pool_lock); 1955 list_add(&va->list, &vp->head); 1956 WRITE_ONCE(vp->len, vp->len + 1); 1957 spin_unlock(&n->pool_lock); 1958 1959 return true; 1960 } 1961 1962 static struct vmap_area * 1963 node_pool_del_va(struct vmap_node *vn, unsigned long size, 1964 unsigned long align, unsigned long vstart, 1965 unsigned long vend) 1966 { 1967 struct vmap_area *va = NULL; 1968 struct vmap_pool *vp; 1969 int err = 0; 1970 1971 vp = size_to_va_pool(vn, size); 1972 if (!vp || list_empty(&vp->head)) 1973 return NULL; 1974 1975 spin_lock(&vn->pool_lock); 1976 if (!list_empty(&vp->head)) { 1977 va = list_first_entry(&vp->head, struct vmap_area, list); 1978 1979 if (IS_ALIGNED(va->va_start, align)) { 1980 /* 1981 * Do some sanity check and emit a warning 1982 * if one of below checks detects an error. 1983 */ 1984 err |= (va_size(va) != size); 1985 err |= (va->va_start < vstart); 1986 err |= (va->va_end > vend); 1987 1988 if (!WARN_ON_ONCE(err)) { 1989 list_del_init(&va->list); 1990 WRITE_ONCE(vp->len, vp->len - 1); 1991 } else { 1992 va = NULL; 1993 } 1994 } else { 1995 list_move_tail(&va->list, &vp->head); 1996 va = NULL; 1997 } 1998 } 1999 spin_unlock(&vn->pool_lock); 2000 2001 return va; 2002 } 2003 2004 static struct vmap_area * 2005 node_alloc(unsigned long size, unsigned long align, 2006 unsigned long vstart, unsigned long vend, 2007 unsigned long *addr, unsigned int *vn_id) 2008 { 2009 struct vmap_area *va; 2010 2011 *vn_id = 0; 2012 *addr = -EINVAL; 2013 2014 /* 2015 * Fallback to a global heap if not vmalloc or there 2016 * is only one node. 2017 */ 2018 if (vstart != VMALLOC_START || vend != VMALLOC_END || 2019 nr_vmap_nodes == 1) 2020 return NULL; 2021 2022 *vn_id = raw_smp_processor_id() % nr_vmap_nodes; 2023 va = node_pool_del_va(id_to_node(*vn_id), size, align, vstart, vend); 2024 *vn_id = encode_vn_id(*vn_id); 2025 2026 if (va) 2027 *addr = va->va_start; 2028 2029 return va; 2030 } 2031 2032 static inline void setup_vmalloc_vm(struct vm_struct *vm, 2033 struct vmap_area *va, unsigned long flags, const void *caller) 2034 { 2035 vm->flags = flags; 2036 vm->addr = (void *)va->va_start; 2037 vm->size = vm->requested_size = va_size(va); 2038 vm->caller = caller; 2039 va->vm = vm; 2040 } 2041 2042 /* 2043 * Allocate a region of KVA of the specified size and alignment, within the 2044 * vstart and vend. If vm is passed in, the two will also be bound. 2045 */ 2046 static struct vmap_area *alloc_vmap_area(unsigned long size, 2047 unsigned long align, 2048 unsigned long vstart, unsigned long vend, 2049 int node, gfp_t gfp_mask, 2050 unsigned long va_flags, struct vm_struct *vm) 2051 { 2052 struct vmap_node *vn; 2053 struct vmap_area *va; 2054 unsigned long freed; 2055 unsigned long addr; 2056 unsigned int vn_id; 2057 bool allow_block; 2058 int purged = 0; 2059 int ret; 2060 2061 if (unlikely(!size || offset_in_page(size) || !is_power_of_2(align))) 2062 return ERR_PTR(-EINVAL); 2063 2064 if (unlikely(!vmap_initialized)) 2065 return ERR_PTR(-EBUSY); 2066 2067 /* Only reclaim behaviour flags are relevant. */ 2068 gfp_mask = gfp_mask & GFP_RECLAIM_MASK; 2069 allow_block = gfpflags_allow_blocking(gfp_mask); 2070 might_sleep_if(allow_block); 2071 2072 /* 2073 * If a VA is obtained from a global heap(if it fails here) 2074 * it is anyway marked with this "vn_id" so it is returned 2075 * to this pool's node later. Such way gives a possibility 2076 * to populate pools based on users demand. 2077 * 2078 * On success a ready to go VA is returned. 2079 */ 2080 va = node_alloc(size, align, vstart, vend, &addr, &vn_id); 2081 if (!va) { 2082 va = kmem_cache_alloc_node(vmap_area_cachep, gfp_mask, node); 2083 if (unlikely(!va)) 2084 return ERR_PTR(-ENOMEM); 2085 2086 /* 2087 * Only scan the relevant parts containing pointers to other objects 2088 * to avoid false negatives. 2089 */ 2090 kmemleak_scan_area(&va->rb_node, SIZE_MAX, gfp_mask); 2091 } 2092 2093 retry: 2094 if (IS_ERR_VALUE(addr)) { 2095 preload_this_cpu_lock(&free_vmap_area_lock, gfp_mask, node); 2096 addr = __alloc_vmap_area(&free_vmap_area_root, &free_vmap_area_list, 2097 size, align, vstart, vend); 2098 spin_unlock(&free_vmap_area_lock); 2099 2100 /* 2101 * This is not a fast path. Check if yielding is needed. This 2102 * is the only reschedule point in the vmalloc() path. 2103 */ 2104 if (allow_block) 2105 cond_resched(); 2106 } 2107 2108 trace_alloc_vmap_area(addr, size, align, vstart, vend, IS_ERR_VALUE(addr)); 2109 2110 /* 2111 * If an allocation fails, the error value is 2112 * returned. Therefore trigger the overflow path. 2113 */ 2114 if (IS_ERR_VALUE(addr)) { 2115 if (allow_block) 2116 goto overflow; 2117 2118 /* 2119 * We can not trigger any reclaim logic because 2120 * sleeping is not allowed, thus fail an allocation. 2121 */ 2122 goto out_free_va; 2123 } 2124 2125 va->va_start = addr; 2126 va->va_end = addr + size; 2127 va->vm = NULL; 2128 va->flags = (va_flags | vn_id); 2129 2130 if (vm) { 2131 vm->addr = (void *)va->va_start; 2132 vm->size = va_size(va); 2133 va->vm = vm; 2134 } 2135 2136 vn = addr_to_node(va->va_start); 2137 2138 spin_lock(&vn->busy.lock); 2139 insert_vmap_area(va, &vn->busy.root, &vn->busy.head); 2140 spin_unlock(&vn->busy.lock); 2141 2142 BUG_ON(!IS_ALIGNED(va->va_start, align)); 2143 BUG_ON(va->va_start < vstart); 2144 BUG_ON(va->va_end > vend); 2145 2146 ret = kasan_populate_vmalloc(addr, size, gfp_mask); 2147 if (ret) { 2148 free_vmap_area(va); 2149 return ERR_PTR(ret); 2150 } 2151 2152 return va; 2153 2154 overflow: 2155 if (!purged) { 2156 reclaim_and_purge_vmap_areas(); 2157 purged = 1; 2158 goto retry; 2159 } 2160 2161 freed = 0; 2162 blocking_notifier_call_chain(&vmap_notify_list, 0, &freed); 2163 2164 if (freed > 0) { 2165 purged = 0; 2166 goto retry; 2167 } 2168 2169 if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit()) 2170 pr_warn("vmalloc_node_range for size %lu failed: Address range restricted to %#lx - %#lx\n", 2171 size, vstart, vend); 2172 2173 out_free_va: 2174 kmem_cache_free(vmap_area_cachep, va); 2175 return ERR_PTR(-EBUSY); 2176 } 2177 2178 int register_vmap_purge_notifier(struct notifier_block *nb) 2179 { 2180 return blocking_notifier_chain_register(&vmap_notify_list, nb); 2181 } 2182 EXPORT_SYMBOL_GPL(register_vmap_purge_notifier); 2183 2184 int unregister_vmap_purge_notifier(struct notifier_block *nb) 2185 { 2186 return blocking_notifier_chain_unregister(&vmap_notify_list, nb); 2187 } 2188 EXPORT_SYMBOL_GPL(unregister_vmap_purge_notifier); 2189 2190 /* 2191 * lazy_max_pages is the maximum amount of virtual address space we gather up 2192 * before attempting to purge with a TLB flush. 2193 * 2194 * There is a tradeoff here: a larger number will cover more kernel page tables 2195 * and take slightly longer to purge, but it will linearly reduce the number of 2196 * global TLB flushes that must be performed. It would seem natural to scale 2197 * this number up linearly with the number of CPUs (because vmapping activity 2198 * could also scale linearly with the number of CPUs), however it is likely 2199 * that in practice, workloads might be constrained in other ways that mean 2200 * vmap activity will not scale linearly with CPUs. Also, I want to be 2201 * conservative and not introduce a big latency on huge systems, so go with 2202 * a less aggressive log scale. It will still be an improvement over the old 2203 * code, and it will be simple to change the scale factor if we find that it 2204 * becomes a problem on bigger systems. 2205 */ 2206 static unsigned long lazy_max_pages(void) 2207 { 2208 unsigned int log; 2209 2210 log = fls(num_online_cpus()); 2211 2212 return log * (32UL * 1024 * 1024 / PAGE_SIZE); 2213 } 2214 2215 /* 2216 * Serialize vmap purging. There is no actual critical section protected 2217 * by this lock, but we want to avoid concurrent calls for performance 2218 * reasons and to make the pcpu_get_vm_areas more deterministic. 2219 */ 2220 static DEFINE_MUTEX(vmap_purge_lock); 2221 2222 /* for per-CPU blocks */ 2223 static void purge_fragmented_blocks_allcpus(void); 2224 2225 static void 2226 reclaim_list_global(struct list_head *head) 2227 { 2228 struct vmap_area *va, *n; 2229 2230 if (list_empty(head)) 2231 return; 2232 2233 spin_lock(&free_vmap_area_lock); 2234 list_for_each_entry_safe(va, n, head, list) 2235 merge_or_add_vmap_area_augment(va, 2236 &free_vmap_area_root, &free_vmap_area_list); 2237 spin_unlock(&free_vmap_area_lock); 2238 } 2239 2240 static void 2241 decay_va_pool_node(struct vmap_node *vn, bool full_decay) 2242 { 2243 LIST_HEAD(decay_list); 2244 struct rb_root decay_root = RB_ROOT; 2245 struct vmap_area *va, *nva; 2246 unsigned long n_decay, pool_len; 2247 int i; 2248 2249 for (i = 0; i < MAX_VA_SIZE_PAGES; i++) { 2250 LIST_HEAD(tmp_list); 2251 2252 if (list_empty(&vn->pool[i].head)) 2253 continue; 2254 2255 /* Detach the pool, so no-one can access it. */ 2256 spin_lock(&vn->pool_lock); 2257 list_replace_init(&vn->pool[i].head, &tmp_list); 2258 spin_unlock(&vn->pool_lock); 2259 2260 pool_len = n_decay = vn->pool[i].len; 2261 WRITE_ONCE(vn->pool[i].len, 0); 2262 2263 /* Decay a pool by ~25% out of left objects. */ 2264 if (!full_decay) 2265 n_decay >>= 2; 2266 pool_len -= n_decay; 2267 2268 list_for_each_entry_safe(va, nva, &tmp_list, list) { 2269 if (!n_decay--) 2270 break; 2271 2272 list_del_init(&va->list); 2273 merge_or_add_vmap_area(va, &decay_root, &decay_list); 2274 } 2275 2276 /* 2277 * Attach the pool back if it has been partly decayed. 2278 * Please note, it is supposed that nobody(other contexts) 2279 * can populate the pool therefore a simple list replace 2280 * operation takes place here. 2281 */ 2282 if (!list_empty(&tmp_list)) { 2283 spin_lock(&vn->pool_lock); 2284 list_replace_init(&tmp_list, &vn->pool[i].head); 2285 WRITE_ONCE(vn->pool[i].len, pool_len); 2286 spin_unlock(&vn->pool_lock); 2287 } 2288 } 2289 2290 reclaim_list_global(&decay_list); 2291 } 2292 2293 #define KASAN_RELEASE_BATCH_SIZE 32 2294 2295 static void 2296 kasan_release_vmalloc_node(struct vmap_node *vn) 2297 { 2298 struct vmap_area *va; 2299 unsigned long start, end; 2300 unsigned int batch_count = 0; 2301 2302 start = list_first_entry(&vn->purge_list, struct vmap_area, list)->va_start; 2303 end = list_last_entry(&vn->purge_list, struct vmap_area, list)->va_end; 2304 2305 list_for_each_entry(va, &vn->purge_list, list) { 2306 if (is_vmalloc_or_module_addr((void *) va->va_start)) 2307 kasan_release_vmalloc(va->va_start, va->va_end, 2308 va->va_start, va->va_end, 2309 KASAN_VMALLOC_PAGE_RANGE); 2310 2311 if (need_resched() || (++batch_count >= KASAN_RELEASE_BATCH_SIZE)) { 2312 cond_resched(); 2313 batch_count = 0; 2314 } 2315 } 2316 2317 kasan_release_vmalloc(start, end, start, end, KASAN_VMALLOC_TLB_FLUSH); 2318 } 2319 2320 static void purge_vmap_node(struct work_struct *work) 2321 { 2322 struct vmap_node *vn = container_of(work, 2323 struct vmap_node, purge_work); 2324 unsigned long nr_purged_pages = 0; 2325 struct vmap_area *va, *n_va; 2326 LIST_HEAD(local_list); 2327 2328 if (IS_ENABLED(CONFIG_KASAN_VMALLOC)) 2329 kasan_release_vmalloc_node(vn); 2330 2331 vn->nr_purged = 0; 2332 2333 list_for_each_entry_safe(va, n_va, &vn->purge_list, list) { 2334 unsigned long nr = va_size(va) >> PAGE_SHIFT; 2335 unsigned int vn_id = decode_vn_id(va->flags); 2336 2337 list_del_init(&va->list); 2338 2339 nr_purged_pages += nr; 2340 vn->nr_purged++; 2341 2342 if (is_vn_id_valid(vn_id) && !vn->skip_populate) 2343 if (node_pool_add_va(vn, va)) 2344 continue; 2345 2346 /* Go back to global. */ 2347 list_add(&va->list, &local_list); 2348 } 2349 2350 atomic_long_sub(nr_purged_pages, &vmap_lazy_nr); 2351 2352 reclaim_list_global(&local_list); 2353 } 2354 2355 /* 2356 * Purges all lazily-freed vmap areas. 2357 */ 2358 static bool __purge_vmap_area_lazy(unsigned long start, unsigned long end, 2359 bool full_pool_decay) 2360 { 2361 unsigned long nr_purged_areas = 0; 2362 unsigned int nr_purge_helpers; 2363 static cpumask_t purge_nodes; 2364 unsigned int nr_purge_nodes; 2365 struct vmap_node *vn; 2366 int i; 2367 2368 lockdep_assert_held(&vmap_purge_lock); 2369 2370 /* 2371 * Use cpumask to mark which node has to be processed. 2372 */ 2373 purge_nodes = CPU_MASK_NONE; 2374 2375 for_each_vmap_node(vn) { 2376 INIT_LIST_HEAD(&vn->purge_list); 2377 vn->skip_populate = full_pool_decay; 2378 decay_va_pool_node(vn, full_pool_decay); 2379 2380 if (RB_EMPTY_ROOT(&vn->lazy.root)) 2381 continue; 2382 2383 spin_lock(&vn->lazy.lock); 2384 WRITE_ONCE(vn->lazy.root.rb_node, NULL); 2385 list_replace_init(&vn->lazy.head, &vn->purge_list); 2386 spin_unlock(&vn->lazy.lock); 2387 2388 start = min(start, list_first_entry(&vn->purge_list, 2389 struct vmap_area, list)->va_start); 2390 2391 end = max(end, list_last_entry(&vn->purge_list, 2392 struct vmap_area, list)->va_end); 2393 2394 cpumask_set_cpu(node_to_id(vn), &purge_nodes); 2395 } 2396 2397 nr_purge_nodes = cpumask_weight(&purge_nodes); 2398 if (nr_purge_nodes > 0) { 2399 flush_tlb_kernel_range(start, end); 2400 2401 /* One extra worker is per a lazy_max_pages() full set minus one. */ 2402 nr_purge_helpers = atomic_long_read(&vmap_lazy_nr) / lazy_max_pages(); 2403 nr_purge_helpers = clamp(nr_purge_helpers, 1U, nr_purge_nodes) - 1; 2404 2405 for_each_cpu(i, &purge_nodes) { 2406 vn = &vmap_nodes[i]; 2407 2408 if (nr_purge_helpers > 0) { 2409 INIT_WORK(&vn->purge_work, purge_vmap_node); 2410 2411 if (cpumask_test_cpu(i, cpu_online_mask)) 2412 schedule_work_on(i, &vn->purge_work); 2413 else 2414 schedule_work(&vn->purge_work); 2415 2416 nr_purge_helpers--; 2417 } else { 2418 vn->purge_work.func = NULL; 2419 purge_vmap_node(&vn->purge_work); 2420 nr_purged_areas += vn->nr_purged; 2421 } 2422 } 2423 2424 for_each_cpu(i, &purge_nodes) { 2425 vn = &vmap_nodes[i]; 2426 2427 if (vn->purge_work.func) { 2428 flush_work(&vn->purge_work); 2429 nr_purged_areas += vn->nr_purged; 2430 } 2431 } 2432 } 2433 2434 trace_purge_vmap_area_lazy(start, end, nr_purged_areas); 2435 return nr_purged_areas > 0; 2436 } 2437 2438 /* 2439 * Reclaim vmap areas by purging fragmented blocks and purge_vmap_area_list. 2440 */ 2441 static void reclaim_and_purge_vmap_areas(void) 2442 2443 { 2444 mutex_lock(&vmap_purge_lock); 2445 purge_fragmented_blocks_allcpus(); 2446 __purge_vmap_area_lazy(ULONG_MAX, 0, true); 2447 mutex_unlock(&vmap_purge_lock); 2448 } 2449 2450 static void drain_vmap_area_work(struct work_struct *work) 2451 { 2452 mutex_lock(&vmap_purge_lock); 2453 __purge_vmap_area_lazy(ULONG_MAX, 0, false); 2454 mutex_unlock(&vmap_purge_lock); 2455 } 2456 2457 /* 2458 * Free a vmap area, caller ensuring that the area has been unmapped, 2459 * unlinked and flush_cache_vunmap had been called for the correct 2460 * range previously. 2461 */ 2462 static void free_vmap_area_noflush(struct vmap_area *va) 2463 { 2464 unsigned long nr_lazy_max = lazy_max_pages(); 2465 unsigned long va_start = va->va_start; 2466 unsigned int vn_id = decode_vn_id(va->flags); 2467 struct vmap_node *vn; 2468 unsigned long nr_lazy; 2469 2470 if (WARN_ON_ONCE(!list_empty(&va->list))) 2471 return; 2472 2473 nr_lazy = atomic_long_add_return_relaxed(va_size(va) >> PAGE_SHIFT, 2474 &vmap_lazy_nr); 2475 2476 /* 2477 * If it was request by a certain node we would like to 2478 * return it to that node, i.e. its pool for later reuse. 2479 */ 2480 vn = is_vn_id_valid(vn_id) ? 2481 id_to_node(vn_id):addr_to_node(va->va_start); 2482 2483 spin_lock(&vn->lazy.lock); 2484 insert_vmap_area(va, &vn->lazy.root, &vn->lazy.head); 2485 spin_unlock(&vn->lazy.lock); 2486 2487 trace_free_vmap_area_noflush(va_start, nr_lazy, nr_lazy_max); 2488 2489 /* After this point, we may free va at any time */ 2490 if (unlikely(nr_lazy > nr_lazy_max)) 2491 schedule_work(&drain_vmap_work); 2492 } 2493 2494 /* 2495 * Free and unmap a vmap area 2496 */ 2497 static void free_unmap_vmap_area(struct vmap_area *va) 2498 { 2499 flush_cache_vunmap(va->va_start, va->va_end); 2500 vunmap_range_noflush(va->va_start, va->va_end); 2501 if (debug_pagealloc_enabled_static()) 2502 flush_tlb_kernel_range(va->va_start, va->va_end); 2503 2504 free_vmap_area_noflush(va); 2505 } 2506 2507 struct vmap_area *find_vmap_area(unsigned long addr) 2508 { 2509 struct vmap_node *vn; 2510 struct vmap_area *va; 2511 int i, j; 2512 2513 if (unlikely(!vmap_initialized)) 2514 return NULL; 2515 2516 /* 2517 * An addr_to_node_id(addr) converts an address to a node index 2518 * where a VA is located. If VA spans several zones and passed 2519 * addr is not the same as va->va_start, what is not common, we 2520 * may need to scan extra nodes. See an example: 2521 * 2522 * <----va----> 2523 * -|-----|-----|-----|-----|- 2524 * 1 2 0 1 2525 * 2526 * VA resides in node 1 whereas it spans 1, 2 an 0. If passed 2527 * addr is within 2 or 0 nodes we should do extra work. 2528 */ 2529 i = j = addr_to_node_id(addr); 2530 do { 2531 vn = &vmap_nodes[i]; 2532 2533 spin_lock(&vn->busy.lock); 2534 va = __find_vmap_area(addr, &vn->busy.root); 2535 spin_unlock(&vn->busy.lock); 2536 2537 if (va) 2538 return va; 2539 } while ((i = (i + nr_vmap_nodes - 1) % nr_vmap_nodes) != j); 2540 2541 return NULL; 2542 } 2543 2544 static struct vmap_area *find_unlink_vmap_area(unsigned long addr) 2545 { 2546 struct vmap_node *vn; 2547 struct vmap_area *va; 2548 int i, j; 2549 2550 /* 2551 * Check the comment in the find_vmap_area() about the loop. 2552 */ 2553 i = j = addr_to_node_id(addr); 2554 do { 2555 vn = &vmap_nodes[i]; 2556 2557 spin_lock(&vn->busy.lock); 2558 va = __find_vmap_area(addr, &vn->busy.root); 2559 if (va) 2560 unlink_va(va, &vn->busy.root); 2561 spin_unlock(&vn->busy.lock); 2562 2563 if (va) 2564 return va; 2565 } while ((i = (i + nr_vmap_nodes - 1) % nr_vmap_nodes) != j); 2566 2567 return NULL; 2568 } 2569 2570 /*** Per cpu kva allocator ***/ 2571 2572 /* 2573 * vmap space is limited especially on 32 bit architectures. Ensure there is 2574 * room for at least 16 percpu vmap blocks per CPU. 2575 */ 2576 /* 2577 * If we had a constant VMALLOC_START and VMALLOC_END, we'd like to be able 2578 * to #define VMALLOC_SPACE (VMALLOC_END-VMALLOC_START). Guess 2579 * instead (we just need a rough idea) 2580 */ 2581 #if BITS_PER_LONG == 32 2582 #define VMALLOC_SPACE (128UL*1024*1024) 2583 #else 2584 #define VMALLOC_SPACE (128UL*1024*1024*1024) 2585 #endif 2586 2587 #define VMALLOC_PAGES (VMALLOC_SPACE / PAGE_SIZE) 2588 #define VMAP_MAX_ALLOC BITS_PER_LONG /* 256K with 4K pages */ 2589 #define VMAP_BBMAP_BITS_MAX 1024 /* 4MB with 4K pages */ 2590 #define VMAP_BBMAP_BITS_MIN (VMAP_MAX_ALLOC*2) 2591 #define VMAP_MIN(x, y) ((x) < (y) ? (x) : (y)) /* can't use min() */ 2592 #define VMAP_MAX(x, y) ((x) > (y) ? (x) : (y)) /* can't use max() */ 2593 #define VMAP_BBMAP_BITS \ 2594 VMAP_MIN(VMAP_BBMAP_BITS_MAX, \ 2595 VMAP_MAX(VMAP_BBMAP_BITS_MIN, \ 2596 VMALLOC_PAGES / roundup_pow_of_two(NR_CPUS) / 16)) 2597 2598 #define VMAP_BLOCK_SIZE (VMAP_BBMAP_BITS * PAGE_SIZE) 2599 2600 /* 2601 * Purge threshold to prevent overeager purging of fragmented blocks for 2602 * regular operations: Purge if vb->free is less than 1/4 of the capacity. 2603 */ 2604 #define VMAP_PURGE_THRESHOLD (VMAP_BBMAP_BITS / 4) 2605 2606 #define VMAP_RAM 0x1 /* indicates vm_map_ram area*/ 2607 #define VMAP_BLOCK 0x2 /* mark out the vmap_block sub-type*/ 2608 #define VMAP_FLAGS_MASK 0x3 2609 2610 struct vmap_block_queue { 2611 spinlock_t lock; 2612 struct list_head free; 2613 2614 /* 2615 * An xarray requires an extra memory dynamically to 2616 * be allocated. If it is an issue, we can use rb-tree 2617 * instead. 2618 */ 2619 struct xarray vmap_blocks; 2620 }; 2621 2622 struct vmap_block { 2623 spinlock_t lock; 2624 struct vmap_area *va; 2625 unsigned long free, dirty; 2626 DECLARE_BITMAP(used_map, VMAP_BBMAP_BITS); 2627 unsigned long dirty_min, dirty_max; /*< dirty range */ 2628 struct list_head free_list; 2629 struct rcu_head rcu_head; 2630 struct list_head purge; 2631 unsigned int cpu; 2632 }; 2633 2634 /* Queue of free and dirty vmap blocks, for allocation and flushing purposes */ 2635 static DEFINE_PER_CPU(struct vmap_block_queue, vmap_block_queue); 2636 2637 /* 2638 * In order to fast access to any "vmap_block" associated with a 2639 * specific address, we use a hash. 2640 * 2641 * A per-cpu vmap_block_queue is used in both ways, to serialize 2642 * an access to free block chains among CPUs(alloc path) and it 2643 * also acts as a vmap_block hash(alloc/free paths). It means we 2644 * overload it, since we already have the per-cpu array which is 2645 * used as a hash table. When used as a hash a 'cpu' passed to 2646 * per_cpu() is not actually a CPU but rather a hash index. 2647 * 2648 * A hash function is addr_to_vb_xa() which hashes any address 2649 * to a specific index(in a hash) it belongs to. This then uses a 2650 * per_cpu() macro to access an array with generated index. 2651 * 2652 * An example: 2653 * 2654 * CPU_1 CPU_2 CPU_0 2655 * | | | 2656 * V V V 2657 * 0 10 20 30 40 50 60 2658 * |------|------|------|------|------|------|...<vmap address space> 2659 * CPU0 CPU1 CPU2 CPU0 CPU1 CPU2 2660 * 2661 * - CPU_1 invokes vm_unmap_ram(6), 6 belongs to CPU0 zone, thus 2662 * it access: CPU0/INDEX0 -> vmap_blocks -> xa_lock; 2663 * 2664 * - CPU_2 invokes vm_unmap_ram(11), 11 belongs to CPU1 zone, thus 2665 * it access: CPU1/INDEX1 -> vmap_blocks -> xa_lock; 2666 * 2667 * - CPU_0 invokes vm_unmap_ram(20), 20 belongs to CPU2 zone, thus 2668 * it access: CPU2/INDEX2 -> vmap_blocks -> xa_lock. 2669 * 2670 * This technique almost always avoids lock contention on insert/remove, 2671 * however xarray spinlocks protect against any contention that remains. 2672 */ 2673 static struct xarray * 2674 addr_to_vb_xa(unsigned long addr) 2675 { 2676 int index = (addr / VMAP_BLOCK_SIZE) % nr_cpu_ids; 2677 2678 /* 2679 * Please note, nr_cpu_ids points on a highest set 2680 * possible bit, i.e. we never invoke cpumask_next() 2681 * if an index points on it which is nr_cpu_ids - 1. 2682 */ 2683 if (!cpu_possible(index)) 2684 index = cpumask_next(index, cpu_possible_mask); 2685 2686 return &per_cpu(vmap_block_queue, index).vmap_blocks; 2687 } 2688 2689 /* 2690 * We should probably have a fallback mechanism to allocate virtual memory 2691 * out of partially filled vmap blocks. However vmap block sizing should be 2692 * fairly reasonable according to the vmalloc size, so it shouldn't be a 2693 * big problem. 2694 */ 2695 2696 static unsigned long addr_to_vb_idx(unsigned long addr) 2697 { 2698 addr -= VMALLOC_START & ~(VMAP_BLOCK_SIZE-1); 2699 addr /= VMAP_BLOCK_SIZE; 2700 return addr; 2701 } 2702 2703 static void *vmap_block_vaddr(unsigned long va_start, unsigned long pages_off) 2704 { 2705 unsigned long addr; 2706 2707 addr = va_start + (pages_off << PAGE_SHIFT); 2708 BUG_ON(addr_to_vb_idx(addr) != addr_to_vb_idx(va_start)); 2709 return (void *)addr; 2710 } 2711 2712 /** 2713 * new_vmap_block - allocates new vmap_block and occupies 2^order pages in this 2714 * block. Of course pages number can't exceed VMAP_BBMAP_BITS 2715 * @order: how many 2^order pages should be occupied in newly allocated block 2716 * @gfp_mask: flags for the page level allocator 2717 * 2718 * Return: virtual address in a newly allocated block or ERR_PTR(-errno) 2719 */ 2720 static void *new_vmap_block(unsigned int order, gfp_t gfp_mask) 2721 { 2722 struct vmap_block_queue *vbq; 2723 struct vmap_block *vb; 2724 struct vmap_area *va; 2725 struct xarray *xa; 2726 unsigned long vb_idx; 2727 int node, err; 2728 void *vaddr; 2729 2730 node = numa_node_id(); 2731 2732 vb = kmalloc_node(sizeof(struct vmap_block), gfp_mask, node); 2733 if (unlikely(!vb)) 2734 return ERR_PTR(-ENOMEM); 2735 2736 va = alloc_vmap_area(VMAP_BLOCK_SIZE, VMAP_BLOCK_SIZE, 2737 VMALLOC_START, VMALLOC_END, 2738 node, gfp_mask, 2739 VMAP_RAM|VMAP_BLOCK, NULL); 2740 if (IS_ERR(va)) { 2741 kfree(vb); 2742 return ERR_CAST(va); 2743 } 2744 2745 vaddr = vmap_block_vaddr(va->va_start, 0); 2746 spin_lock_init(&vb->lock); 2747 vb->va = va; 2748 /* At least something should be left free */ 2749 BUG_ON(VMAP_BBMAP_BITS <= (1UL << order)); 2750 bitmap_zero(vb->used_map, VMAP_BBMAP_BITS); 2751 vb->free = VMAP_BBMAP_BITS - (1UL << order); 2752 vb->dirty = 0; 2753 vb->dirty_min = VMAP_BBMAP_BITS; 2754 vb->dirty_max = 0; 2755 bitmap_set(vb->used_map, 0, (1UL << order)); 2756 INIT_LIST_HEAD(&vb->free_list); 2757 vb->cpu = raw_smp_processor_id(); 2758 2759 xa = addr_to_vb_xa(va->va_start); 2760 vb_idx = addr_to_vb_idx(va->va_start); 2761 err = xa_insert(xa, vb_idx, vb, gfp_mask); 2762 if (err) { 2763 kfree(vb); 2764 free_vmap_area(va); 2765 return ERR_PTR(err); 2766 } 2767 /* 2768 * list_add_tail_rcu could happened in another core 2769 * rather than vb->cpu due to task migration, which 2770 * is safe as list_add_tail_rcu will ensure the list's 2771 * integrity together with list_for_each_rcu from read 2772 * side. 2773 */ 2774 vbq = per_cpu_ptr(&vmap_block_queue, vb->cpu); 2775 spin_lock(&vbq->lock); 2776 list_add_tail_rcu(&vb->free_list, &vbq->free); 2777 spin_unlock(&vbq->lock); 2778 2779 return vaddr; 2780 } 2781 2782 static void free_vmap_block(struct vmap_block *vb) 2783 { 2784 struct vmap_node *vn; 2785 struct vmap_block *tmp; 2786 struct xarray *xa; 2787 2788 xa = addr_to_vb_xa(vb->va->va_start); 2789 tmp = xa_erase(xa, addr_to_vb_idx(vb->va->va_start)); 2790 BUG_ON(tmp != vb); 2791 2792 vn = addr_to_node(vb->va->va_start); 2793 spin_lock(&vn->busy.lock); 2794 unlink_va(vb->va, &vn->busy.root); 2795 spin_unlock(&vn->busy.lock); 2796 2797 free_vmap_area_noflush(vb->va); 2798 kfree_rcu(vb, rcu_head); 2799 } 2800 2801 static bool purge_fragmented_block(struct vmap_block *vb, 2802 struct list_head *purge_list, bool force_purge) 2803 { 2804 struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, vb->cpu); 2805 2806 if (vb->free + vb->dirty != VMAP_BBMAP_BITS || 2807 vb->dirty == VMAP_BBMAP_BITS) 2808 return false; 2809 2810 /* Don't overeagerly purge usable blocks unless requested */ 2811 if (!(force_purge || vb->free < VMAP_PURGE_THRESHOLD)) 2812 return false; 2813 2814 /* prevent further allocs after releasing lock */ 2815 WRITE_ONCE(vb->free, 0); 2816 /* prevent purging it again */ 2817 WRITE_ONCE(vb->dirty, VMAP_BBMAP_BITS); 2818 vb->dirty_min = 0; 2819 vb->dirty_max = VMAP_BBMAP_BITS; 2820 spin_lock(&vbq->lock); 2821 list_del_rcu(&vb->free_list); 2822 spin_unlock(&vbq->lock); 2823 list_add_tail(&vb->purge, purge_list); 2824 return true; 2825 } 2826 2827 static void free_purged_blocks(struct list_head *purge_list) 2828 { 2829 struct vmap_block *vb, *n_vb; 2830 2831 list_for_each_entry_safe(vb, n_vb, purge_list, purge) { 2832 list_del(&vb->purge); 2833 free_vmap_block(vb); 2834 } 2835 } 2836 2837 static void purge_fragmented_blocks(int cpu) 2838 { 2839 LIST_HEAD(purge); 2840 struct vmap_block *vb; 2841 struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu); 2842 2843 rcu_read_lock(); 2844 list_for_each_entry_rcu(vb, &vbq->free, free_list) { 2845 unsigned long free = READ_ONCE(vb->free); 2846 unsigned long dirty = READ_ONCE(vb->dirty); 2847 2848 if (free + dirty != VMAP_BBMAP_BITS || 2849 dirty == VMAP_BBMAP_BITS) 2850 continue; 2851 2852 spin_lock(&vb->lock); 2853 purge_fragmented_block(vb, &purge, true); 2854 spin_unlock(&vb->lock); 2855 } 2856 rcu_read_unlock(); 2857 free_purged_blocks(&purge); 2858 } 2859 2860 static void purge_fragmented_blocks_allcpus(void) 2861 { 2862 int cpu; 2863 2864 for_each_possible_cpu(cpu) 2865 purge_fragmented_blocks(cpu); 2866 } 2867 2868 static void *vb_alloc(unsigned long size, gfp_t gfp_mask) 2869 { 2870 struct vmap_block_queue *vbq; 2871 struct vmap_block *vb; 2872 void *vaddr = NULL; 2873 unsigned int order; 2874 2875 BUG_ON(offset_in_page(size)); 2876 BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC); 2877 if (WARN_ON(size == 0)) { 2878 /* 2879 * Allocating 0 bytes isn't what caller wants since 2880 * get_order(0) returns funny result. Just warn and terminate 2881 * early. 2882 */ 2883 return ERR_PTR(-EINVAL); 2884 } 2885 order = get_order(size); 2886 2887 rcu_read_lock(); 2888 vbq = raw_cpu_ptr(&vmap_block_queue); 2889 list_for_each_entry_rcu(vb, &vbq->free, free_list) { 2890 unsigned long pages_off; 2891 2892 if (READ_ONCE(vb->free) < (1UL << order)) 2893 continue; 2894 2895 spin_lock(&vb->lock); 2896 if (vb->free < (1UL << order)) { 2897 spin_unlock(&vb->lock); 2898 continue; 2899 } 2900 2901 pages_off = VMAP_BBMAP_BITS - vb->free; 2902 vaddr = vmap_block_vaddr(vb->va->va_start, pages_off); 2903 WRITE_ONCE(vb->free, vb->free - (1UL << order)); 2904 bitmap_set(vb->used_map, pages_off, (1UL << order)); 2905 if (vb->free == 0) { 2906 spin_lock(&vbq->lock); 2907 list_del_rcu(&vb->free_list); 2908 spin_unlock(&vbq->lock); 2909 } 2910 2911 spin_unlock(&vb->lock); 2912 break; 2913 } 2914 2915 rcu_read_unlock(); 2916 2917 /* Allocate new block if nothing was found */ 2918 if (!vaddr) 2919 vaddr = new_vmap_block(order, gfp_mask); 2920 2921 return vaddr; 2922 } 2923 2924 static void vb_free(unsigned long addr, unsigned long size) 2925 { 2926 unsigned long offset; 2927 unsigned int order; 2928 struct vmap_block *vb; 2929 struct xarray *xa; 2930 2931 BUG_ON(offset_in_page(size)); 2932 BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC); 2933 2934 flush_cache_vunmap(addr, addr + size); 2935 2936 order = get_order(size); 2937 offset = (addr & (VMAP_BLOCK_SIZE - 1)) >> PAGE_SHIFT; 2938 2939 xa = addr_to_vb_xa(addr); 2940 vb = xa_load(xa, addr_to_vb_idx(addr)); 2941 2942 spin_lock(&vb->lock); 2943 bitmap_clear(vb->used_map, offset, (1UL << order)); 2944 spin_unlock(&vb->lock); 2945 2946 vunmap_range_noflush(addr, addr + size); 2947 2948 if (debug_pagealloc_enabled_static()) 2949 flush_tlb_kernel_range(addr, addr + size); 2950 2951 spin_lock(&vb->lock); 2952 2953 /* Expand the not yet TLB flushed dirty range */ 2954 vb->dirty_min = min(vb->dirty_min, offset); 2955 vb->dirty_max = max(vb->dirty_max, offset + (1UL << order)); 2956 2957 WRITE_ONCE(vb->dirty, vb->dirty + (1UL << order)); 2958 if (vb->dirty == VMAP_BBMAP_BITS) { 2959 BUG_ON(vb->free); 2960 spin_unlock(&vb->lock); 2961 free_vmap_block(vb); 2962 } else 2963 spin_unlock(&vb->lock); 2964 } 2965 2966 static void _vm_unmap_aliases(unsigned long start, unsigned long end, int flush) 2967 { 2968 LIST_HEAD(purge_list); 2969 int cpu; 2970 2971 if (unlikely(!vmap_initialized)) 2972 return; 2973 2974 mutex_lock(&vmap_purge_lock); 2975 2976 for_each_possible_cpu(cpu) { 2977 struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu); 2978 struct vmap_block *vb; 2979 unsigned long idx; 2980 2981 rcu_read_lock(); 2982 xa_for_each(&vbq->vmap_blocks, idx, vb) { 2983 spin_lock(&vb->lock); 2984 2985 /* 2986 * Try to purge a fragmented block first. If it's 2987 * not purgeable, check whether there is dirty 2988 * space to be flushed. 2989 */ 2990 if (!purge_fragmented_block(vb, &purge_list, false) && 2991 vb->dirty_max && vb->dirty != VMAP_BBMAP_BITS) { 2992 unsigned long va_start = vb->va->va_start; 2993 unsigned long s, e; 2994 2995 s = va_start + (vb->dirty_min << PAGE_SHIFT); 2996 e = va_start + (vb->dirty_max << PAGE_SHIFT); 2997 2998 start = min(s, start); 2999 end = max(e, end); 3000 3001 /* Prevent that this is flushed again */ 3002 vb->dirty_min = VMAP_BBMAP_BITS; 3003 vb->dirty_max = 0; 3004 3005 flush = 1; 3006 } 3007 spin_unlock(&vb->lock); 3008 } 3009 rcu_read_unlock(); 3010 } 3011 free_purged_blocks(&purge_list); 3012 3013 if (!__purge_vmap_area_lazy(start, end, false) && flush) 3014 flush_tlb_kernel_range(start, end); 3015 mutex_unlock(&vmap_purge_lock); 3016 } 3017 3018 /** 3019 * vm_unmap_aliases - unmap outstanding lazy aliases in the vmap layer 3020 * 3021 * The vmap/vmalloc layer lazily flushes kernel virtual mappings primarily 3022 * to amortize TLB flushing overheads. What this means is that any page you 3023 * have now, may, in a former life, have been mapped into kernel virtual 3024 * address by the vmap layer and so there might be some CPUs with TLB entries 3025 * still referencing that page (additional to the regular 1:1 kernel mapping). 3026 * 3027 * vm_unmap_aliases flushes all such lazy mappings. After it returns, we can 3028 * be sure that none of the pages we have control over will have any aliases 3029 * from the vmap layer. 3030 */ 3031 void vm_unmap_aliases(void) 3032 { 3033 _vm_unmap_aliases(ULONG_MAX, 0, 0); 3034 } 3035 EXPORT_SYMBOL_GPL(vm_unmap_aliases); 3036 3037 /** 3038 * vm_unmap_ram - unmap linear kernel address space set up by vm_map_ram 3039 * @mem: the pointer returned by vm_map_ram 3040 * @count: the count passed to that vm_map_ram call (cannot unmap partial) 3041 */ 3042 void vm_unmap_ram(const void *mem, unsigned int count) 3043 { 3044 unsigned long size = (unsigned long)count << PAGE_SHIFT; 3045 unsigned long addr = (unsigned long)kasan_reset_tag(mem); 3046 struct vmap_area *va; 3047 3048 might_sleep(); 3049 BUG_ON(!addr); 3050 BUG_ON(addr < VMALLOC_START); 3051 BUG_ON(addr > VMALLOC_END); 3052 BUG_ON(!PAGE_ALIGNED(addr)); 3053 3054 kasan_poison_vmalloc(mem, size); 3055 3056 if (likely(count <= VMAP_MAX_ALLOC)) { 3057 debug_check_no_locks_freed(mem, size); 3058 vb_free(addr, size); 3059 return; 3060 } 3061 3062 va = find_unlink_vmap_area(addr); 3063 if (WARN_ON_ONCE(!va)) 3064 return; 3065 3066 debug_check_no_locks_freed((void *)va->va_start, va_size(va)); 3067 free_unmap_vmap_area(va); 3068 } 3069 EXPORT_SYMBOL(vm_unmap_ram); 3070 3071 /** 3072 * vm_map_ram - map pages linearly into kernel virtual address (vmalloc space) 3073 * @pages: an array of pointers to the pages to be mapped 3074 * @count: number of pages 3075 * @node: prefer to allocate data structures on this node 3076 * 3077 * If you use this function for less than VMAP_MAX_ALLOC pages, it could be 3078 * faster than vmap so it's good. But if you mix long-life and short-life 3079 * objects with vm_map_ram(), it could consume lots of address space through 3080 * fragmentation (especially on a 32bit machine). You could see failures in 3081 * the end. Please use this function for short-lived objects. 3082 * 3083 * Returns: a pointer to the address that has been mapped, or %NULL on failure 3084 */ 3085 void *vm_map_ram(struct page **pages, unsigned int count, int node) 3086 { 3087 unsigned long size = (unsigned long)count << PAGE_SHIFT; 3088 unsigned long addr; 3089 void *mem; 3090 3091 if (likely(count <= VMAP_MAX_ALLOC)) { 3092 mem = vb_alloc(size, GFP_KERNEL); 3093 if (IS_ERR(mem)) 3094 return NULL; 3095 addr = (unsigned long)mem; 3096 } else { 3097 struct vmap_area *va; 3098 va = alloc_vmap_area(size, PAGE_SIZE, 3099 VMALLOC_START, VMALLOC_END, 3100 node, GFP_KERNEL, VMAP_RAM, 3101 NULL); 3102 if (IS_ERR(va)) 3103 return NULL; 3104 3105 addr = va->va_start; 3106 mem = (void *)addr; 3107 } 3108 3109 if (vmap_pages_range(addr, addr + size, PAGE_KERNEL, 3110 pages, PAGE_SHIFT) < 0) { 3111 vm_unmap_ram(mem, count); 3112 return NULL; 3113 } 3114 3115 /* 3116 * Mark the pages as accessible, now that they are mapped. 3117 * With hardware tag-based KASAN, marking is skipped for 3118 * non-VM_ALLOC mappings, see __kasan_unpoison_vmalloc(). 3119 */ 3120 mem = kasan_unpoison_vmalloc(mem, size, KASAN_VMALLOC_PROT_NORMAL); 3121 3122 return mem; 3123 } 3124 EXPORT_SYMBOL(vm_map_ram); 3125 3126 static struct vm_struct *vmlist __initdata; 3127 3128 static inline unsigned int vm_area_page_order(struct vm_struct *vm) 3129 { 3130 #ifdef CONFIG_HAVE_ARCH_HUGE_VMALLOC 3131 return vm->page_order; 3132 #else 3133 return 0; 3134 #endif 3135 } 3136 3137 unsigned int get_vm_area_page_order(struct vm_struct *vm) 3138 { 3139 return vm_area_page_order(vm); 3140 } 3141 3142 static inline void set_vm_area_page_order(struct vm_struct *vm, unsigned int order) 3143 { 3144 #ifdef CONFIG_HAVE_ARCH_HUGE_VMALLOC 3145 vm->page_order = order; 3146 #else 3147 BUG_ON(order != 0); 3148 #endif 3149 } 3150 3151 /** 3152 * vm_area_add_early - add vmap area early during boot 3153 * @vm: vm_struct to add 3154 * 3155 * This function is used to add fixed kernel vm area to vmlist before 3156 * vmalloc_init() is called. @vm->addr, @vm->size, and @vm->flags 3157 * should contain proper values and the other fields should be zero. 3158 * 3159 * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING. 3160 */ 3161 void __init vm_area_add_early(struct vm_struct *vm) 3162 { 3163 struct vm_struct *tmp, **p; 3164 3165 BUG_ON(vmap_initialized); 3166 for (p = &vmlist; (tmp = *p) != NULL; p = &tmp->next) { 3167 if (tmp->addr >= vm->addr) { 3168 BUG_ON(tmp->addr < vm->addr + vm->size); 3169 break; 3170 } else 3171 BUG_ON(tmp->addr + tmp->size > vm->addr); 3172 } 3173 vm->next = *p; 3174 *p = vm; 3175 } 3176 3177 /** 3178 * vm_area_register_early - register vmap area early during boot 3179 * @vm: vm_struct to register 3180 * @align: requested alignment 3181 * 3182 * This function is used to register kernel vm area before 3183 * vmalloc_init() is called. @vm->size and @vm->flags should contain 3184 * proper values on entry and other fields should be zero. On return, 3185 * vm->addr contains the allocated address. 3186 * 3187 * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING. 3188 */ 3189 void __init vm_area_register_early(struct vm_struct *vm, size_t align) 3190 { 3191 unsigned long addr = ALIGN(VMALLOC_START, align); 3192 struct vm_struct *cur, **p; 3193 3194 BUG_ON(vmap_initialized); 3195 3196 for (p = &vmlist; (cur = *p) != NULL; p = &cur->next) { 3197 if ((unsigned long)cur->addr - addr >= vm->size) 3198 break; 3199 addr = ALIGN((unsigned long)cur->addr + cur->size, align); 3200 } 3201 3202 BUG_ON(addr > VMALLOC_END - vm->size); 3203 vm->addr = (void *)addr; 3204 vm->next = *p; 3205 *p = vm; 3206 kasan_populate_early_vm_area_shadow(vm->addr, vm->size); 3207 } 3208 3209 void clear_vm_uninitialized_flag(struct vm_struct *vm) 3210 { 3211 /* 3212 * Before removing VM_UNINITIALIZED, 3213 * we should make sure that vm has proper values. 3214 * Pair with smp_rmb() in vread_iter() and vmalloc_info_show(). 3215 */ 3216 smp_wmb(); 3217 vm->flags &= ~VM_UNINITIALIZED; 3218 } 3219 3220 struct vm_struct *__get_vm_area_node(unsigned long size, 3221 unsigned long align, unsigned long shift, unsigned long flags, 3222 unsigned long start, unsigned long end, int node, 3223 gfp_t gfp_mask, const void *caller) 3224 { 3225 struct vmap_area *va; 3226 struct vm_struct *area; 3227 unsigned long requested_size = size; 3228 3229 BUG_ON(in_nmi() || in_hardirq()); 3230 size = ALIGN(size, 1ul << shift); 3231 if (unlikely(!size)) 3232 return NULL; 3233 3234 if (flags & VM_IOREMAP) 3235 align = 1ul << clamp_t(int, get_count_order_long(size), 3236 PAGE_SHIFT, IOREMAP_MAX_ORDER); 3237 3238 area = kzalloc_node(sizeof(*area), gfp_mask & GFP_RECLAIM_MASK, node); 3239 if (unlikely(!area)) 3240 return NULL; 3241 3242 if (!(flags & VM_NO_GUARD)) 3243 size += PAGE_SIZE; 3244 3245 area->flags = flags; 3246 area->caller = caller; 3247 area->requested_size = requested_size; 3248 3249 va = alloc_vmap_area(size, align, start, end, node, gfp_mask, 0, area); 3250 if (IS_ERR(va)) { 3251 kfree(area); 3252 return NULL; 3253 } 3254 3255 /* 3256 * Mark pages for non-VM_ALLOC mappings as accessible. Do it now as a 3257 * best-effort approach, as they can be mapped outside of vmalloc code. 3258 * For VM_ALLOC mappings, the pages are marked as accessible after 3259 * getting mapped in __vmalloc_node_range(). 3260 * With hardware tag-based KASAN, marking is skipped for 3261 * non-VM_ALLOC mappings, see __kasan_unpoison_vmalloc(). 3262 */ 3263 if (!(flags & VM_ALLOC)) 3264 area->addr = kasan_unpoison_vmalloc(area->addr, requested_size, 3265 KASAN_VMALLOC_PROT_NORMAL); 3266 3267 return area; 3268 } 3269 3270 struct vm_struct *__get_vm_area_caller(unsigned long size, unsigned long flags, 3271 unsigned long start, unsigned long end, 3272 const void *caller) 3273 { 3274 return __get_vm_area_node(size, 1, PAGE_SHIFT, flags, start, end, 3275 NUMA_NO_NODE, GFP_KERNEL, caller); 3276 } 3277 3278 /** 3279 * get_vm_area - reserve a contiguous kernel virtual area 3280 * @size: size of the area 3281 * @flags: %VM_IOREMAP for I/O mappings or VM_ALLOC 3282 * 3283 * Search an area of @size in the kernel virtual mapping area, 3284 * and reserved it for out purposes. Returns the area descriptor 3285 * on success or %NULL on failure. 3286 * 3287 * Return: the area descriptor on success or %NULL on failure. 3288 */ 3289 struct vm_struct *get_vm_area(unsigned long size, unsigned long flags) 3290 { 3291 return __get_vm_area_node(size, 1, PAGE_SHIFT, flags, 3292 VMALLOC_START, VMALLOC_END, 3293 NUMA_NO_NODE, GFP_KERNEL, 3294 __builtin_return_address(0)); 3295 } 3296 3297 struct vm_struct *get_vm_area_caller(unsigned long size, unsigned long flags, 3298 const void *caller) 3299 { 3300 return __get_vm_area_node(size, 1, PAGE_SHIFT, flags, 3301 VMALLOC_START, VMALLOC_END, 3302 NUMA_NO_NODE, GFP_KERNEL, caller); 3303 } 3304 3305 /** 3306 * find_vm_area - find a continuous kernel virtual area 3307 * @addr: base address 3308 * 3309 * Search for the kernel VM area starting at @addr, and return it. 3310 * It is up to the caller to do all required locking to keep the returned 3311 * pointer valid. 3312 * 3313 * Return: the area descriptor on success or %NULL on failure. 3314 */ 3315 struct vm_struct *find_vm_area(const void *addr) 3316 { 3317 struct vmap_area *va; 3318 3319 va = find_vmap_area((unsigned long)addr); 3320 if (!va) 3321 return NULL; 3322 3323 return va->vm; 3324 } 3325 3326 /** 3327 * remove_vm_area - find and remove a continuous kernel virtual area 3328 * @addr: base address 3329 * 3330 * Search for the kernel VM area starting at @addr, and remove it. 3331 * This function returns the found VM area, but using it is NOT safe 3332 * on SMP machines, except for its size or flags. 3333 * 3334 * Return: the area descriptor on success or %NULL on failure. 3335 */ 3336 struct vm_struct *remove_vm_area(const void *addr) 3337 { 3338 struct vmap_area *va; 3339 struct vm_struct *vm; 3340 3341 might_sleep(); 3342 3343 if (WARN(!PAGE_ALIGNED(addr), "Trying to vfree() bad address (%p)\n", 3344 addr)) 3345 return NULL; 3346 3347 va = find_unlink_vmap_area((unsigned long)addr); 3348 if (!va || !va->vm) 3349 return NULL; 3350 vm = va->vm; 3351 3352 debug_check_no_locks_freed(vm->addr, get_vm_area_size(vm)); 3353 debug_check_no_obj_freed(vm->addr, get_vm_area_size(vm)); 3354 kasan_free_module_shadow(vm); 3355 kasan_poison_vmalloc(vm->addr, get_vm_area_size(vm)); 3356 3357 free_unmap_vmap_area(va); 3358 return vm; 3359 } 3360 3361 static inline void set_area_direct_map(const struct vm_struct *area, 3362 int (*set_direct_map)(struct page *page)) 3363 { 3364 int i; 3365 3366 /* HUGE_VMALLOC passes small pages to set_direct_map */ 3367 for (i = 0; i < area->nr_pages; i++) 3368 if (page_address(area->pages[i])) 3369 set_direct_map(area->pages[i]); 3370 } 3371 3372 /* 3373 * Flush the vm mapping and reset the direct map. 3374 */ 3375 static void vm_reset_perms(struct vm_struct *area) 3376 { 3377 unsigned long start = ULONG_MAX, end = 0; 3378 unsigned int page_order = vm_area_page_order(area); 3379 int flush_dmap = 0; 3380 int i; 3381 3382 /* 3383 * Find the start and end range of the direct mappings to make sure that 3384 * the vm_unmap_aliases() flush includes the direct map. 3385 */ 3386 for (i = 0; i < area->nr_pages; i += 1U << page_order) { 3387 unsigned long addr = (unsigned long)page_address(area->pages[i]); 3388 3389 if (addr) { 3390 unsigned long page_size; 3391 3392 page_size = PAGE_SIZE << page_order; 3393 start = min(addr, start); 3394 end = max(addr + page_size, end); 3395 flush_dmap = 1; 3396 } 3397 } 3398 3399 /* 3400 * Set direct map to something invalid so that it won't be cached if 3401 * there are any accesses after the TLB flush, then flush the TLB and 3402 * reset the direct map permissions to the default. 3403 */ 3404 set_area_direct_map(area, set_direct_map_invalid_noflush); 3405 _vm_unmap_aliases(start, end, flush_dmap); 3406 set_area_direct_map(area, set_direct_map_default_noflush); 3407 } 3408 3409 static void delayed_vfree_work(struct work_struct *w) 3410 { 3411 struct vfree_deferred *p = container_of(w, struct vfree_deferred, wq); 3412 struct llist_node *t, *llnode; 3413 3414 llist_for_each_safe(llnode, t, llist_del_all(&p->list)) 3415 vfree(llnode); 3416 } 3417 3418 /** 3419 * vfree_atomic - release memory allocated by vmalloc() 3420 * @addr: memory base address 3421 * 3422 * This one is just like vfree() but can be called in any atomic context 3423 * except NMIs. 3424 */ 3425 void vfree_atomic(const void *addr) 3426 { 3427 struct vfree_deferred *p = raw_cpu_ptr(&vfree_deferred); 3428 3429 BUG_ON(in_nmi()); 3430 kmemleak_free(addr); 3431 3432 /* 3433 * Use raw_cpu_ptr() because this can be called from preemptible 3434 * context. Preemption is absolutely fine here, because the llist_add() 3435 * implementation is lockless, so it works even if we are adding to 3436 * another cpu's list. schedule_work() should be fine with this too. 3437 */ 3438 if (addr && llist_add((struct llist_node *)addr, &p->list)) 3439 schedule_work(&p->wq); 3440 } 3441 3442 /* 3443 * vm_area_free_pages - free a range of pages from a vmalloc allocation 3444 * @vm: the vm_struct containing the pages 3445 * @start_idx: first page index to free (inclusive) 3446 * @end_idx: last page index to free (exclusive) 3447 * 3448 * Free pages [start_idx, end_idx) updating NR_VMALLOC stat accounting. 3449 * Freed vm->pages[] entries are set to NULL. 3450 * Caller is responsible for unmapping (vunmap_range) and KASAN 3451 * poisoning before calling this. 3452 */ 3453 static void vm_area_free_pages(struct vm_struct *vm, unsigned int start_idx, 3454 unsigned int end_idx) 3455 { 3456 unsigned int i; 3457 3458 if (!(vm->flags & VM_MAP_PUT_PAGES)) { 3459 for (i = start_idx; i < end_idx; i++) 3460 mod_lruvec_page_state(vm->pages[i], NR_VMALLOC, -1); 3461 } 3462 free_pages_bulk(vm->pages + start_idx, end_idx - start_idx); 3463 3464 for (i = start_idx; i < end_idx; i++) 3465 vm->pages[i] = NULL; 3466 } 3467 3468 /** 3469 * vfree - Release memory allocated by vmalloc() 3470 * @addr: Memory base address 3471 * 3472 * Free the virtually continuous memory area starting at @addr, as obtained 3473 * from one of the vmalloc() family of APIs. This will usually also free the 3474 * physical memory underlying the virtual allocation, but that memory is 3475 * reference counted, so it will not be freed until the last user goes away. 3476 * 3477 * If @addr is NULL, no operation is performed. 3478 * 3479 * Context: 3480 * May sleep if called *not* from interrupt context. 3481 * Must not be called in NMI context (strictly speaking, it could be 3482 * if we have CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG, but making the calling 3483 * conventions for vfree() arch-dependent would be a really bad idea). 3484 */ 3485 void vfree(const void *addr) 3486 { 3487 struct vm_struct *vm; 3488 3489 if (unlikely(in_interrupt())) { 3490 vfree_atomic(addr); 3491 return; 3492 } 3493 3494 BUG_ON(in_nmi()); 3495 kmemleak_free(addr); 3496 might_sleep(); 3497 3498 if (!addr) 3499 return; 3500 3501 vm = remove_vm_area(addr); 3502 if (unlikely(!vm)) { 3503 WARN(1, KERN_ERR "Trying to vfree() nonexistent vm area (%p)\n", 3504 addr); 3505 return; 3506 } 3507 3508 if (unlikely(vm->flags & VM_FLUSH_RESET_PERMS)) 3509 vm_reset_perms(vm); 3510 3511 vm_area_free_pages(vm, 0, vm->nr_pages); 3512 kvfree(vm->pages); 3513 kfree(vm); 3514 } 3515 EXPORT_SYMBOL(vfree); 3516 3517 /** 3518 * vunmap - release virtual mapping obtained by vmap() 3519 * @addr: memory base address 3520 * 3521 * Free the virtually contiguous memory area starting at @addr, 3522 * which was created from the page array passed to vmap(). 3523 * 3524 * Must not be called in interrupt context. 3525 */ 3526 void vunmap(const void *addr) 3527 { 3528 struct vm_struct *vm; 3529 3530 BUG_ON(in_interrupt()); 3531 might_sleep(); 3532 3533 if (!addr) 3534 return; 3535 vm = remove_vm_area(addr); 3536 if (unlikely(!vm)) { 3537 WARN(1, KERN_ERR "Trying to vunmap() nonexistent vm area (%p)\n", 3538 addr); 3539 return; 3540 } 3541 kfree(vm); 3542 } 3543 EXPORT_SYMBOL(vunmap); 3544 3545 /** 3546 * vmap - map an array of pages into virtually contiguous space 3547 * @pages: array of page pointers 3548 * @count: number of pages to map 3549 * @flags: vm_area->flags 3550 * @prot: page protection for the mapping 3551 * 3552 * Maps @count pages from @pages into contiguous kernel virtual space. 3553 * If @flags contains %VM_MAP_PUT_PAGES the ownership of the pages array itself 3554 * (which must be kmalloc or vmalloc memory) and one reference per pages in it 3555 * are transferred from the caller to vmap(), and will be freed / dropped when 3556 * vfree() is called on the return value. 3557 * 3558 * Return: the address of the area or %NULL on failure 3559 */ 3560 void *vmap(struct page **pages, unsigned int count, 3561 unsigned long flags, pgprot_t prot) 3562 { 3563 struct vm_struct *area; 3564 unsigned long addr; 3565 unsigned long size; /* In bytes */ 3566 3567 might_sleep(); 3568 3569 if (WARN_ON_ONCE(flags & VM_FLUSH_RESET_PERMS)) 3570 return NULL; 3571 3572 /* 3573 * Your top guard is someone else's bottom guard. Not having a top 3574 * guard compromises someone else's mappings too. 3575 */ 3576 if (WARN_ON_ONCE(flags & VM_NO_GUARD)) 3577 flags &= ~VM_NO_GUARD; 3578 3579 if (count > totalram_pages()) 3580 return NULL; 3581 3582 size = (unsigned long)count << PAGE_SHIFT; 3583 area = get_vm_area_caller(size, flags, __builtin_return_address(0)); 3584 if (!area) 3585 return NULL; 3586 3587 addr = (unsigned long)area->addr; 3588 if (vmap_pages_range(addr, addr + size, pgprot_nx(prot), 3589 pages, PAGE_SHIFT) < 0) { 3590 vunmap(area->addr); 3591 return NULL; 3592 } 3593 3594 if (flags & VM_MAP_PUT_PAGES) { 3595 area->pages = pages; 3596 area->nr_pages = count; 3597 } 3598 return area->addr; 3599 } 3600 EXPORT_SYMBOL(vmap); 3601 3602 #ifdef CONFIG_VMAP_PFN 3603 struct vmap_pfn_data { 3604 unsigned long *pfns; 3605 pgprot_t prot; 3606 unsigned int idx; 3607 }; 3608 3609 static int vmap_pfn_apply(pte_t *pte, unsigned long addr, void *private) 3610 { 3611 struct vmap_pfn_data *data = private; 3612 unsigned long pfn = data->pfns[data->idx]; 3613 pte_t ptent; 3614 3615 if (WARN_ON_ONCE(pfn_valid(pfn))) 3616 return -EINVAL; 3617 3618 ptent = pte_mkspecial(pfn_pte(pfn, data->prot)); 3619 set_pte_at(&init_mm, addr, pte, ptent); 3620 3621 data->idx++; 3622 return 0; 3623 } 3624 3625 /** 3626 * vmap_pfn - map an array of PFNs into virtually contiguous space 3627 * @pfns: array of PFNs 3628 * @count: number of pages to map 3629 * @prot: page protection for the mapping 3630 * 3631 * Maps @count PFNs from @pfns into contiguous kernel virtual space and returns 3632 * the start address of the mapping. 3633 */ 3634 void *vmap_pfn(unsigned long *pfns, unsigned int count, pgprot_t prot) 3635 { 3636 struct vmap_pfn_data data = { .pfns = pfns, .prot = pgprot_nx(prot) }; 3637 struct vm_struct *area; 3638 3639 area = get_vm_area_caller(count * PAGE_SIZE, VM_IOREMAP, 3640 __builtin_return_address(0)); 3641 if (!area) 3642 return NULL; 3643 if (apply_to_page_range(&init_mm, (unsigned long)area->addr, 3644 count * PAGE_SIZE, vmap_pfn_apply, &data)) { 3645 free_vm_area(area); 3646 return NULL; 3647 } 3648 3649 flush_cache_vmap((unsigned long)area->addr, 3650 (unsigned long)area->addr + count * PAGE_SIZE); 3651 3652 return area->addr; 3653 } 3654 EXPORT_SYMBOL_GPL(vmap_pfn); 3655 #endif /* CONFIG_VMAP_PFN */ 3656 3657 /* 3658 * Helper for vmalloc to adjust the gfp flags for certain allocations. 3659 */ 3660 static inline gfp_t vmalloc_gfp_adjust(gfp_t flags, const bool large) 3661 { 3662 flags |= __GFP_NOWARN; 3663 if (large) 3664 flags &= ~__GFP_NOFAIL; 3665 return flags; 3666 } 3667 3668 static inline unsigned int 3669 vm_area_alloc_pages(gfp_t gfp, int nid, 3670 unsigned int order, unsigned int nr_pages, struct page **pages) 3671 { 3672 unsigned int nr_allocated = 0; 3673 unsigned int nr_remaining = nr_pages; 3674 unsigned int max_attempt_order = MAX_PAGE_ORDER; 3675 struct page *page; 3676 int i; 3677 unsigned int large_order = ilog2(nr_remaining); 3678 gfp_t large_gfp = vmalloc_gfp_adjust(gfp, large_order) & ~__GFP_DIRECT_RECLAIM; 3679 3680 large_order = min(max_attempt_order, large_order); 3681 3682 /* 3683 * Initially, attempt to have the page allocator give us large order 3684 * pages. Do not attempt allocating smaller than order chunks since 3685 * __vmap_pages_range() expects physically contigous pages of exactly 3686 * order long chunks. 3687 */ 3688 while (large_order > order && nr_remaining) { 3689 if (nid == NUMA_NO_NODE) 3690 page = alloc_pages_noprof(large_gfp, large_order); 3691 else 3692 page = alloc_pages_node_noprof(nid, large_gfp, large_order); 3693 3694 if (unlikely(!page)) { 3695 max_attempt_order = --large_order; 3696 continue; 3697 } 3698 3699 mod_lruvec_page_state(page, NR_VMALLOC, 1 << large_order); 3700 3701 split_page(page, large_order); 3702 for (i = 0; i < (1U << large_order); i++) 3703 pages[nr_allocated + i] = page + i; 3704 3705 nr_allocated += 1U << large_order; 3706 nr_remaining = nr_pages - nr_allocated; 3707 3708 large_order = ilog2(nr_remaining); 3709 large_order = min(max_attempt_order, large_order); 3710 } 3711 3712 /* 3713 * For order-0 pages we make use of bulk allocator, if 3714 * the page array is partly or not at all populated due 3715 * to fails, fallback to a single page allocator that is 3716 * more permissive. 3717 */ 3718 if (!order) { 3719 while (nr_allocated < nr_pages) { 3720 unsigned int nr, nr_pages_request; 3721 int i; 3722 3723 /* 3724 * A maximum allowed request is hard-coded and is 100 3725 * pages per call. That is done in order to prevent a 3726 * long preemption off scenario in the bulk-allocator 3727 * so the range is [1:100]. 3728 */ 3729 nr_pages_request = min(100U, nr_pages - nr_allocated); 3730 3731 /* memory allocation should consider mempolicy, we can't 3732 * wrongly use nearest node when nid == NUMA_NO_NODE, 3733 * otherwise memory may be allocated in only one node, 3734 * but mempolicy wants to alloc memory by interleaving. 3735 */ 3736 if (IS_ENABLED(CONFIG_NUMA) && nid == NUMA_NO_NODE) 3737 nr = alloc_pages_bulk_mempolicy_noprof(gfp, 3738 nr_pages_request, 3739 pages + nr_allocated); 3740 else 3741 nr = alloc_pages_bulk_node_noprof(gfp, nid, 3742 nr_pages_request, 3743 pages + nr_allocated); 3744 3745 for (i = nr_allocated; i < nr_allocated + nr; i++) 3746 mod_lruvec_page_state(pages[i], NR_VMALLOC, 1); 3747 3748 nr_allocated += nr; 3749 3750 /* 3751 * If zero or pages were obtained partly, 3752 * fallback to a single page allocator. 3753 */ 3754 if (nr != nr_pages_request) 3755 break; 3756 } 3757 } 3758 3759 /* High-order pages or fallback path if "bulk" fails. */ 3760 while (nr_allocated < nr_pages) { 3761 if (!(gfp & __GFP_NOFAIL) && fatal_signal_pending(current)) 3762 break; 3763 3764 if (nid == NUMA_NO_NODE) 3765 page = alloc_pages_noprof(gfp, order); 3766 else 3767 page = alloc_pages_node_noprof(nid, gfp, order); 3768 3769 if (unlikely(!page)) 3770 break; 3771 3772 mod_lruvec_page_state(page, NR_VMALLOC, 1 << order); 3773 3774 /* 3775 * High-order allocations must be able to be treated as 3776 * independent small pages by callers (as they can with 3777 * small-page vmallocs). Some drivers do their own refcounting 3778 * on vmalloc_to_page() pages, some use page->mapping, 3779 * page->lru, etc. 3780 */ 3781 if (order) 3782 split_page(page, order); 3783 3784 /* 3785 * Careful, we allocate and map page-order pages, but 3786 * tracking is done per PAGE_SIZE page so as to keep the 3787 * vm_struct APIs independent of the physical/mapped size. 3788 */ 3789 for (i = 0; i < (1U << order); i++) 3790 pages[nr_allocated + i] = page + i; 3791 3792 nr_allocated += 1U << order; 3793 } 3794 3795 return nr_allocated; 3796 } 3797 3798 static LLIST_HEAD(pending_vm_area_cleanup); 3799 static void cleanup_vm_area_work(struct work_struct *work) 3800 { 3801 struct vm_struct *area, *tmp; 3802 struct llist_node *head; 3803 3804 head = llist_del_all(&pending_vm_area_cleanup); 3805 if (!head) 3806 return; 3807 3808 llist_for_each_entry_safe(area, tmp, head, llnode) { 3809 if (!area->pages) 3810 free_vm_area(area); 3811 else 3812 vfree(area->addr); 3813 } 3814 } 3815 3816 /* 3817 * Helper for __vmalloc_area_node() to defer cleanup 3818 * of partially initialized vm_struct in error paths. 3819 */ 3820 static DECLARE_WORK(cleanup_vm_area, cleanup_vm_area_work); 3821 static void defer_vm_area_cleanup(struct vm_struct *area) 3822 { 3823 if (llist_add(&area->llnode, &pending_vm_area_cleanup)) 3824 schedule_work(&cleanup_vm_area); 3825 } 3826 3827 /* 3828 * Page tables allocations ignore external GFP. Enforces it by 3829 * the memalloc scope API. It is used by vmalloc internals and 3830 * KASAN shadow population only. 3831 * 3832 * GFP to scope mapping: 3833 * 3834 * non-blocking (no __GFP_DIRECT_RECLAIM) - memalloc_noreclaim_save() 3835 * GFP_NOFS - memalloc_nofs_save() 3836 * GFP_NOIO - memalloc_noio_save() 3837 * __GFP_RETRY_MAYFAIL, __GFP_NORETRY - memalloc_noreclaim_save() 3838 * to prevent OOMs 3839 * 3840 * Returns a flag cookie to pair with restore. 3841 */ 3842 unsigned int 3843 memalloc_apply_gfp_scope(gfp_t gfp_mask) 3844 { 3845 unsigned int flags = 0; 3846 3847 if (!gfpflags_allow_blocking(gfp_mask) || 3848 (gfp_mask & (__GFP_RETRY_MAYFAIL | __GFP_NORETRY))) 3849 flags = memalloc_noreclaim_save(); 3850 else if ((gfp_mask & (__GFP_FS | __GFP_IO)) == __GFP_IO) 3851 flags = memalloc_nofs_save(); 3852 else if ((gfp_mask & (__GFP_FS | __GFP_IO)) == 0) 3853 flags = memalloc_noio_save(); 3854 3855 /* 0 - no scope applied. */ 3856 return flags; 3857 } 3858 3859 void 3860 memalloc_restore_scope(unsigned int flags) 3861 { 3862 if (flags) 3863 memalloc_flags_restore(flags); 3864 } 3865 3866 static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask, 3867 pgprot_t prot, unsigned int page_shift, 3868 int node) 3869 { 3870 const gfp_t nested_gfp = (gfp_mask & GFP_RECLAIM_MASK) | __GFP_ZERO; 3871 bool nofail = gfp_mask & __GFP_NOFAIL; 3872 unsigned long addr = (unsigned long)area->addr; 3873 unsigned long size = get_vm_area_size(area); 3874 unsigned long array_size; 3875 unsigned int nr_small_pages = size >> PAGE_SHIFT; 3876 unsigned int page_order; 3877 unsigned int flags; 3878 int ret; 3879 3880 array_size = (unsigned long)nr_small_pages * sizeof(struct page *); 3881 3882 /* __GFP_NOFAIL and "noblock" flags are mutually exclusive. */ 3883 if (!gfpflags_allow_blocking(gfp_mask)) 3884 nofail = false; 3885 3886 if (!(gfp_mask & (GFP_DMA | GFP_DMA32))) 3887 gfp_mask |= __GFP_HIGHMEM; 3888 3889 /* Please note that the recursion is strictly bounded. */ 3890 if (array_size > PAGE_SIZE) { 3891 area->pages = __vmalloc_node_noprof(array_size, 1, nested_gfp, node, 3892 area->caller); 3893 } else { 3894 area->pages = kmalloc_node_noprof(array_size, nested_gfp, node); 3895 } 3896 3897 if (!area->pages) { 3898 warn_alloc(gfp_mask, NULL, 3899 "vmalloc error: size %lu, failed to allocated page array size %lu", 3900 nr_small_pages * PAGE_SIZE, array_size); 3901 goto fail; 3902 } 3903 3904 set_vm_area_page_order(area, page_shift - PAGE_SHIFT); 3905 page_order = vm_area_page_order(area); 3906 3907 /* 3908 * High-order nofail allocations are really expensive and 3909 * potentially dangerous (pre-mature OOM, disruptive reclaim 3910 * and compaction etc. 3911 * 3912 * Please note, the __vmalloc_node_range_noprof() falls-back 3913 * to order-0 pages if high-order attempt is unsuccessful. 3914 */ 3915 area->nr_pages = vm_area_alloc_pages( 3916 vmalloc_gfp_adjust(gfp_mask, page_order), node, 3917 page_order, nr_small_pages, area->pages); 3918 3919 /* 3920 * If not enough pages were obtained to accomplish an 3921 * allocation request, free them via vfree() if any. 3922 */ 3923 if (area->nr_pages != nr_small_pages) { 3924 /* 3925 * vm_area_alloc_pages() can fail due to insufficient memory but 3926 * also:- 3927 * 3928 * - a pending fatal signal 3929 * - insufficient huge page-order pages 3930 * 3931 * Since we always retry allocations at order-0 in the huge page 3932 * case a warning for either is spurious. 3933 */ 3934 if (!fatal_signal_pending(current) && page_order == 0) 3935 warn_alloc(gfp_mask, NULL, 3936 "vmalloc error: size %lu, failed to allocate pages", 3937 nr_small_pages * PAGE_SIZE); 3938 goto fail; 3939 } 3940 3941 /* 3942 * page tables allocations ignore external gfp mask, enforce it 3943 * by the scope API 3944 */ 3945 flags = memalloc_apply_gfp_scope(gfp_mask); 3946 do { 3947 ret = __vmap_pages_range(addr, addr + size, prot, area->pages, 3948 page_shift, nested_gfp); 3949 if (nofail && (ret < 0)) 3950 schedule_timeout_uninterruptible(1); 3951 } while (nofail && (ret < 0)); 3952 memalloc_restore_scope(flags); 3953 3954 if (ret < 0) { 3955 warn_alloc(gfp_mask, NULL, 3956 "vmalloc error: size %lu, failed to map pages", 3957 area->nr_pages * PAGE_SIZE); 3958 goto fail; 3959 } 3960 3961 return area->addr; 3962 3963 fail: 3964 defer_vm_area_cleanup(area); 3965 return NULL; 3966 } 3967 3968 /* 3969 * See __vmalloc_node_range() for a clear list of supported vmalloc flags. 3970 * This gfp lists all flags currently passed through vmalloc. Currently, 3971 * __GFP_ZERO is used by BPF and __GFP_NORETRY is used by percpu. Both drm 3972 * and BPF also use GFP_USER. Additionally, various users pass 3973 * GFP_KERNEL_ACCOUNT. Xfs uses __GFP_NOLOCKDEP. 3974 */ 3975 #define GFP_VMALLOC_SUPPORTED (GFP_KERNEL | GFP_ATOMIC | GFP_NOWAIT |\ 3976 __GFP_NOFAIL | __GFP_ZERO |\ 3977 __GFP_NORETRY | __GFP_RETRY_MAYFAIL |\ 3978 GFP_NOFS | GFP_NOIO | GFP_KERNEL_ACCOUNT |\ 3979 GFP_USER | __GFP_NOLOCKDEP | __GFP_SKIP_KASAN) 3980 3981 static gfp_t vmalloc_fix_flags(gfp_t flags) 3982 { 3983 gfp_t invalid_mask = flags & ~GFP_VMALLOC_SUPPORTED; 3984 3985 flags &= GFP_VMALLOC_SUPPORTED; 3986 WARN_ONCE(1, "Unexpected gfp: %#x (%pGg). Fixing up to gfp: %#x (%pGg). Fix your code!\n", 3987 invalid_mask, &invalid_mask, flags, &flags); 3988 return flags; 3989 } 3990 3991 /** 3992 * __vmalloc_node_range - allocate virtually contiguous memory 3993 * @size: allocation size 3994 * @align: desired alignment 3995 * @start: vm area range start 3996 * @end: vm area range end 3997 * @gfp_mask: flags for the page level allocator 3998 * @prot: protection mask for the allocated pages 3999 * @vm_flags: additional vm area flags (e.g. %VM_NO_GUARD) 4000 * @node: node to use for allocation or NUMA_NO_NODE 4001 * @caller: caller's return address 4002 * 4003 * Allocate enough pages to cover @size from the page level 4004 * allocator with @gfp_mask flags and map them into contiguous 4005 * virtual range with protection @prot. 4006 * 4007 * Supported GFP classes: %GFP_KERNEL, %GFP_ATOMIC, %GFP_NOWAIT, 4008 * %__GFP_RETRY_MAYFAIL, %__GFP_NORETRY, %GFP_NOFS and %GFP_NOIO. 4009 * Zone modifiers are not supported. 4010 * Please note %GFP_ATOMIC and %GFP_NOWAIT are supported only 4011 * by __vmalloc(). 4012 * 4013 * Retry modifiers: only %__GFP_NOFAIL is fully supported; 4014 * %__GFP_NORETRY and %__GFP_RETRY_MAYFAIL are supported with limitation, 4015 * i.e. page tables are allocated with NOWAIT semantic so they might fail 4016 * under moderate memory pressure. 4017 * 4018 * %__GFP_NOWARN can be used to suppress failure messages. 4019 * 4020 * %__GFP_SKIP_KASAN can be used to skip unpoisoning of mapped pages 4021 * (when prot=%PAGE_KERNEL). 4022 * 4023 * Can not be called from interrupt nor NMI contexts. 4024 * Return: the address of the area or %NULL on failure 4025 */ 4026 void *__vmalloc_node_range_noprof(unsigned long size, unsigned long align, 4027 unsigned long start, unsigned long end, gfp_t gfp_mask, 4028 pgprot_t prot, unsigned long vm_flags, int node, 4029 const void *caller) 4030 { 4031 struct vm_struct *area; 4032 void *ret; 4033 kasan_vmalloc_flags_t kasan_flags = KASAN_VMALLOC_NONE; 4034 unsigned long original_align = align; 4035 unsigned int shift = PAGE_SHIFT; 4036 bool skip_vmalloc_kasan = kasan_hw_tags_enabled() && (gfp_mask & __GFP_SKIP_KASAN); 4037 4038 if (WARN_ON_ONCE(!size)) 4039 return NULL; 4040 4041 if ((size >> PAGE_SHIFT) > totalram_pages()) { 4042 warn_alloc(gfp_mask, NULL, 4043 "vmalloc error: size %lu, exceeds total pages", 4044 size); 4045 return NULL; 4046 } 4047 4048 if (vmap_allow_huge && (vm_flags & VM_ALLOW_HUGE_VMAP)) { 4049 /* 4050 * Try huge pages. Only try for PAGE_KERNEL allocations, 4051 * others like modules don't yet expect huge pages in 4052 * their allocations due to apply_to_page_range not 4053 * supporting them. 4054 */ 4055 4056 if (arch_vmap_pmd_supported(prot) && size >= PMD_SIZE) 4057 shift = PMD_SHIFT; 4058 else 4059 shift = arch_vmap_pte_supported_shift(size); 4060 4061 align = max(original_align, 1UL << shift); 4062 } 4063 4064 again: 4065 area = __get_vm_area_node(size, align, shift, VM_ALLOC | 4066 VM_UNINITIALIZED | vm_flags, start, end, node, 4067 gfp_mask & ~__GFP_SKIP_KASAN, caller); 4068 if (!area) { 4069 bool nofail = gfp_mask & __GFP_NOFAIL; 4070 warn_alloc(gfp_mask, NULL, 4071 "vmalloc error: size %lu, align 0x%lx, vm_struct allocation failed%s", 4072 size, align, (nofail) ? ". Retrying." : ""); 4073 if (nofail) { 4074 schedule_timeout_uninterruptible(1); 4075 goto again; 4076 } 4077 goto fail; 4078 } 4079 4080 /* 4081 * Prepare arguments for __vmalloc_area_node() and 4082 * kasan_unpoison_vmalloc(). 4083 */ 4084 if (pgprot_val(prot) == pgprot_val(PAGE_KERNEL)) { 4085 if (kasan_hw_tags_enabled() && !skip_vmalloc_kasan) { 4086 /* 4087 * Modify protection bits to allow tagging. 4088 * This must be done before mapping. 4089 */ 4090 prot = arch_vmap_pgprot_tagged(prot); 4091 4092 /* 4093 * Skip page_alloc poisoning and zeroing for physical 4094 * pages backing VM_ALLOC mapping. Memory is instead 4095 * poisoned and zeroed by kasan_unpoison_vmalloc(). 4096 */ 4097 gfp_mask |= __GFP_SKIP_KASAN | __GFP_SKIP_ZERO; 4098 } 4099 4100 /* Take note that the mapping is PAGE_KERNEL. */ 4101 kasan_flags |= KASAN_VMALLOC_PROT_NORMAL; 4102 } 4103 4104 /* Allocate physical pages and map them into vmalloc space. */ 4105 ret = __vmalloc_area_node(area, gfp_mask, prot, shift, node); 4106 if (!ret) 4107 goto fail; 4108 4109 /* 4110 * Mark the pages as accessible, now that they are mapped. 4111 * The condition for setting KASAN_VMALLOC_INIT should complement the 4112 * one in post_alloc_hook() with regards to the __GFP_SKIP_ZERO check 4113 * to make sure that memory is initialized under the same conditions. 4114 * Tag-based KASAN modes only assign tags to normal non-executable 4115 * allocations, see __kasan_unpoison_vmalloc(). 4116 */ 4117 kasan_flags |= KASAN_VMALLOC_VM_ALLOC; 4118 if (!want_init_on_free() && want_init_on_alloc(gfp_mask) && 4119 (gfp_mask & __GFP_SKIP_ZERO)) 4120 kasan_flags |= KASAN_VMALLOC_INIT; 4121 /* KASAN_VMALLOC_PROT_NORMAL already set if required. */ 4122 if (!skip_vmalloc_kasan) 4123 area->addr = kasan_unpoison_vmalloc(area->addr, size, kasan_flags); 4124 4125 /* 4126 * In this function, newly allocated vm_struct has VM_UNINITIALIZED 4127 * flag. It means that vm_struct is not fully initialized. 4128 * Now, it is fully initialized, so remove this flag here. 4129 */ 4130 clear_vm_uninitialized_flag(area); 4131 4132 if (!(vm_flags & VM_DEFER_KMEMLEAK)) 4133 kmemleak_vmalloc(area, PAGE_ALIGN(size), gfp_mask); 4134 4135 return area->addr; 4136 4137 fail: 4138 if (shift > PAGE_SHIFT) { 4139 shift = PAGE_SHIFT; 4140 align = original_align; 4141 goto again; 4142 } 4143 4144 return NULL; 4145 } 4146 4147 /** 4148 * __vmalloc_node - allocate virtually contiguous memory 4149 * @size: allocation size 4150 * @align: desired alignment 4151 * @gfp_mask: flags for the page level allocator 4152 * @node: node to use for allocation or NUMA_NO_NODE 4153 * @caller: caller's return address 4154 * 4155 * Allocate enough pages to cover @size from the page level allocator with 4156 * @gfp_mask flags. Map them into contiguous kernel virtual space. 4157 * 4158 * Semantics of @gfp_mask (including reclaim/retry modifiers such as 4159 * __GFP_NOFAIL) are the same as in __vmalloc_node_range_noprof(). 4160 * 4161 * Return: pointer to the allocated memory or %NULL on error 4162 */ 4163 void *__vmalloc_node_noprof(unsigned long size, unsigned long align, 4164 gfp_t gfp_mask, int node, const void *caller) 4165 { 4166 return __vmalloc_node_range_noprof(size, align, VMALLOC_START, VMALLOC_END, 4167 gfp_mask, PAGE_KERNEL, 0, node, caller); 4168 } 4169 /* 4170 * This is only for performance analysis of vmalloc and stress purpose. 4171 * It is required by vmalloc test module, therefore do not use it other 4172 * than that. 4173 */ 4174 #ifdef CONFIG_TEST_VMALLOC_MODULE 4175 EXPORT_SYMBOL_GPL(__vmalloc_node_noprof); 4176 #endif 4177 4178 void *__vmalloc_noprof(unsigned long size, gfp_t gfp_mask) 4179 { 4180 if (unlikely(gfp_mask & ~GFP_VMALLOC_SUPPORTED)) 4181 gfp_mask = vmalloc_fix_flags(gfp_mask); 4182 return __vmalloc_node_noprof(size, 1, gfp_mask, NUMA_NO_NODE, 4183 __builtin_return_address(0)); 4184 } 4185 EXPORT_SYMBOL(__vmalloc_noprof); 4186 4187 /** 4188 * vmalloc - allocate virtually contiguous memory 4189 * @size: allocation size 4190 * 4191 * Allocate enough pages to cover @size from the page level 4192 * allocator and map them into contiguous kernel virtual space. 4193 * 4194 * For tight control over page level allocator and protection flags 4195 * use __vmalloc() instead. 4196 * 4197 * Return: pointer to the allocated memory or %NULL on error 4198 */ 4199 void *vmalloc_noprof(unsigned long size) 4200 { 4201 return __vmalloc_node_noprof(size, 1, GFP_KERNEL, NUMA_NO_NODE, 4202 __builtin_return_address(0)); 4203 } 4204 EXPORT_SYMBOL(vmalloc_noprof); 4205 4206 /** 4207 * vmalloc_huge_node - allocate virtually contiguous memory, allow huge pages 4208 * @size: allocation size 4209 * @gfp_mask: flags for the page level allocator 4210 * @node: node to use for allocation or NUMA_NO_NODE 4211 * 4212 * Allocate enough pages to cover @size from the page level 4213 * allocator and map them into contiguous kernel virtual space. 4214 * If @size is greater than or equal to PMD_SIZE, allow using 4215 * huge pages for the memory 4216 * 4217 * Return: pointer to the allocated memory or %NULL on error 4218 */ 4219 void *vmalloc_huge_node_noprof(unsigned long size, gfp_t gfp_mask, int node) 4220 { 4221 if (unlikely(gfp_mask & ~GFP_VMALLOC_SUPPORTED)) 4222 gfp_mask = vmalloc_fix_flags(gfp_mask); 4223 return __vmalloc_node_range_noprof(size, 1, VMALLOC_START, VMALLOC_END, 4224 gfp_mask, PAGE_KERNEL, VM_ALLOW_HUGE_VMAP, 4225 node, __builtin_return_address(0)); 4226 } 4227 EXPORT_SYMBOL_GPL(vmalloc_huge_node_noprof); 4228 4229 /** 4230 * vzalloc - allocate virtually contiguous memory with zero fill 4231 * @size: allocation size 4232 * 4233 * Allocate enough pages to cover @size from the page level 4234 * allocator and map them into contiguous kernel virtual space. 4235 * The memory allocated is set to zero. 4236 * 4237 * For tight control over page level allocator and protection flags 4238 * use __vmalloc() instead. 4239 * 4240 * Return: pointer to the allocated memory or %NULL on error 4241 */ 4242 void *vzalloc_noprof(unsigned long size) 4243 { 4244 return __vmalloc_node_noprof(size, 1, GFP_KERNEL | __GFP_ZERO, NUMA_NO_NODE, 4245 __builtin_return_address(0)); 4246 } 4247 EXPORT_SYMBOL(vzalloc_noprof); 4248 4249 /** 4250 * vmalloc_user - allocate zeroed virtually contiguous memory for userspace 4251 * @size: allocation size 4252 * 4253 * The resulting memory area is zeroed so it can be mapped to userspace 4254 * without leaking data. 4255 * 4256 * Return: pointer to the allocated memory or %NULL on error 4257 */ 4258 void *vmalloc_user_noprof(unsigned long size) 4259 { 4260 return __vmalloc_node_range_noprof(size, SHMLBA, VMALLOC_START, VMALLOC_END, 4261 GFP_KERNEL | __GFP_ZERO, PAGE_KERNEL, 4262 VM_USERMAP, NUMA_NO_NODE, 4263 __builtin_return_address(0)); 4264 } 4265 EXPORT_SYMBOL(vmalloc_user_noprof); 4266 4267 /** 4268 * vmalloc_node - allocate memory on a specific node 4269 * @size: allocation size 4270 * @node: numa node 4271 * 4272 * Allocate enough pages to cover @size from the page level 4273 * allocator and map them into contiguous kernel virtual space. 4274 * 4275 * For tight control over page level allocator and protection flags 4276 * use __vmalloc() instead. 4277 * 4278 * Return: pointer to the allocated memory or %NULL on error 4279 */ 4280 void *vmalloc_node_noprof(unsigned long size, int node) 4281 { 4282 return __vmalloc_node_noprof(size, 1, GFP_KERNEL, node, 4283 __builtin_return_address(0)); 4284 } 4285 EXPORT_SYMBOL(vmalloc_node_noprof); 4286 4287 /** 4288 * vzalloc_node - allocate memory on a specific node with zero fill 4289 * @size: allocation size 4290 * @node: numa node 4291 * 4292 * Allocate enough pages to cover @size from the page level 4293 * allocator and map them into contiguous kernel virtual space. 4294 * The memory allocated is set to zero. 4295 * 4296 * Return: pointer to the allocated memory or %NULL on error 4297 */ 4298 void *vzalloc_node_noprof(unsigned long size, int node) 4299 { 4300 return __vmalloc_node_noprof(size, 1, GFP_KERNEL | __GFP_ZERO, node, 4301 __builtin_return_address(0)); 4302 } 4303 EXPORT_SYMBOL(vzalloc_node_noprof); 4304 4305 /** 4306 * vrealloc_node_align - reallocate virtually contiguous memory; contents 4307 * remain unchanged 4308 * @p: object to reallocate memory for 4309 * @size: the size to reallocate 4310 * @align: requested alignment 4311 * @flags: the flags for the page level allocator 4312 * @nid: node number of the target node 4313 * 4314 * If @p is %NULL, vrealloc_XXX() behaves exactly like vmalloc_XXX(). If @size 4315 * is 0 and @p is not a %NULL pointer, the object pointed to is freed. 4316 * 4317 * If the caller wants the new memory to be on specific node *only*, 4318 * __GFP_THISNODE flag should be set, otherwise the function will try to avoid 4319 * reallocation and possibly disregard the specified @nid. 4320 * 4321 * If __GFP_ZERO logic is requested, callers must ensure that, starting with the 4322 * initial memory allocation, every subsequent call to this API for the same 4323 * memory allocation is flagged with __GFP_ZERO. Otherwise, it is possible that 4324 * __GFP_ZERO is not fully honored by this API. 4325 * 4326 * Requesting an alignment that is bigger than the alignment of the existing 4327 * allocation will fail. 4328 * 4329 * In any case, the contents of the object pointed to are preserved up to the 4330 * lesser of the new and old sizes. 4331 * 4332 * This function must not be called concurrently with itself or vfree() for the 4333 * same memory allocation. 4334 * 4335 * Return: pointer to the allocated memory; %NULL if @size is zero or in case of 4336 * failure 4337 */ 4338 void *vrealloc_node_align_noprof(const void *p, size_t size, unsigned long align, 4339 gfp_t flags, int nid) 4340 { 4341 struct vm_struct *vm = NULL; 4342 size_t alloced_size = 0; 4343 size_t old_size = 0; 4344 void *n; 4345 4346 if (!size) { 4347 vfree(p); 4348 return NULL; 4349 } 4350 4351 if (p) { 4352 vm = find_vm_area(p); 4353 if (unlikely(!vm)) { 4354 WARN(1, "Trying to vrealloc() nonexistent vm area (%p)\n", p); 4355 return NULL; 4356 } 4357 4358 alloced_size = get_vm_area_size(vm); 4359 old_size = vm->requested_size; 4360 if (WARN(alloced_size < old_size, 4361 "vrealloc() has mismatched area vs requested sizes (%p)\n", p)) 4362 return NULL; 4363 if (WARN(!IS_ALIGNED((unsigned long)p, align), 4364 "will not reallocate with a bigger alignment (0x%lx)\n", align)) 4365 return NULL; 4366 if (unlikely(flags & __GFP_THISNODE) && nid != NUMA_NO_NODE && 4367 nid != page_to_nid(vmalloc_to_page(p))) 4368 goto need_realloc; 4369 } else { 4370 /* 4371 * If p is NULL, vrealloc behaves exactly like vmalloc. 4372 * Skip the shrink and in-place grow paths. 4373 */ 4374 goto need_realloc; 4375 } 4376 4377 if (size <= old_size) { 4378 unsigned int new_nr_pages = PAGE_ALIGN(size) >> PAGE_SHIFT; 4379 4380 /* Zero out "freed" memory, potentially for future realloc. */ 4381 if (want_init_on_free() || want_init_on_alloc(flags)) 4382 memset((void *)p + size, 0, old_size - size); 4383 4384 /* 4385 * Free tail pages when shrink crosses a page boundary. 4386 * 4387 * Skip huge page allocations (page_order > 0) as partial 4388 * freeing would require splitting. 4389 * 4390 * Skip VM_FLUSH_RESET_PERMS, as direct-map permissions must 4391 * be reset before pages are returned to the allocator. 4392 * 4393 * Skip VM_USERMAP, as remap_vmalloc_range_partial() validates 4394 * mapping requests against the unchanged vm->size; freeing 4395 * tail pages would cause vmalloc_to_page() to return NULL for 4396 * the unmapped range. 4397 * 4398 * Skip if either GFP_NOFS or GFP_NOIO are used. 4399 * kmemleak_free_part() internally allocates with 4400 * GFP_KERNEL, which could trigger a recursive deadlock 4401 * if we are under filesystem or I/O reclaim. 4402 */ 4403 if (new_nr_pages < vm->nr_pages && !vm_area_page_order(vm) && 4404 !(vm->flags & (VM_FLUSH_RESET_PERMS | VM_USERMAP)) && 4405 gfp_has_io_fs(flags)) { 4406 unsigned long addr = (unsigned long)kasan_reset_tag(p); 4407 unsigned int old_nr_pages = vm->nr_pages; 4408 4409 /* 4410 * Use the node lock to synchronize with concurrent 4411 * readers (vmalloc_info_show). 4412 */ 4413 struct vmap_node *vn = addr_to_node(addr); 4414 4415 spin_lock(&vn->busy.lock); 4416 vm->nr_pages = new_nr_pages; 4417 spin_unlock(&vn->busy.lock); 4418 4419 /* Notify kmemleak of the reduced allocation size before unmapping. */ 4420 kmemleak_free_part( 4421 (void *)addr + ((unsigned long)new_nr_pages 4422 << PAGE_SHIFT), 4423 (unsigned long)(old_nr_pages - new_nr_pages) 4424 << PAGE_SHIFT); 4425 4426 vunmap_range(addr + ((unsigned long)new_nr_pages 4427 << PAGE_SHIFT), 4428 addr + ((unsigned long)old_nr_pages 4429 << PAGE_SHIFT)); 4430 4431 vm_area_free_pages(vm, new_nr_pages, old_nr_pages); 4432 } 4433 vm->requested_size = size; 4434 kasan_vrealloc(p, old_size, size); 4435 return (void *)p; 4436 } 4437 4438 /* 4439 * We already have the bytes available in the allocation; use them. 4440 */ 4441 if (size <= vm->nr_pages << PAGE_SHIFT) { 4442 /* 4443 * No need to zero memory here, as unused memory will have 4444 * already been zeroed at initial allocation time or during 4445 * realloc shrink time. 4446 */ 4447 vm->requested_size = size; 4448 kasan_vrealloc(p, old_size, size); 4449 return (void *)p; 4450 } 4451 4452 need_realloc: 4453 /* TODO: Grow the vm_area, i.e. allocate and map additional pages. */ 4454 n = __vmalloc_node_noprof(size, align, flags, nid, __builtin_return_address(0)); 4455 4456 if (!n) 4457 return NULL; 4458 4459 if (p) { 4460 memcpy(n, p, min(size, old_size)); 4461 vfree(p); 4462 } 4463 4464 return n; 4465 } 4466 EXPORT_SYMBOL(vrealloc_node_align_noprof); 4467 4468 #if defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA32) 4469 #define GFP_VMALLOC32 (GFP_DMA32 | GFP_KERNEL) 4470 #elif defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA) 4471 #define GFP_VMALLOC32 (GFP_DMA | GFP_KERNEL) 4472 #else 4473 /* 4474 * 64b systems should always have either DMA or DMA32 zones. For others 4475 * GFP_DMA32 should do the right thing and use the normal zone. 4476 */ 4477 #define GFP_VMALLOC32 (GFP_DMA32 | GFP_KERNEL) 4478 #endif 4479 4480 /** 4481 * vmalloc_32 - allocate virtually contiguous memory (32bit addressable) 4482 * @size: allocation size 4483 * 4484 * Allocate enough 32bit PA addressable pages to cover @size from the 4485 * page level allocator and map them into contiguous kernel virtual space. 4486 * 4487 * Return: pointer to the allocated memory or %NULL on error 4488 */ 4489 void *vmalloc_32_noprof(unsigned long size) 4490 { 4491 return __vmalloc_node_noprof(size, 1, GFP_VMALLOC32, NUMA_NO_NODE, 4492 __builtin_return_address(0)); 4493 } 4494 EXPORT_SYMBOL(vmalloc_32_noprof); 4495 4496 /** 4497 * vmalloc_32_user - allocate zeroed virtually contiguous 32bit memory 4498 * @size: allocation size 4499 * 4500 * The resulting memory area is 32bit addressable and zeroed so it can be 4501 * mapped to userspace without leaking data. 4502 * 4503 * Return: pointer to the allocated memory or %NULL on error 4504 */ 4505 void *vmalloc_32_user_noprof(unsigned long size) 4506 { 4507 return __vmalloc_node_range_noprof(size, SHMLBA, VMALLOC_START, VMALLOC_END, 4508 GFP_VMALLOC32 | __GFP_ZERO, PAGE_KERNEL, 4509 VM_USERMAP, NUMA_NO_NODE, 4510 __builtin_return_address(0)); 4511 } 4512 EXPORT_SYMBOL(vmalloc_32_user_noprof); 4513 4514 /* 4515 * Atomically zero bytes in the iterator. 4516 * 4517 * Returns the number of zeroed bytes. 4518 */ 4519 static size_t zero_iter(struct iov_iter *iter, size_t count) 4520 { 4521 size_t remains = count; 4522 4523 while (remains > 0) { 4524 size_t num, copied; 4525 4526 num = min_t(size_t, remains, PAGE_SIZE); 4527 copied = copy_page_to_iter_nofault(ZERO_PAGE(0), 0, num, iter); 4528 remains -= copied; 4529 4530 if (copied < num) 4531 break; 4532 } 4533 4534 return count - remains; 4535 } 4536 4537 /* 4538 * small helper routine, copy contents to iter from addr. 4539 * If the page is not present, fill zero. 4540 * 4541 * Returns the number of copied bytes. 4542 */ 4543 static size_t aligned_vread_iter(struct iov_iter *iter, 4544 const char *addr, size_t count) 4545 { 4546 size_t remains = count; 4547 struct page *page; 4548 4549 while (remains > 0) { 4550 unsigned long offset, length; 4551 size_t copied = 0; 4552 4553 offset = offset_in_page(addr); 4554 length = PAGE_SIZE - offset; 4555 if (length > remains) 4556 length = remains; 4557 page = vmalloc_to_page(addr); 4558 /* 4559 * To do safe access to this _mapped_ area, we need lock. But 4560 * adding lock here means that we need to add overhead of 4561 * vmalloc()/vfree() calls for this _debug_ interface, rarely 4562 * used. Instead of that, we'll use an local mapping via 4563 * copy_page_to_iter_nofault() and accept a small overhead in 4564 * this access function. 4565 */ 4566 if (page) 4567 copied = copy_page_to_iter_nofault(page, offset, 4568 length, iter); 4569 else 4570 copied = zero_iter(iter, length); 4571 4572 addr += copied; 4573 remains -= copied; 4574 4575 if (copied != length) 4576 break; 4577 } 4578 4579 return count - remains; 4580 } 4581 4582 /* 4583 * Read from a vm_map_ram region of memory. 4584 * 4585 * Returns the number of copied bytes. 4586 */ 4587 static size_t vmap_ram_vread_iter(struct iov_iter *iter, const char *addr, 4588 size_t count, unsigned long flags) 4589 { 4590 char *start; 4591 struct vmap_block *vb; 4592 struct xarray *xa; 4593 unsigned long offset; 4594 unsigned int rs, re; 4595 size_t remains, n; 4596 4597 /* 4598 * If it's area created by vm_map_ram() interface directly, but 4599 * not further subdividing and delegating management to vmap_block, 4600 * handle it here. 4601 */ 4602 if (!(flags & VMAP_BLOCK)) 4603 return aligned_vread_iter(iter, addr, count); 4604 4605 remains = count; 4606 4607 /* 4608 * Area is split into regions and tracked with vmap_block, read out 4609 * each region and zero fill the hole between regions. 4610 */ 4611 xa = addr_to_vb_xa((unsigned long) addr); 4612 vb = xa_load(xa, addr_to_vb_idx((unsigned long)addr)); 4613 if (!vb) 4614 goto finished_zero; 4615 4616 spin_lock(&vb->lock); 4617 if (bitmap_empty(vb->used_map, VMAP_BBMAP_BITS)) { 4618 spin_unlock(&vb->lock); 4619 goto finished_zero; 4620 } 4621 4622 for_each_set_bitrange(rs, re, vb->used_map, VMAP_BBMAP_BITS) { 4623 size_t copied; 4624 4625 if (remains == 0) 4626 goto finished; 4627 4628 start = vmap_block_vaddr(vb->va->va_start, rs); 4629 4630 if (addr < start) { 4631 size_t to_zero = min_t(size_t, start - addr, remains); 4632 size_t zeroed = zero_iter(iter, to_zero); 4633 4634 addr += zeroed; 4635 remains -= zeroed; 4636 4637 if (remains == 0 || zeroed != to_zero) 4638 goto finished; 4639 } 4640 4641 /*it could start reading from the middle of used region*/ 4642 offset = offset_in_page(addr); 4643 n = ((re - rs + 1) << PAGE_SHIFT) - offset; 4644 if (n > remains) 4645 n = remains; 4646 4647 copied = aligned_vread_iter(iter, start + offset, n); 4648 4649 addr += copied; 4650 remains -= copied; 4651 4652 if (copied != n) 4653 goto finished; 4654 } 4655 4656 spin_unlock(&vb->lock); 4657 4658 finished_zero: 4659 /* zero-fill the left dirty or free regions */ 4660 return count - remains + zero_iter(iter, remains); 4661 finished: 4662 /* We couldn't copy/zero everything */ 4663 spin_unlock(&vb->lock); 4664 return count - remains; 4665 } 4666 4667 /** 4668 * vread_iter() - read vmalloc area in a safe way to an iterator. 4669 * @iter: the iterator to which data should be written. 4670 * @addr: vm address. 4671 * @count: number of bytes to be read. 4672 * 4673 * This function checks that addr is a valid vmalloc'ed area, and 4674 * copies data from that area to a given iterator. If the given memory range 4675 * of [addr...addr+count) includes some valid address, data is copied to 4676 * proper area of @iter. If there are memory holes, they'll be zero-filled. 4677 * IOREMAP area is treated as memory hole and no copy is done. 4678 * 4679 * If [addr...addr+count) doesn't includes any intersects with alive 4680 * vm_struct area, returns 0. 4681 * 4682 * Note: In usual ops, vread_iter() is never necessary because the caller 4683 * should know vmalloc() area is valid and can use memcpy(). 4684 * This is for routines which have to access vmalloc area without 4685 * any information, as /proc/kcore. 4686 * 4687 * Return: number of bytes for which addr and iter should be advanced 4688 * (same number as @count) or %0 if [addr...addr+count) doesn't 4689 * include any intersection with valid vmalloc area 4690 */ 4691 long vread_iter(struct iov_iter *iter, const char *addr, size_t count) 4692 { 4693 struct vmap_node *vn; 4694 struct vmap_area *va; 4695 struct vm_struct *vm; 4696 char *vaddr; 4697 size_t n, size, flags, remains; 4698 unsigned long next; 4699 4700 addr = kasan_reset_tag(addr); 4701 4702 /* Don't allow overflow */ 4703 if ((unsigned long) addr + count < count) 4704 count = -(unsigned long) addr; 4705 4706 remains = count; 4707 4708 vn = find_vmap_area_exceed_addr_lock((unsigned long) addr, &va); 4709 if (!vn) 4710 goto finished_zero; 4711 4712 /* no intersects with alive vmap_area */ 4713 if ((unsigned long)addr + remains <= va->va_start) 4714 goto finished_zero; 4715 4716 do { 4717 size_t copied; 4718 4719 if (remains == 0) 4720 goto finished; 4721 4722 vm = va->vm; 4723 flags = va->flags & VMAP_FLAGS_MASK; 4724 /* 4725 * VMAP_BLOCK indicates a sub-type of vm_map_ram area, need 4726 * be set together with VMAP_RAM. 4727 */ 4728 WARN_ON(flags == VMAP_BLOCK); 4729 4730 if (!vm && !flags) 4731 goto next_va; 4732 4733 if (vm && (vm->flags & VM_UNINITIALIZED)) 4734 goto next_va; 4735 4736 /* Pair with smp_wmb() in clear_vm_uninitialized_flag() */ 4737 smp_rmb(); 4738 4739 vaddr = (char *) va->va_start; 4740 if (vm) 4741 /* 4742 * For VM_ALLOC areas, use nr_pages rather than 4743 * get_vm_area_size() because vrealloc() may shrink 4744 * the mapping without updating area->size. Other 4745 * mapping types (vmap, ioremap) don't set nr_pages. 4746 */ 4747 size = (vm->flags & VM_ALLOC && vm->nr_pages) ? 4748 (vm->nr_pages << PAGE_SHIFT) : 4749 get_vm_area_size(vm); 4750 else 4751 size = va_size(va); 4752 4753 if (addr >= vaddr + size) 4754 goto next_va; 4755 4756 if (addr < vaddr) { 4757 size_t to_zero = min_t(size_t, vaddr - addr, remains); 4758 size_t zeroed = zero_iter(iter, to_zero); 4759 4760 addr += zeroed; 4761 remains -= zeroed; 4762 4763 if (remains == 0 || zeroed != to_zero) 4764 goto finished; 4765 } 4766 4767 n = vaddr + size - addr; 4768 if (n > remains) 4769 n = remains; 4770 4771 if (flags & VMAP_RAM) 4772 copied = vmap_ram_vread_iter(iter, addr, n, flags); 4773 else if (!(vm && (vm->flags & (VM_IOREMAP | VM_SPARSE)))) 4774 copied = aligned_vread_iter(iter, addr, n); 4775 else /* IOREMAP | SPARSE area is treated as memory hole */ 4776 copied = zero_iter(iter, n); 4777 4778 addr += copied; 4779 remains -= copied; 4780 4781 if (copied != n) 4782 goto finished; 4783 4784 next_va: 4785 next = va->va_end; 4786 spin_unlock(&vn->busy.lock); 4787 } while ((vn = find_vmap_area_exceed_addr_lock(next, &va))); 4788 4789 finished_zero: 4790 if (vn) 4791 spin_unlock(&vn->busy.lock); 4792 4793 /* zero-fill memory holes */ 4794 return count - remains + zero_iter(iter, remains); 4795 finished: 4796 /* Nothing remains, or We couldn't copy/zero everything. */ 4797 if (vn) 4798 spin_unlock(&vn->busy.lock); 4799 4800 return count - remains; 4801 } 4802 4803 /** 4804 * remap_vmalloc_range_partial - map vmalloc pages to userspace 4805 * @vma: vma to cover 4806 * @uaddr: target user address to start at 4807 * @kaddr: virtual address of vmalloc kernel memory 4808 * @pgoff: offset from @kaddr to start at 4809 * @size: size of map area 4810 * 4811 * Returns: 0 for success, -Exxx on failure 4812 * 4813 * This function checks that @kaddr is a valid vmalloc'ed area, 4814 * and that it is big enough to cover the range starting at 4815 * @uaddr in @vma. Will return failure if that criteria isn't 4816 * met. 4817 * 4818 * Similar to remap_pfn_range() (see mm/memory.c) 4819 */ 4820 int remap_vmalloc_range_partial(struct vm_area_struct *vma, unsigned long uaddr, 4821 void *kaddr, unsigned long pgoff, 4822 unsigned long size) 4823 { 4824 struct vm_struct *area; 4825 unsigned long off; 4826 unsigned long end_index; 4827 4828 if (check_shl_overflow(pgoff, PAGE_SHIFT, &off)) 4829 return -EINVAL; 4830 4831 size = PAGE_ALIGN(size); 4832 4833 if (!PAGE_ALIGNED(uaddr) || !PAGE_ALIGNED(kaddr)) 4834 return -EINVAL; 4835 4836 area = find_vm_area(kaddr); 4837 if (!area) 4838 return -EINVAL; 4839 4840 if (!(area->flags & (VM_USERMAP | VM_DMA_COHERENT))) 4841 return -EINVAL; 4842 4843 if (check_add_overflow(size, off, &end_index) || 4844 end_index > get_vm_area_size(area)) 4845 return -EINVAL; 4846 kaddr += off; 4847 4848 do { 4849 struct page *page = vmalloc_to_page(kaddr); 4850 int ret; 4851 4852 ret = vm_insert_page(vma, uaddr, page); 4853 if (ret) 4854 return ret; 4855 4856 uaddr += PAGE_SIZE; 4857 kaddr += PAGE_SIZE; 4858 size -= PAGE_SIZE; 4859 } while (size > 0); 4860 4861 vm_flags_set(vma, VM_DONTEXPAND | VM_DONTDUMP); 4862 4863 return 0; 4864 } 4865 4866 /** 4867 * remap_vmalloc_range - map vmalloc pages to userspace 4868 * @vma: vma to cover (map full range of vma) 4869 * @addr: vmalloc memory 4870 * @pgoff: number of pages into addr before first page to map 4871 * 4872 * Returns: 0 for success, -Exxx on failure 4873 * 4874 * This function checks that addr is a valid vmalloc'ed area, and 4875 * that it is big enough to cover the vma. Will return failure if 4876 * that criteria isn't met. 4877 * 4878 * Similar to remap_pfn_range() (see mm/memory.c) 4879 */ 4880 int remap_vmalloc_range(struct vm_area_struct *vma, void *addr, 4881 unsigned long pgoff) 4882 { 4883 return remap_vmalloc_range_partial(vma, vma->vm_start, 4884 addr, pgoff, 4885 vma->vm_end - vma->vm_start); 4886 } 4887 EXPORT_SYMBOL(remap_vmalloc_range); 4888 4889 void free_vm_area(struct vm_struct *area) 4890 { 4891 struct vm_struct *ret; 4892 ret = remove_vm_area(area->addr); 4893 BUG_ON(ret != area); 4894 kfree(area); 4895 } 4896 EXPORT_SYMBOL_GPL(free_vm_area); 4897 4898 #ifdef CONFIG_SMP 4899 static struct vmap_area *node_to_va(struct rb_node *n) 4900 { 4901 return rb_entry_safe(n, struct vmap_area, rb_node); 4902 } 4903 4904 /** 4905 * pvm_find_va_enclose_addr - find the vmap_area @addr belongs to 4906 * @addr: target address 4907 * 4908 * Returns: vmap_area if it is found. If there is no such area 4909 * the first highest(reverse order) vmap_area is returned 4910 * i.e. va->va_start < addr && va->va_end < addr or NULL 4911 * if there are no any areas before @addr. 4912 */ 4913 static struct vmap_area * 4914 pvm_find_va_enclose_addr(unsigned long addr) 4915 { 4916 struct vmap_area *va, *tmp; 4917 struct rb_node *n; 4918 4919 n = free_vmap_area_root.rb_node; 4920 va = NULL; 4921 4922 while (n) { 4923 tmp = rb_entry(n, struct vmap_area, rb_node); 4924 if (tmp->va_start <= addr) { 4925 va = tmp; 4926 if (tmp->va_end >= addr) 4927 break; 4928 4929 n = n->rb_right; 4930 } else { 4931 n = n->rb_left; 4932 } 4933 } 4934 4935 return va; 4936 } 4937 4938 /** 4939 * pvm_determine_end_from_reverse - find the highest aligned address 4940 * of free block below VMALLOC_END 4941 * @va: 4942 * in - the VA we start the search(reverse order); 4943 * out - the VA with the highest aligned end address. 4944 * @align: alignment for required highest address 4945 * 4946 * Returns: determined end address within vmap_area 4947 */ 4948 static unsigned long 4949 pvm_determine_end_from_reverse(struct vmap_area **va, unsigned long align) 4950 { 4951 unsigned long vmalloc_end = VMALLOC_END & ~(align - 1); 4952 unsigned long addr; 4953 4954 if (likely(*va)) { 4955 list_for_each_entry_from_reverse((*va), 4956 &free_vmap_area_list, list) { 4957 addr = min((*va)->va_end & ~(align - 1), vmalloc_end); 4958 if ((*va)->va_start < addr) 4959 return addr; 4960 } 4961 } 4962 4963 return 0; 4964 } 4965 4966 /** 4967 * pcpu_get_vm_areas - allocate vmalloc areas for percpu allocator 4968 * @offsets: array containing offset of each area 4969 * @sizes: array containing size of each area 4970 * @nr_vms: the number of areas to allocate 4971 * @align: alignment, all entries in @offsets and @sizes must be aligned to this 4972 * @gfp: allocation flags passed to the underlying memory allocator 4973 * 4974 * Returns: kmalloc'd vm_struct pointer array pointing to allocated 4975 * vm_structs on success, %NULL on failure 4976 * 4977 * Percpu allocator wants to use congruent vm areas so that it can 4978 * maintain the offsets among percpu areas. This function allocates 4979 * congruent vmalloc areas for it. These areas tend to be scattered 4980 * pretty far, distance between two areas easily going up to gigabytes. 4981 * To avoid interacting with regular vmallocs, these areas are allocated 4982 * from top. 4983 * 4984 * Despite its complicated look, this allocator is rather simple. It 4985 * does everything top-down and scans free blocks from the end looking 4986 * for matching base. While scanning, if any of the areas do not fit the 4987 * base address is pulled down to fit the area. Scanning is repeated till 4988 * all the areas fit and then all necessary data structures are inserted 4989 * and the result is returned. 4990 */ 4991 struct vm_struct **pcpu_get_vm_areas(const unsigned long *offsets, 4992 const size_t *sizes, int nr_vms, 4993 size_t align, gfp_t gfp) 4994 { 4995 const unsigned long vmalloc_start = ALIGN(VMALLOC_START, align); 4996 const unsigned long vmalloc_end = VMALLOC_END & ~(align - 1); 4997 struct vmap_area **vas, *va; 4998 struct vm_struct **vms; 4999 int area, area2, last_area, term_area; 5000 unsigned long base, start, size, end, last_end, orig_start, orig_end; 5001 bool purged = false; 5002 5003 /* verify parameters and allocate data structures */ 5004 BUG_ON(offset_in_page(align) || !is_power_of_2(align)); 5005 for (last_area = 0, area = 0; area < nr_vms; area++) { 5006 start = offsets[area]; 5007 end = start + sizes[area]; 5008 5009 /* is everything aligned properly? */ 5010 BUG_ON(!IS_ALIGNED(offsets[area], align)); 5011 BUG_ON(!IS_ALIGNED(sizes[area], align)); 5012 5013 /* detect the area with the highest address */ 5014 if (start > offsets[last_area]) 5015 last_area = area; 5016 5017 for (area2 = area + 1; area2 < nr_vms; area2++) { 5018 unsigned long start2 = offsets[area2]; 5019 unsigned long end2 = start2 + sizes[area2]; 5020 5021 BUG_ON(start2 < end && start < end2); 5022 } 5023 } 5024 last_end = offsets[last_area] + sizes[last_area]; 5025 5026 if (vmalloc_end - vmalloc_start < last_end) { 5027 WARN_ON(true); 5028 return NULL; 5029 } 5030 5031 vms = kzalloc_objs(vms[0], nr_vms, gfp); 5032 vas = kzalloc_objs(vas[0], nr_vms, gfp); 5033 if (!vas || !vms) 5034 goto err_free2; 5035 5036 for (area = 0; area < nr_vms; area++) { 5037 vas[area] = kmem_cache_zalloc(vmap_area_cachep, gfp); 5038 vms[area] = kzalloc_obj(struct vm_struct, gfp); 5039 if (!vas[area] || !vms[area]) 5040 goto err_free; 5041 } 5042 retry: 5043 spin_lock(&free_vmap_area_lock); 5044 5045 /* start scanning - we scan from the top, begin with the last area */ 5046 area = term_area = last_area; 5047 start = offsets[area]; 5048 end = start + sizes[area]; 5049 5050 va = pvm_find_va_enclose_addr(vmalloc_end); 5051 base = pvm_determine_end_from_reverse(&va, align) - end; 5052 5053 while (true) { 5054 /* 5055 * base might have underflowed, add last_end before 5056 * comparing. 5057 */ 5058 if (base + last_end < vmalloc_start + last_end) 5059 goto overflow; 5060 5061 /* 5062 * Fitting base has not been found. 5063 */ 5064 if (va == NULL) 5065 goto overflow; 5066 5067 /* 5068 * If required width exceeds current VA block, move 5069 * base downwards and then recheck. 5070 */ 5071 if (base + end > va->va_end) { 5072 base = pvm_determine_end_from_reverse(&va, align) - end; 5073 term_area = area; 5074 continue; 5075 } 5076 5077 /* 5078 * If this VA does not fit, move base downwards and recheck. 5079 */ 5080 if (base + start < va->va_start) { 5081 va = node_to_va(rb_prev(&va->rb_node)); 5082 base = pvm_determine_end_from_reverse(&va, align) - end; 5083 term_area = area; 5084 continue; 5085 } 5086 5087 /* 5088 * This area fits, move on to the previous one. If 5089 * the previous one is the terminal one, we're done. 5090 */ 5091 area = (area + nr_vms - 1) % nr_vms; 5092 if (area == term_area) 5093 break; 5094 5095 start = offsets[area]; 5096 end = start + sizes[area]; 5097 va = pvm_find_va_enclose_addr(base + end); 5098 } 5099 5100 /* we've found a fitting base, insert all va's */ 5101 for (area = 0; area < nr_vms; area++) { 5102 int ret; 5103 5104 start = base + offsets[area]; 5105 size = sizes[area]; 5106 5107 va = pvm_find_va_enclose_addr(start); 5108 if (WARN_ON_ONCE(va == NULL)) 5109 /* It is a BUG(), but trigger recovery instead. */ 5110 goto recovery; 5111 5112 ret = va_clip(&free_vmap_area_root, 5113 &free_vmap_area_list, va, start, size); 5114 if (WARN_ON_ONCE(unlikely(ret))) 5115 /* It is a BUG(), but trigger recovery instead. */ 5116 goto recovery; 5117 5118 /* Allocated area. */ 5119 va = vas[area]; 5120 va->va_start = start; 5121 va->va_end = start + size; 5122 } 5123 5124 spin_unlock(&free_vmap_area_lock); 5125 5126 /* populate the kasan shadow space */ 5127 for (area = 0; area < nr_vms; area++) { 5128 if (kasan_populate_vmalloc(vas[area]->va_start, sizes[area], gfp)) 5129 goto err_free_shadow; 5130 } 5131 5132 /* insert all vm's */ 5133 for (area = 0; area < nr_vms; area++) { 5134 struct vmap_node *vn = addr_to_node(vas[area]->va_start); 5135 5136 spin_lock(&vn->busy.lock); 5137 insert_vmap_area(vas[area], &vn->busy.root, &vn->busy.head); 5138 setup_vmalloc_vm(vms[area], vas[area], VM_ALLOC, 5139 pcpu_get_vm_areas); 5140 spin_unlock(&vn->busy.lock); 5141 } 5142 5143 /* 5144 * Mark allocated areas as accessible. Do it now as a best-effort 5145 * approach, as they can be mapped outside of vmalloc code. 5146 * With hardware tag-based KASAN, marking is skipped for 5147 * non-VM_ALLOC mappings, see __kasan_unpoison_vmalloc(). 5148 */ 5149 kasan_unpoison_vmap_areas(vms, nr_vms, KASAN_VMALLOC_PROT_NORMAL); 5150 5151 kfree(vas); 5152 return vms; 5153 5154 recovery: 5155 /* 5156 * Remove previously allocated areas. There is no 5157 * need in removing these areas from the busy tree, 5158 * because they are inserted only on the final step 5159 * and when pcpu_get_vm_areas() is success. 5160 */ 5161 while (area--) { 5162 orig_start = vas[area]->va_start; 5163 orig_end = vas[area]->va_end; 5164 va = merge_or_add_vmap_area_augment(vas[area], &free_vmap_area_root, 5165 &free_vmap_area_list); 5166 if (va) 5167 kasan_release_vmalloc(orig_start, orig_end, 5168 va->va_start, va->va_end, 5169 KASAN_VMALLOC_PAGE_RANGE | KASAN_VMALLOC_TLB_FLUSH); 5170 vas[area] = NULL; 5171 } 5172 5173 overflow: 5174 spin_unlock(&free_vmap_area_lock); 5175 if (!purged) { 5176 reclaim_and_purge_vmap_areas(); 5177 purged = true; 5178 5179 /* Before "retry", check if we recover. */ 5180 for (area = 0; area < nr_vms; area++) { 5181 if (vas[area]) 5182 continue; 5183 5184 vas[area] = kmem_cache_zalloc( 5185 vmap_area_cachep, gfp); 5186 if (!vas[area]) 5187 goto err_free; 5188 } 5189 5190 goto retry; 5191 } 5192 5193 err_free: 5194 for (area = 0; area < nr_vms; area++) { 5195 if (vas[area]) 5196 kmem_cache_free(vmap_area_cachep, vas[area]); 5197 5198 kfree(vms[area]); 5199 } 5200 err_free2: 5201 kfree(vas); 5202 kfree(vms); 5203 return NULL; 5204 5205 err_free_shadow: 5206 spin_lock(&free_vmap_area_lock); 5207 /* 5208 * We release all the vmalloc shadows, even the ones for regions that 5209 * hadn't been successfully added. This relies on kasan_release_vmalloc 5210 * being able to tolerate this case. 5211 */ 5212 for (area = 0; area < nr_vms; area++) { 5213 orig_start = vas[area]->va_start; 5214 orig_end = vas[area]->va_end; 5215 va = merge_or_add_vmap_area_augment(vas[area], &free_vmap_area_root, 5216 &free_vmap_area_list); 5217 if (va) 5218 kasan_release_vmalloc(orig_start, orig_end, 5219 va->va_start, va->va_end, 5220 KASAN_VMALLOC_PAGE_RANGE | KASAN_VMALLOC_TLB_FLUSH); 5221 vas[area] = NULL; 5222 kfree(vms[area]); 5223 } 5224 spin_unlock(&free_vmap_area_lock); 5225 goto err_free2; 5226 } 5227 5228 /** 5229 * pcpu_free_vm_areas - free vmalloc areas for percpu allocator 5230 * @vms: vm_struct pointer array returned by pcpu_get_vm_areas() 5231 * @nr_vms: the number of allocated areas 5232 * 5233 * Free vm_structs and the array allocated by pcpu_get_vm_areas(). 5234 */ 5235 void pcpu_free_vm_areas(struct vm_struct **vms, int nr_vms) 5236 { 5237 int i; 5238 5239 for (i = 0; i < nr_vms; i++) 5240 free_vm_area(vms[i]); 5241 kfree(vms); 5242 } 5243 #endif /* CONFIG_SMP */ 5244 5245 #ifdef CONFIG_PRINTK 5246 bool vmalloc_dump_obj(void *object) 5247 { 5248 const void *caller; 5249 struct vm_struct *vm; 5250 struct vmap_area *va; 5251 struct vmap_node *vn; 5252 unsigned long addr; 5253 unsigned int nr_pages; 5254 5255 addr = PAGE_ALIGN((unsigned long) object); 5256 vn = addr_to_node(addr); 5257 5258 if (!spin_trylock(&vn->busy.lock)) 5259 return false; 5260 5261 va = __find_vmap_area(addr, &vn->busy.root); 5262 if (!va || !va->vm) { 5263 spin_unlock(&vn->busy.lock); 5264 return false; 5265 } 5266 5267 vm = va->vm; 5268 addr = (unsigned long) vm->addr; 5269 caller = vm->caller; 5270 nr_pages = vm->nr_pages; 5271 spin_unlock(&vn->busy.lock); 5272 5273 pr_cont(" %u-page vmalloc region starting at %#lx allocated at %pS\n", 5274 nr_pages, addr, caller); 5275 5276 return true; 5277 } 5278 #endif 5279 5280 #ifdef CONFIG_PROC_FS 5281 5282 /* 5283 * Print number of pages allocated on each memory node. 5284 * 5285 * This function can only be called if CONFIG_NUMA is enabled 5286 * and VM_UNINITIALIZED bit in v->flags is disabled. 5287 */ 5288 static void show_numa_info(struct seq_file *m, struct vm_struct *v, 5289 unsigned int *counters) 5290 { 5291 unsigned int nr; 5292 unsigned int step = 1U << vm_area_page_order(v); 5293 5294 if (!counters) 5295 return; 5296 5297 memset(counters, 0, nr_node_ids * sizeof(unsigned int)); 5298 5299 for (nr = 0; nr < v->nr_pages; nr += step) 5300 counters[page_to_nid(v->pages[nr])] += step; 5301 for_each_node_state(nr, N_HIGH_MEMORY) 5302 if (counters[nr]) 5303 seq_printf(m, " N%u=%u", nr, counters[nr]); 5304 } 5305 5306 static void show_purge_info(struct seq_file *m) 5307 { 5308 struct vmap_node *vn; 5309 struct vmap_area *va; 5310 5311 for_each_vmap_node(vn) { 5312 spin_lock(&vn->lazy.lock); 5313 list_for_each_entry(va, &vn->lazy.head, list) { 5314 seq_printf(m, "0x%pK-0x%pK %7ld unpurged vm_area\n", 5315 (void *)va->va_start, (void *)va->va_end, 5316 va_size(va)); 5317 } 5318 spin_unlock(&vn->lazy.lock); 5319 } 5320 } 5321 5322 static int vmalloc_info_show(struct seq_file *m, void *p) 5323 { 5324 struct vmap_node *vn; 5325 struct vmap_area *va; 5326 struct vm_struct *v; 5327 unsigned int *counters; 5328 5329 if (IS_ENABLED(CONFIG_NUMA)) 5330 counters = kmalloc_array(nr_node_ids, sizeof(unsigned int), GFP_KERNEL); 5331 5332 for_each_vmap_node(vn) { 5333 spin_lock(&vn->busy.lock); 5334 list_for_each_entry(va, &vn->busy.head, list) { 5335 if (!va->vm) { 5336 if (va->flags & VMAP_RAM) 5337 seq_printf(m, "0x%pK-0x%pK %7ld vm_map_ram\n", 5338 (void *)va->va_start, (void *)va->va_end, 5339 va_size(va)); 5340 5341 continue; 5342 } 5343 5344 v = va->vm; 5345 if (v->flags & VM_UNINITIALIZED) 5346 continue; 5347 5348 /* Pair with smp_wmb() in clear_vm_uninitialized_flag() */ 5349 smp_rmb(); 5350 5351 seq_printf(m, "0x%pK-0x%pK %7ld", 5352 v->addr, v->addr + v->size, v->size); 5353 5354 if (v->caller) 5355 seq_printf(m, " %pS", v->caller); 5356 5357 if (v->nr_pages) 5358 seq_printf(m, " pages=%d", v->nr_pages); 5359 5360 if (v->phys_addr) 5361 seq_printf(m, " phys=%pa", &v->phys_addr); 5362 5363 if (v->flags & VM_IOREMAP) 5364 seq_puts(m, " ioremap"); 5365 5366 if (v->flags & VM_SPARSE) 5367 seq_puts(m, " sparse"); 5368 5369 if (v->flags & VM_ALLOC) 5370 seq_puts(m, " vmalloc"); 5371 5372 if (v->flags & VM_MAP) 5373 seq_puts(m, " vmap"); 5374 5375 if (v->flags & VM_USERMAP) 5376 seq_puts(m, " user"); 5377 5378 if (v->flags & VM_DMA_COHERENT) 5379 seq_puts(m, " dma-coherent"); 5380 5381 if (is_vmalloc_addr(v->pages)) 5382 seq_puts(m, " vpages"); 5383 5384 if (IS_ENABLED(CONFIG_NUMA)) 5385 show_numa_info(m, v, counters); 5386 5387 seq_putc(m, '\n'); 5388 } 5389 spin_unlock(&vn->busy.lock); 5390 } 5391 5392 /* 5393 * As a final step, dump "unpurged" areas. 5394 */ 5395 show_purge_info(m); 5396 if (IS_ENABLED(CONFIG_NUMA)) 5397 kfree(counters); 5398 return 0; 5399 } 5400 5401 static int __init proc_vmalloc_init(void) 5402 { 5403 proc_create_single("vmallocinfo", 0400, NULL, vmalloc_info_show); 5404 return 0; 5405 } 5406 module_init(proc_vmalloc_init); 5407 5408 #endif 5409 5410 static void __init vmap_init_free_space(void) 5411 { 5412 unsigned long vmap_start = 1; 5413 const unsigned long vmap_end = ULONG_MAX; 5414 struct vmap_area *free; 5415 struct vm_struct *busy; 5416 5417 /* 5418 * B F B B B F 5419 * -|-----|.....|-----|-----|-----|.....|- 5420 * | The KVA space | 5421 * |<--------------------------------->| 5422 */ 5423 for (busy = vmlist; busy; busy = busy->next) { 5424 if ((unsigned long) busy->addr - vmap_start > 0) { 5425 free = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT); 5426 if (!WARN_ON_ONCE(!free)) { 5427 free->va_start = vmap_start; 5428 free->va_end = (unsigned long) busy->addr; 5429 5430 insert_vmap_area_augment(free, NULL, 5431 &free_vmap_area_root, 5432 &free_vmap_area_list); 5433 } 5434 } 5435 5436 vmap_start = (unsigned long) busy->addr + busy->size; 5437 } 5438 5439 if (vmap_end - vmap_start > 0) { 5440 free = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT); 5441 if (!WARN_ON_ONCE(!free)) { 5442 free->va_start = vmap_start; 5443 free->va_end = vmap_end; 5444 5445 insert_vmap_area_augment(free, NULL, 5446 &free_vmap_area_root, 5447 &free_vmap_area_list); 5448 } 5449 } 5450 } 5451 5452 static void vmap_init_nodes(void) 5453 { 5454 struct vmap_node *vn; 5455 int i; 5456 5457 #if BITS_PER_LONG == 64 5458 /* 5459 * A high threshold of max nodes is fixed and bound to 128, 5460 * thus a scale factor is 1 for systems where number of cores 5461 * are less or equal to specified threshold. 5462 * 5463 * As for NUMA-aware notes. For bigger systems, for example 5464 * NUMA with multi-sockets, where we can end-up with thousands 5465 * of cores in total, a "sub-numa-clustering" should be added. 5466 * 5467 * In this case a NUMA domain is considered as a single entity 5468 * with dedicated sub-nodes in it which describe one group or 5469 * set of cores. Therefore a per-domain purging is supposed to 5470 * be added as well as a per-domain balancing. 5471 */ 5472 int n = clamp_t(unsigned int, num_possible_cpus(), 1, 128); 5473 5474 if (n > 1) { 5475 vn = kmalloc_objs(*vn, n, GFP_NOWAIT); 5476 if (vn) { 5477 /* Node partition is 16 pages. */ 5478 vmap_zone_size = (1 << 4) * PAGE_SIZE; 5479 nr_vmap_nodes = n; 5480 vmap_nodes = vn; 5481 } else { 5482 pr_err("Failed to allocate an array. Disable a node layer\n"); 5483 } 5484 } 5485 #endif 5486 5487 for_each_vmap_node(vn) { 5488 vn->busy.root = RB_ROOT; 5489 INIT_LIST_HEAD(&vn->busy.head); 5490 spin_lock_init(&vn->busy.lock); 5491 5492 vn->lazy.root = RB_ROOT; 5493 INIT_LIST_HEAD(&vn->lazy.head); 5494 spin_lock_init(&vn->lazy.lock); 5495 5496 for (i = 0; i < MAX_VA_SIZE_PAGES; i++) { 5497 INIT_LIST_HEAD(&vn->pool[i].head); 5498 WRITE_ONCE(vn->pool[i].len, 0); 5499 } 5500 5501 spin_lock_init(&vn->pool_lock); 5502 } 5503 } 5504 5505 static unsigned long 5506 vmap_node_shrink_count(struct shrinker *shrink, struct shrink_control *sc) 5507 { 5508 unsigned long count = 0; 5509 struct vmap_node *vn; 5510 int i; 5511 5512 for_each_vmap_node(vn) { 5513 for (i = 0; i < MAX_VA_SIZE_PAGES; i++) 5514 count += READ_ONCE(vn->pool[i].len); 5515 } 5516 5517 return count ? count : SHRINK_EMPTY; 5518 } 5519 5520 static unsigned long 5521 vmap_node_shrink_scan(struct shrinker *shrink, struct shrink_control *sc) 5522 { 5523 struct vmap_node *vn; 5524 5525 guard(mutex)(&vmap_purge_lock); 5526 for_each_vmap_node(vn) 5527 decay_va_pool_node(vn, true); 5528 5529 return SHRINK_STOP; 5530 } 5531 5532 void __init vmalloc_init(void) 5533 { 5534 struct shrinker *vmap_node_shrinker; 5535 struct vmap_area *va; 5536 struct vmap_node *vn; 5537 struct vm_struct *tmp; 5538 int i; 5539 5540 /* 5541 * Create the cache for vmap_area objects. 5542 */ 5543 vmap_area_cachep = KMEM_CACHE(vmap_area, SLAB_PANIC); 5544 5545 for_each_possible_cpu(i) { 5546 struct vmap_block_queue *vbq; 5547 struct vfree_deferred *p; 5548 5549 vbq = &per_cpu(vmap_block_queue, i); 5550 spin_lock_init(&vbq->lock); 5551 INIT_LIST_HEAD(&vbq->free); 5552 p = &per_cpu(vfree_deferred, i); 5553 init_llist_head(&p->list); 5554 INIT_WORK(&p->wq, delayed_vfree_work); 5555 xa_init(&vbq->vmap_blocks); 5556 } 5557 5558 /* 5559 * Setup nodes before importing vmlist. 5560 */ 5561 vmap_init_nodes(); 5562 5563 /* Import existing vmlist entries. */ 5564 for (tmp = vmlist; tmp; tmp = tmp->next) { 5565 va = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT); 5566 if (WARN_ON_ONCE(!va)) 5567 continue; 5568 5569 va->va_start = (unsigned long)tmp->addr; 5570 va->va_end = va->va_start + tmp->size; 5571 va->vm = tmp; 5572 5573 vn = addr_to_node(va->va_start); 5574 insert_vmap_area(va, &vn->busy.root, &vn->busy.head); 5575 } 5576 5577 /* 5578 * Now we can initialize a free vmap space. 5579 */ 5580 vmap_init_free_space(); 5581 vmap_initialized = true; 5582 5583 vmap_node_shrinker = shrinker_alloc(0, "vmap-node"); 5584 if (!vmap_node_shrinker) { 5585 pr_err("Failed to allocate vmap-node shrinker!\n"); 5586 return; 5587 } 5588 5589 vmap_node_shrinker->count_objects = vmap_node_shrink_count; 5590 vmap_node_shrinker->scan_objects = vmap_node_shrink_scan; 5591 shrinker_register(vmap_node_shrinker); 5592 } 5593