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