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