1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 1993 Linus Torvalds
4 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
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
11 #include <linux/vmalloc.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>
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/llist.h>
35 #include <linux/bitops.h>
36 #include <linux/rbtree_augmented.h>
37 #include <linux/overflow.h>
38 #include <linux/pgtable.h>
39 #include <linux/uaccess.h>
40 #include <linux/hugetlb.h>
41 #include <asm/tlbflush.h>
42 #include <asm/shmparam.h>
45 #include "pgalloc-track.h"
47 #ifdef CONFIG_HAVE_ARCH_HUGE_VMAP
48 static unsigned int __ro_after_init ioremap_max_page_shift = BITS_PER_LONG - 1;
50 static int __init set_nohugeiomap(char *str)
52 ioremap_max_page_shift = PAGE_SHIFT;
55 early_param("nohugeiomap", set_nohugeiomap);
56 #else /* CONFIG_HAVE_ARCH_HUGE_VMAP */
57 static const unsigned int ioremap_max_page_shift = PAGE_SHIFT;
58 #endif /* CONFIG_HAVE_ARCH_HUGE_VMAP */
60 #ifdef CONFIG_HAVE_ARCH_HUGE_VMALLOC
61 static bool __ro_after_init vmap_allow_huge = true;
63 static int __init set_nohugevmalloc(char *str)
65 vmap_allow_huge = false;
68 early_param("nohugevmalloc", set_nohugevmalloc);
69 #else /* CONFIG_HAVE_ARCH_HUGE_VMALLOC */
70 static const bool vmap_allow_huge = false;
71 #endif /* CONFIG_HAVE_ARCH_HUGE_VMALLOC */
73 bool is_vmalloc_addr(const void *x)
75 unsigned long addr = (unsigned long)x;
77 return addr >= VMALLOC_START && addr < VMALLOC_END;
79 EXPORT_SYMBOL(is_vmalloc_addr);
81 struct vfree_deferred {
82 struct llist_head list;
83 struct work_struct wq;
85 static DEFINE_PER_CPU(struct vfree_deferred, vfree_deferred);
87 static void __vunmap(const void *, int);
89 static void free_work(struct work_struct *w)
91 struct vfree_deferred *p = container_of(w, struct vfree_deferred, wq);
92 struct llist_node *t, *llnode;
94 llist_for_each_safe(llnode, t, llist_del_all(&p->list))
95 __vunmap((void *)llnode, 1);
98 /*** Page table manipulation functions ***/
99 static int vmap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
100 phys_addr_t phys_addr, pgprot_t prot,
101 unsigned int max_page_shift, pgtbl_mod_mask *mask)
105 unsigned long size = PAGE_SIZE;
107 pfn = phys_addr >> PAGE_SHIFT;
108 pte = pte_alloc_kernel_track(pmd, addr, mask);
112 BUG_ON(!pte_none(*pte));
114 #ifdef CONFIG_HUGETLB_PAGE
115 size = arch_vmap_pte_range_map_size(addr, end, pfn, max_page_shift);
116 if (size != PAGE_SIZE) {
117 pte_t entry = pfn_pte(pfn, prot);
119 entry = pte_mkhuge(entry);
120 entry = arch_make_huge_pte(entry, ilog2(size), 0);
121 set_huge_pte_at(&init_mm, addr, pte, entry);
122 pfn += PFN_DOWN(size);
126 set_pte_at(&init_mm, addr, pte, pfn_pte(pfn, prot));
128 } while (pte += PFN_DOWN(size), addr += size, addr != end);
129 *mask |= PGTBL_PTE_MODIFIED;
133 static int vmap_try_huge_pmd(pmd_t *pmd, unsigned long addr, unsigned long end,
134 phys_addr_t phys_addr, pgprot_t prot,
135 unsigned int max_page_shift)
137 if (max_page_shift < PMD_SHIFT)
140 if (!arch_vmap_pmd_supported(prot))
143 if ((end - addr) != PMD_SIZE)
146 if (!IS_ALIGNED(addr, PMD_SIZE))
149 if (!IS_ALIGNED(phys_addr, PMD_SIZE))
152 if (pmd_present(*pmd) && !pmd_free_pte_page(pmd, addr))
155 return pmd_set_huge(pmd, phys_addr, prot);
158 static int vmap_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,
159 phys_addr_t phys_addr, pgprot_t prot,
160 unsigned int max_page_shift, pgtbl_mod_mask *mask)
165 pmd = pmd_alloc_track(&init_mm, pud, addr, mask);
169 next = pmd_addr_end(addr, end);
171 if (vmap_try_huge_pmd(pmd, addr, next, phys_addr, prot,
173 *mask |= PGTBL_PMD_MODIFIED;
177 if (vmap_pte_range(pmd, addr, next, phys_addr, prot, max_page_shift, mask))
179 } while (pmd++, phys_addr += (next - addr), addr = next, addr != end);
183 static int vmap_try_huge_pud(pud_t *pud, unsigned long addr, unsigned long end,
184 phys_addr_t phys_addr, pgprot_t prot,
185 unsigned int max_page_shift)
187 if (max_page_shift < PUD_SHIFT)
190 if (!arch_vmap_pud_supported(prot))
193 if ((end - addr) != PUD_SIZE)
196 if (!IS_ALIGNED(addr, PUD_SIZE))
199 if (!IS_ALIGNED(phys_addr, PUD_SIZE))
202 if (pud_present(*pud) && !pud_free_pmd_page(pud, addr))
205 return pud_set_huge(pud, phys_addr, prot);
208 static int vmap_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end,
209 phys_addr_t phys_addr, pgprot_t prot,
210 unsigned int max_page_shift, pgtbl_mod_mask *mask)
215 pud = pud_alloc_track(&init_mm, p4d, addr, mask);
219 next = pud_addr_end(addr, end);
221 if (vmap_try_huge_pud(pud, addr, next, phys_addr, prot,
223 *mask |= PGTBL_PUD_MODIFIED;
227 if (vmap_pmd_range(pud, addr, next, phys_addr, prot,
228 max_page_shift, mask))
230 } while (pud++, phys_addr += (next - addr), addr = next, addr != end);
234 static int vmap_try_huge_p4d(p4d_t *p4d, unsigned long addr, unsigned long end,
235 phys_addr_t phys_addr, pgprot_t prot,
236 unsigned int max_page_shift)
238 if (max_page_shift < P4D_SHIFT)
241 if (!arch_vmap_p4d_supported(prot))
244 if ((end - addr) != P4D_SIZE)
247 if (!IS_ALIGNED(addr, P4D_SIZE))
250 if (!IS_ALIGNED(phys_addr, P4D_SIZE))
253 if (p4d_present(*p4d) && !p4d_free_pud_page(p4d, addr))
256 return p4d_set_huge(p4d, phys_addr, prot);
259 static int vmap_p4d_range(pgd_t *pgd, unsigned long addr, unsigned long end,
260 phys_addr_t phys_addr, pgprot_t prot,
261 unsigned int max_page_shift, pgtbl_mod_mask *mask)
266 p4d = p4d_alloc_track(&init_mm, pgd, addr, mask);
270 next = p4d_addr_end(addr, end);
272 if (vmap_try_huge_p4d(p4d, addr, next, phys_addr, prot,
274 *mask |= PGTBL_P4D_MODIFIED;
278 if (vmap_pud_range(p4d, addr, next, phys_addr, prot,
279 max_page_shift, mask))
281 } while (p4d++, phys_addr += (next - addr), addr = next, addr != end);
285 static int vmap_range_noflush(unsigned long addr, unsigned long end,
286 phys_addr_t phys_addr, pgprot_t prot,
287 unsigned int max_page_shift)
293 pgtbl_mod_mask mask = 0;
299 pgd = pgd_offset_k(addr);
301 next = pgd_addr_end(addr, end);
302 err = vmap_p4d_range(pgd, addr, next, phys_addr, prot,
303 max_page_shift, &mask);
306 } while (pgd++, phys_addr += (next - addr), addr = next, addr != end);
308 if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
309 arch_sync_kernel_mappings(start, end);
314 int ioremap_page_range(unsigned long addr, unsigned long end,
315 phys_addr_t phys_addr, pgprot_t prot)
319 err = vmap_range_noflush(addr, end, phys_addr, pgprot_nx(prot),
320 ioremap_max_page_shift);
321 flush_cache_vmap(addr, end);
325 static void vunmap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
326 pgtbl_mod_mask *mask)
330 pte = pte_offset_kernel(pmd, addr);
332 pte_t ptent = ptep_get_and_clear(&init_mm, addr, pte);
333 WARN_ON(!pte_none(ptent) && !pte_present(ptent));
334 } while (pte++, addr += PAGE_SIZE, addr != end);
335 *mask |= PGTBL_PTE_MODIFIED;
338 static void vunmap_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,
339 pgtbl_mod_mask *mask)
345 pmd = pmd_offset(pud, addr);
347 next = pmd_addr_end(addr, end);
349 cleared = pmd_clear_huge(pmd);
350 if (cleared || pmd_bad(*pmd))
351 *mask |= PGTBL_PMD_MODIFIED;
355 if (pmd_none_or_clear_bad(pmd))
357 vunmap_pte_range(pmd, addr, next, mask);
360 } while (pmd++, addr = next, addr != end);
363 static void vunmap_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end,
364 pgtbl_mod_mask *mask)
370 pud = pud_offset(p4d, addr);
372 next = pud_addr_end(addr, end);
374 cleared = pud_clear_huge(pud);
375 if (cleared || pud_bad(*pud))
376 *mask |= PGTBL_PUD_MODIFIED;
380 if (pud_none_or_clear_bad(pud))
382 vunmap_pmd_range(pud, addr, next, mask);
383 } while (pud++, addr = next, addr != end);
386 static void vunmap_p4d_range(pgd_t *pgd, unsigned long addr, unsigned long end,
387 pgtbl_mod_mask *mask)
393 p4d = p4d_offset(pgd, addr);
395 next = p4d_addr_end(addr, end);
397 cleared = p4d_clear_huge(p4d);
398 if (cleared || p4d_bad(*p4d))
399 *mask |= PGTBL_P4D_MODIFIED;
403 if (p4d_none_or_clear_bad(p4d))
405 vunmap_pud_range(p4d, addr, next, mask);
406 } while (p4d++, addr = next, addr != end);
410 * vunmap_range_noflush is similar to vunmap_range, but does not
411 * flush caches or TLBs.
413 * The caller is responsible for calling flush_cache_vmap() before calling
414 * this function, and flush_tlb_kernel_range after it has returned
415 * successfully (and before the addresses are expected to cause a page fault
416 * or be re-mapped for something else, if TLB flushes are being delayed or
419 * This is an internal function only. Do not use outside mm/.
421 void vunmap_range_noflush(unsigned long start, unsigned long end)
425 unsigned long addr = start;
426 pgtbl_mod_mask mask = 0;
429 pgd = pgd_offset_k(addr);
431 next = pgd_addr_end(addr, end);
433 mask |= PGTBL_PGD_MODIFIED;
434 if (pgd_none_or_clear_bad(pgd))
436 vunmap_p4d_range(pgd, addr, next, &mask);
437 } while (pgd++, addr = next, addr != end);
439 if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
440 arch_sync_kernel_mappings(start, end);
444 * vunmap_range - unmap kernel virtual addresses
445 * @addr: start of the VM area to unmap
446 * @end: end of the VM area to unmap (non-inclusive)
448 * Clears any present PTEs in the virtual address range, flushes TLBs and
449 * caches. Any subsequent access to the address before it has been re-mapped
452 void vunmap_range(unsigned long addr, unsigned long end)
454 flush_cache_vunmap(addr, end);
455 vunmap_range_noflush(addr, end);
456 flush_tlb_kernel_range(addr, end);
459 static int vmap_pages_pte_range(pmd_t *pmd, unsigned long addr,
460 unsigned long end, pgprot_t prot, struct page **pages, int *nr,
461 pgtbl_mod_mask *mask)
466 * nr is a running index into the array which helps higher level
467 * callers keep track of where we're up to.
470 pte = pte_alloc_kernel_track(pmd, addr, mask);
474 struct page *page = pages[*nr];
476 if (WARN_ON(!pte_none(*pte)))
480 set_pte_at(&init_mm, addr, pte, mk_pte(page, prot));
482 } while (pte++, addr += PAGE_SIZE, addr != end);
483 *mask |= PGTBL_PTE_MODIFIED;
487 static int vmap_pages_pmd_range(pud_t *pud, unsigned long addr,
488 unsigned long end, pgprot_t prot, struct page **pages, int *nr,
489 pgtbl_mod_mask *mask)
494 pmd = pmd_alloc_track(&init_mm, pud, addr, mask);
498 next = pmd_addr_end(addr, end);
499 if (vmap_pages_pte_range(pmd, addr, next, prot, pages, nr, mask))
501 } while (pmd++, addr = next, addr != end);
505 static int vmap_pages_pud_range(p4d_t *p4d, unsigned long addr,
506 unsigned long end, pgprot_t prot, struct page **pages, int *nr,
507 pgtbl_mod_mask *mask)
512 pud = pud_alloc_track(&init_mm, p4d, addr, mask);
516 next = pud_addr_end(addr, end);
517 if (vmap_pages_pmd_range(pud, addr, next, prot, pages, nr, mask))
519 } while (pud++, addr = next, addr != end);
523 static int vmap_pages_p4d_range(pgd_t *pgd, unsigned long addr,
524 unsigned long end, pgprot_t prot, struct page **pages, int *nr,
525 pgtbl_mod_mask *mask)
530 p4d = p4d_alloc_track(&init_mm, pgd, addr, mask);
534 next = p4d_addr_end(addr, end);
535 if (vmap_pages_pud_range(p4d, addr, next, prot, pages, nr, mask))
537 } while (p4d++, addr = next, addr != end);
541 static int vmap_small_pages_range_noflush(unsigned long addr, unsigned long end,
542 pgprot_t prot, struct page **pages)
544 unsigned long start = addr;
549 pgtbl_mod_mask mask = 0;
552 pgd = pgd_offset_k(addr);
554 next = pgd_addr_end(addr, end);
556 mask |= PGTBL_PGD_MODIFIED;
557 err = vmap_pages_p4d_range(pgd, addr, next, prot, pages, &nr, &mask);
560 } while (pgd++, addr = next, addr != end);
562 if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
563 arch_sync_kernel_mappings(start, end);
569 * vmap_pages_range_noflush is similar to vmap_pages_range, but does not
572 * The caller is responsible for calling flush_cache_vmap() after this
573 * function returns successfully and before the addresses are accessed.
575 * This is an internal function only. Do not use outside mm/.
577 int vmap_pages_range_noflush(unsigned long addr, unsigned long end,
578 pgprot_t prot, struct page **pages, unsigned int page_shift)
580 unsigned int i, nr = (end - addr) >> PAGE_SHIFT;
582 WARN_ON(page_shift < PAGE_SHIFT);
584 if (!IS_ENABLED(CONFIG_HAVE_ARCH_HUGE_VMALLOC) ||
585 page_shift == PAGE_SHIFT)
586 return vmap_small_pages_range_noflush(addr, end, prot, pages);
588 for (i = 0; i < nr; i += 1U << (page_shift - PAGE_SHIFT)) {
591 err = vmap_range_noflush(addr, addr + (1UL << page_shift),
592 __pa(page_address(pages[i])), prot,
597 addr += 1UL << page_shift;
604 * vmap_pages_range - map pages to a kernel virtual address
605 * @addr: start of the VM area to map
606 * @end: end of the VM area to map (non-inclusive)
607 * @prot: page protection flags to use
608 * @pages: pages to map (always PAGE_SIZE pages)
609 * @page_shift: maximum shift that the pages may be mapped with, @pages must
610 * be aligned and contiguous up to at least this shift.
613 * 0 on success, -errno on failure.
615 static int vmap_pages_range(unsigned long addr, unsigned long end,
616 pgprot_t prot, struct page **pages, unsigned int page_shift)
620 err = vmap_pages_range_noflush(addr, end, prot, pages, page_shift);
621 flush_cache_vmap(addr, end);
625 int is_vmalloc_or_module_addr(const void *x)
628 * ARM, x86-64 and sparc64 put modules in a special place,
629 * and fall back on vmalloc() if that fails. Others
630 * just put it in the vmalloc space.
632 #if defined(CONFIG_MODULES) && defined(MODULES_VADDR)
633 unsigned long addr = (unsigned long)x;
634 if (addr >= MODULES_VADDR && addr < MODULES_END)
637 return is_vmalloc_addr(x);
641 * Walk a vmap address to the struct page it maps. Huge vmap mappings will
642 * return the tail page that corresponds to the base page address, which
643 * matches small vmap mappings.
645 struct page *vmalloc_to_page(const void *vmalloc_addr)
647 unsigned long addr = (unsigned long) vmalloc_addr;
648 struct page *page = NULL;
649 pgd_t *pgd = pgd_offset_k(addr);
656 * XXX we might need to change this if we add VIRTUAL_BUG_ON for
657 * architectures that do not vmalloc module space
659 VIRTUAL_BUG_ON(!is_vmalloc_or_module_addr(vmalloc_addr));
663 if (WARN_ON_ONCE(pgd_leaf(*pgd)))
664 return NULL; /* XXX: no allowance for huge pgd */
665 if (WARN_ON_ONCE(pgd_bad(*pgd)))
668 p4d = p4d_offset(pgd, addr);
672 return p4d_page(*p4d) + ((addr & ~P4D_MASK) >> PAGE_SHIFT);
673 if (WARN_ON_ONCE(p4d_bad(*p4d)))
676 pud = pud_offset(p4d, addr);
680 return pud_page(*pud) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
681 if (WARN_ON_ONCE(pud_bad(*pud)))
684 pmd = pmd_offset(pud, addr);
688 return pmd_page(*pmd) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
689 if (WARN_ON_ONCE(pmd_bad(*pmd)))
692 ptep = pte_offset_map(pmd, addr);
694 if (pte_present(pte))
695 page = pte_page(pte);
700 EXPORT_SYMBOL(vmalloc_to_page);
703 * Map a vmalloc()-space virtual address to the physical page frame number.
705 unsigned long vmalloc_to_pfn(const void *vmalloc_addr)
707 return page_to_pfn(vmalloc_to_page(vmalloc_addr));
709 EXPORT_SYMBOL(vmalloc_to_pfn);
712 /*** Global kva allocator ***/
714 #define DEBUG_AUGMENT_PROPAGATE_CHECK 0
715 #define DEBUG_AUGMENT_LOWEST_MATCH_CHECK 0
718 static DEFINE_SPINLOCK(vmap_area_lock);
719 static DEFINE_SPINLOCK(free_vmap_area_lock);
720 /* Export for kexec only */
721 LIST_HEAD(vmap_area_list);
722 static struct rb_root vmap_area_root = RB_ROOT;
723 static bool vmap_initialized __read_mostly;
725 static struct rb_root purge_vmap_area_root = RB_ROOT;
726 static LIST_HEAD(purge_vmap_area_list);
727 static DEFINE_SPINLOCK(purge_vmap_area_lock);
730 * This kmem_cache is used for vmap_area objects. Instead of
731 * allocating from slab we reuse an object from this cache to
732 * make things faster. Especially in "no edge" splitting of
735 static struct kmem_cache *vmap_area_cachep;
738 * This linked list is used in pair with free_vmap_area_root.
739 * It gives O(1) access to prev/next to perform fast coalescing.
741 static LIST_HEAD(free_vmap_area_list);
744 * This augment red-black tree represents the free vmap space.
745 * All vmap_area objects in this tree are sorted by va->va_start
746 * address. It is used for allocation and merging when a vmap
747 * object is released.
749 * Each vmap_area node contains a maximum available free block
750 * of its sub-tree, right or left. Therefore it is possible to
751 * find a lowest match of free area.
753 static struct rb_root free_vmap_area_root = RB_ROOT;
756 * Preload a CPU with one object for "no edge" split case. The
757 * aim is to get rid of allocations from the atomic context, thus
758 * to use more permissive allocation masks.
760 static DEFINE_PER_CPU(struct vmap_area *, ne_fit_preload_node);
762 static __always_inline unsigned long
763 va_size(struct vmap_area *va)
765 return (va->va_end - va->va_start);
768 static __always_inline unsigned long
769 get_subtree_max_size(struct rb_node *node)
771 struct vmap_area *va;
773 va = rb_entry_safe(node, struct vmap_area, rb_node);
774 return va ? va->subtree_max_size : 0;
778 * Gets called when remove the node and rotate.
780 static __always_inline unsigned long
781 compute_subtree_max_size(struct vmap_area *va)
783 return max3(va_size(va),
784 get_subtree_max_size(va->rb_node.rb_left),
785 get_subtree_max_size(va->rb_node.rb_right));
788 RB_DECLARE_CALLBACKS_MAX(static, free_vmap_area_rb_augment_cb,
789 struct vmap_area, rb_node, unsigned long, subtree_max_size, va_size)
791 static void purge_vmap_area_lazy(void);
792 static BLOCKING_NOTIFIER_HEAD(vmap_notify_list);
793 static unsigned long lazy_max_pages(void);
795 static atomic_long_t nr_vmalloc_pages;
797 unsigned long vmalloc_nr_pages(void)
799 return atomic_long_read(&nr_vmalloc_pages);
802 static struct vmap_area *find_vmap_area_exceed_addr(unsigned long addr)
804 struct vmap_area *va = NULL;
805 struct rb_node *n = vmap_area_root.rb_node;
808 struct vmap_area *tmp;
810 tmp = rb_entry(n, struct vmap_area, rb_node);
811 if (tmp->va_end > addr) {
813 if (tmp->va_start <= addr)
824 static struct vmap_area *__find_vmap_area(unsigned long addr)
826 struct rb_node *n = vmap_area_root.rb_node;
829 struct vmap_area *va;
831 va = rb_entry(n, struct vmap_area, rb_node);
832 if (addr < va->va_start)
834 else if (addr >= va->va_end)
844 * This function returns back addresses of parent node
845 * and its left or right link for further processing.
847 * Otherwise NULL is returned. In that case all further
848 * steps regarding inserting of conflicting overlap range
849 * have to be declined and actually considered as a bug.
851 static __always_inline struct rb_node **
852 find_va_links(struct vmap_area *va,
853 struct rb_root *root, struct rb_node *from,
854 struct rb_node **parent)
856 struct vmap_area *tmp_va;
857 struct rb_node **link;
860 link = &root->rb_node;
861 if (unlikely(!*link)) {
870 * Go to the bottom of the tree. When we hit the last point
871 * we end up with parent rb_node and correct direction, i name
872 * it link, where the new va->rb_node will be attached to.
875 tmp_va = rb_entry(*link, struct vmap_area, rb_node);
878 * During the traversal we also do some sanity check.
879 * Trigger the BUG() if there are sides(left/right)
882 if (va->va_start < tmp_va->va_end &&
883 va->va_end <= tmp_va->va_start)
884 link = &(*link)->rb_left;
885 else if (va->va_end > tmp_va->va_start &&
886 va->va_start >= tmp_va->va_end)
887 link = &(*link)->rb_right;
889 WARN(1, "vmalloc bug: 0x%lx-0x%lx overlaps with 0x%lx-0x%lx\n",
890 va->va_start, va->va_end, tmp_va->va_start, tmp_va->va_end);
896 *parent = &tmp_va->rb_node;
900 static __always_inline struct list_head *
901 get_va_next_sibling(struct rb_node *parent, struct rb_node **link)
903 struct list_head *list;
905 if (unlikely(!parent))
907 * The red-black tree where we try to find VA neighbors
908 * before merging or inserting is empty, i.e. it means
909 * there is no free vmap space. Normally it does not
910 * happen but we handle this case anyway.
914 list = &rb_entry(parent, struct vmap_area, rb_node)->list;
915 return (&parent->rb_right == link ? list->next : list);
918 static __always_inline void
919 link_va(struct vmap_area *va, struct rb_root *root,
920 struct rb_node *parent, struct rb_node **link, struct list_head *head)
923 * VA is still not in the list, but we can
924 * identify its future previous list_head node.
926 if (likely(parent)) {
927 head = &rb_entry(parent, struct vmap_area, rb_node)->list;
928 if (&parent->rb_right != link)
932 /* Insert to the rb-tree */
933 rb_link_node(&va->rb_node, parent, link);
934 if (root == &free_vmap_area_root) {
936 * Some explanation here. Just perform simple insertion
937 * to the tree. We do not set va->subtree_max_size to
938 * its current size before calling rb_insert_augmented().
939 * It is because of we populate the tree from the bottom
940 * to parent levels when the node _is_ in the tree.
942 * Therefore we set subtree_max_size to zero after insertion,
943 * to let __augment_tree_propagate_from() puts everything to
944 * the correct order later on.
946 rb_insert_augmented(&va->rb_node,
947 root, &free_vmap_area_rb_augment_cb);
948 va->subtree_max_size = 0;
950 rb_insert_color(&va->rb_node, root);
953 /* Address-sort this list */
954 list_add(&va->list, head);
957 static __always_inline void
958 unlink_va(struct vmap_area *va, struct rb_root *root)
960 if (WARN_ON(RB_EMPTY_NODE(&va->rb_node)))
963 if (root == &free_vmap_area_root)
964 rb_erase_augmented(&va->rb_node,
965 root, &free_vmap_area_rb_augment_cb);
967 rb_erase(&va->rb_node, root);
970 RB_CLEAR_NODE(&va->rb_node);
973 #if DEBUG_AUGMENT_PROPAGATE_CHECK
975 augment_tree_propagate_check(void)
977 struct vmap_area *va;
978 unsigned long computed_size;
980 list_for_each_entry(va, &free_vmap_area_list, list) {
981 computed_size = compute_subtree_max_size(va);
982 if (computed_size != va->subtree_max_size)
983 pr_emerg("tree is corrupted: %lu, %lu\n",
984 va_size(va), va->subtree_max_size);
990 * This function populates subtree_max_size from bottom to upper
991 * levels starting from VA point. The propagation must be done
992 * when VA size is modified by changing its va_start/va_end. Or
993 * in case of newly inserting of VA to the tree.
995 * It means that __augment_tree_propagate_from() must be called:
996 * - After VA has been inserted to the tree(free path);
997 * - After VA has been shrunk(allocation path);
998 * - After VA has been increased(merging path).
1000 * Please note that, it does not mean that upper parent nodes
1001 * and their subtree_max_size are recalculated all the time up
1010 * For example if we modify the node 4, shrinking it to 2, then
1011 * no any modification is required. If we shrink the node 2 to 1
1012 * its subtree_max_size is updated only, and set to 1. If we shrink
1013 * the node 8 to 6, then its subtree_max_size is set to 6 and parent
1014 * node becomes 4--6.
1016 static __always_inline void
1017 augment_tree_propagate_from(struct vmap_area *va)
1020 * Populate the tree from bottom towards the root until
1021 * the calculated maximum available size of checked node
1022 * is equal to its current one.
1024 free_vmap_area_rb_augment_cb_propagate(&va->rb_node, NULL);
1026 #if DEBUG_AUGMENT_PROPAGATE_CHECK
1027 augment_tree_propagate_check();
1032 insert_vmap_area(struct vmap_area *va,
1033 struct rb_root *root, struct list_head *head)
1035 struct rb_node **link;
1036 struct rb_node *parent;
1038 link = find_va_links(va, root, NULL, &parent);
1040 link_va(va, root, parent, link, head);
1044 insert_vmap_area_augment(struct vmap_area *va,
1045 struct rb_node *from, struct rb_root *root,
1046 struct list_head *head)
1048 struct rb_node **link;
1049 struct rb_node *parent;
1052 link = find_va_links(va, NULL, from, &parent);
1054 link = find_va_links(va, root, NULL, &parent);
1057 link_va(va, root, parent, link, head);
1058 augment_tree_propagate_from(va);
1063 * Merge de-allocated chunk of VA memory with previous
1064 * and next free blocks. If coalesce is not done a new
1065 * free area is inserted. If VA has been merged, it is
1068 * Please note, it can return NULL in case of overlap
1069 * ranges, followed by WARN() report. Despite it is a
1070 * buggy behaviour, a system can be alive and keep
1073 static __always_inline struct vmap_area *
1074 merge_or_add_vmap_area(struct vmap_area *va,
1075 struct rb_root *root, struct list_head *head)
1077 struct vmap_area *sibling;
1078 struct list_head *next;
1079 struct rb_node **link;
1080 struct rb_node *parent;
1081 bool merged = false;
1084 * Find a place in the tree where VA potentially will be
1085 * inserted, unless it is merged with its sibling/siblings.
1087 link = find_va_links(va, root, NULL, &parent);
1092 * Get next node of VA to check if merging can be done.
1094 next = get_va_next_sibling(parent, link);
1095 if (unlikely(next == NULL))
1101 * |<------VA------>|<-----Next----->|
1106 sibling = list_entry(next, struct vmap_area, list);
1107 if (sibling->va_start == va->va_end) {
1108 sibling->va_start = va->va_start;
1110 /* Free vmap_area object. */
1111 kmem_cache_free(vmap_area_cachep, va);
1113 /* Point to the new merged area. */
1122 * |<-----Prev----->|<------VA------>|
1126 if (next->prev != head) {
1127 sibling = list_entry(next->prev, struct vmap_area, list);
1128 if (sibling->va_end == va->va_start) {
1130 * If both neighbors are coalesced, it is important
1131 * to unlink the "next" node first, followed by merging
1132 * with "previous" one. Otherwise the tree might not be
1133 * fully populated if a sibling's augmented value is
1134 * "normalized" because of rotation operations.
1137 unlink_va(va, root);
1139 sibling->va_end = va->va_end;
1141 /* Free vmap_area object. */
1142 kmem_cache_free(vmap_area_cachep, va);
1144 /* Point to the new merged area. */
1152 link_va(va, root, parent, link, head);
1157 static __always_inline struct vmap_area *
1158 merge_or_add_vmap_area_augment(struct vmap_area *va,
1159 struct rb_root *root, struct list_head *head)
1161 va = merge_or_add_vmap_area(va, root, head);
1163 augment_tree_propagate_from(va);
1168 static __always_inline bool
1169 is_within_this_va(struct vmap_area *va, unsigned long size,
1170 unsigned long align, unsigned long vstart)
1172 unsigned long nva_start_addr;
1174 if (va->va_start > vstart)
1175 nva_start_addr = ALIGN(va->va_start, align);
1177 nva_start_addr = ALIGN(vstart, align);
1179 /* Can be overflowed due to big size or alignment. */
1180 if (nva_start_addr + size < nva_start_addr ||
1181 nva_start_addr < vstart)
1184 return (nva_start_addr + size <= va->va_end);
1188 * Find the first free block(lowest start address) in the tree,
1189 * that will accomplish the request corresponding to passing
1192 static __always_inline struct vmap_area *
1193 find_vmap_lowest_match(unsigned long size,
1194 unsigned long align, unsigned long vstart)
1196 struct vmap_area *va;
1197 struct rb_node *node;
1199 /* Start from the root. */
1200 node = free_vmap_area_root.rb_node;
1203 va = rb_entry(node, struct vmap_area, rb_node);
1205 if (get_subtree_max_size(node->rb_left) >= size &&
1206 vstart < va->va_start) {
1207 node = node->rb_left;
1209 if (is_within_this_va(va, size, align, vstart))
1213 * Does not make sense to go deeper towards the right
1214 * sub-tree if it does not have a free block that is
1215 * equal or bigger to the requested search size.
1217 if (get_subtree_max_size(node->rb_right) >= size) {
1218 node = node->rb_right;
1223 * OK. We roll back and find the first right sub-tree,
1224 * that will satisfy the search criteria. It can happen
1225 * due to "vstart" restriction or an alignment overhead
1226 * that is bigger then PAGE_SIZE.
1228 while ((node = rb_parent(node))) {
1229 va = rb_entry(node, struct vmap_area, rb_node);
1230 if (is_within_this_va(va, size, align, vstart))
1233 if (get_subtree_max_size(node->rb_right) >= size &&
1234 vstart <= va->va_start) {
1236 * Shift the vstart forward. Please note, we update it with
1237 * parent's start address adding "1" because we do not want
1238 * to enter same sub-tree after it has already been checked
1239 * and no suitable free block found there.
1241 vstart = va->va_start + 1;
1242 node = node->rb_right;
1252 #if DEBUG_AUGMENT_LOWEST_MATCH_CHECK
1253 #include <linux/random.h>
1255 static struct vmap_area *
1256 find_vmap_lowest_linear_match(unsigned long size,
1257 unsigned long align, unsigned long vstart)
1259 struct vmap_area *va;
1261 list_for_each_entry(va, &free_vmap_area_list, list) {
1262 if (!is_within_this_va(va, size, align, vstart))
1272 find_vmap_lowest_match_check(unsigned long size, unsigned long align)
1274 struct vmap_area *va_1, *va_2;
1275 unsigned long vstart;
1278 get_random_bytes(&rnd, sizeof(rnd));
1279 vstart = VMALLOC_START + rnd;
1281 va_1 = find_vmap_lowest_match(size, align, vstart);
1282 va_2 = find_vmap_lowest_linear_match(size, align, vstart);
1285 pr_emerg("not lowest: t: 0x%p, l: 0x%p, v: 0x%lx\n",
1286 va_1, va_2, vstart);
1292 FL_FIT_TYPE = 1, /* full fit */
1293 LE_FIT_TYPE = 2, /* left edge fit */
1294 RE_FIT_TYPE = 3, /* right edge fit */
1295 NE_FIT_TYPE = 4 /* no edge fit */
1298 static __always_inline enum fit_type
1299 classify_va_fit_type(struct vmap_area *va,
1300 unsigned long nva_start_addr, unsigned long size)
1304 /* Check if it is within VA. */
1305 if (nva_start_addr < va->va_start ||
1306 nva_start_addr + size > va->va_end)
1310 if (va->va_start == nva_start_addr) {
1311 if (va->va_end == nva_start_addr + size)
1315 } else if (va->va_end == nva_start_addr + size) {
1324 static __always_inline int
1325 adjust_va_to_fit_type(struct vmap_area *va,
1326 unsigned long nva_start_addr, unsigned long size,
1329 struct vmap_area *lva = NULL;
1331 if (type == FL_FIT_TYPE) {
1333 * No need to split VA, it fully fits.
1339 unlink_va(va, &free_vmap_area_root);
1340 kmem_cache_free(vmap_area_cachep, va);
1341 } else if (type == LE_FIT_TYPE) {
1343 * Split left edge of fit VA.
1349 va->va_start += size;
1350 } else if (type == RE_FIT_TYPE) {
1352 * Split right edge of fit VA.
1358 va->va_end = nva_start_addr;
1359 } else if (type == NE_FIT_TYPE) {
1361 * Split no edge of fit VA.
1367 lva = __this_cpu_xchg(ne_fit_preload_node, NULL);
1368 if (unlikely(!lva)) {
1370 * For percpu allocator we do not do any pre-allocation
1371 * and leave it as it is. The reason is it most likely
1372 * never ends up with NE_FIT_TYPE splitting. In case of
1373 * percpu allocations offsets and sizes are aligned to
1374 * fixed align request, i.e. RE_FIT_TYPE and FL_FIT_TYPE
1375 * are its main fitting cases.
1377 * There are a few exceptions though, as an example it is
1378 * a first allocation (early boot up) when we have "one"
1379 * big free space that has to be split.
1381 * Also we can hit this path in case of regular "vmap"
1382 * allocations, if "this" current CPU was not preloaded.
1383 * See the comment in alloc_vmap_area() why. If so, then
1384 * GFP_NOWAIT is used instead to get an extra object for
1385 * split purpose. That is rare and most time does not
1388 * What happens if an allocation gets failed. Basically,
1389 * an "overflow" path is triggered to purge lazily freed
1390 * areas to free some memory, then, the "retry" path is
1391 * triggered to repeat one more time. See more details
1392 * in alloc_vmap_area() function.
1394 lva = kmem_cache_alloc(vmap_area_cachep, GFP_NOWAIT);
1400 * Build the remainder.
1402 lva->va_start = va->va_start;
1403 lva->va_end = nva_start_addr;
1406 * Shrink this VA to remaining size.
1408 va->va_start = nva_start_addr + size;
1413 if (type != FL_FIT_TYPE) {
1414 augment_tree_propagate_from(va);
1416 if (lva) /* type == NE_FIT_TYPE */
1417 insert_vmap_area_augment(lva, &va->rb_node,
1418 &free_vmap_area_root, &free_vmap_area_list);
1425 * Returns a start address of the newly allocated area, if success.
1426 * Otherwise a vend is returned that indicates failure.
1428 static __always_inline unsigned long
1429 __alloc_vmap_area(unsigned long size, unsigned long align,
1430 unsigned long vstart, unsigned long vend)
1432 unsigned long nva_start_addr;
1433 struct vmap_area *va;
1437 va = find_vmap_lowest_match(size, align, vstart);
1441 if (va->va_start > vstart)
1442 nva_start_addr = ALIGN(va->va_start, align);
1444 nva_start_addr = ALIGN(vstart, align);
1446 /* Check the "vend" restriction. */
1447 if (nva_start_addr + size > vend)
1450 /* Classify what we have found. */
1451 type = classify_va_fit_type(va, nva_start_addr, size);
1452 if (WARN_ON_ONCE(type == NOTHING_FIT))
1455 /* Update the free vmap_area. */
1456 ret = adjust_va_to_fit_type(va, nva_start_addr, size, type);
1460 #if DEBUG_AUGMENT_LOWEST_MATCH_CHECK
1461 find_vmap_lowest_match_check(size, align);
1464 return nva_start_addr;
1468 * Free a region of KVA allocated by alloc_vmap_area
1470 static void free_vmap_area(struct vmap_area *va)
1473 * Remove from the busy tree/list.
1475 spin_lock(&vmap_area_lock);
1476 unlink_va(va, &vmap_area_root);
1477 spin_unlock(&vmap_area_lock);
1480 * Insert/Merge it back to the free tree/list.
1482 spin_lock(&free_vmap_area_lock);
1483 merge_or_add_vmap_area_augment(va, &free_vmap_area_root, &free_vmap_area_list);
1484 spin_unlock(&free_vmap_area_lock);
1488 preload_this_cpu_lock(spinlock_t *lock, gfp_t gfp_mask, int node)
1490 struct vmap_area *va = NULL;
1493 * Preload this CPU with one extra vmap_area object. It is used
1494 * when fit type of free area is NE_FIT_TYPE. It guarantees that
1495 * a CPU that does an allocation is preloaded.
1497 * We do it in non-atomic context, thus it allows us to use more
1498 * permissive allocation masks to be more stable under low memory
1499 * condition and high memory pressure.
1501 if (!this_cpu_read(ne_fit_preload_node))
1502 va = kmem_cache_alloc_node(vmap_area_cachep, gfp_mask, node);
1506 if (va && __this_cpu_cmpxchg(ne_fit_preload_node, NULL, va))
1507 kmem_cache_free(vmap_area_cachep, va);
1511 * Allocate a region of KVA of the specified size and alignment, within the
1514 static struct vmap_area *alloc_vmap_area(unsigned long size,
1515 unsigned long align,
1516 unsigned long vstart, unsigned long vend,
1517 int node, gfp_t gfp_mask)
1519 struct vmap_area *va;
1520 unsigned long freed;
1526 BUG_ON(offset_in_page(size));
1527 BUG_ON(!is_power_of_2(align));
1529 if (unlikely(!vmap_initialized))
1530 return ERR_PTR(-EBUSY);
1533 gfp_mask = gfp_mask & GFP_RECLAIM_MASK;
1535 va = kmem_cache_alloc_node(vmap_area_cachep, gfp_mask, node);
1537 return ERR_PTR(-ENOMEM);
1540 * Only scan the relevant parts containing pointers to other objects
1541 * to avoid false negatives.
1543 kmemleak_scan_area(&va->rb_node, SIZE_MAX, gfp_mask);
1546 preload_this_cpu_lock(&free_vmap_area_lock, gfp_mask, node);
1547 addr = __alloc_vmap_area(size, align, vstart, vend);
1548 spin_unlock(&free_vmap_area_lock);
1551 * If an allocation fails, the "vend" address is
1552 * returned. Therefore trigger the overflow path.
1554 if (unlikely(addr == vend))
1557 va->va_start = addr;
1558 va->va_end = addr + size;
1561 spin_lock(&vmap_area_lock);
1562 insert_vmap_area(va, &vmap_area_root, &vmap_area_list);
1563 spin_unlock(&vmap_area_lock);
1565 BUG_ON(!IS_ALIGNED(va->va_start, align));
1566 BUG_ON(va->va_start < vstart);
1567 BUG_ON(va->va_end > vend);
1569 ret = kasan_populate_vmalloc(addr, size);
1572 return ERR_PTR(ret);
1579 purge_vmap_area_lazy();
1585 blocking_notifier_call_chain(&vmap_notify_list, 0, &freed);
1592 if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit())
1593 pr_warn("vmap allocation for size %lu failed: use vmalloc=<size> to increase size\n",
1596 kmem_cache_free(vmap_area_cachep, va);
1597 return ERR_PTR(-EBUSY);
1600 int register_vmap_purge_notifier(struct notifier_block *nb)
1602 return blocking_notifier_chain_register(&vmap_notify_list, nb);
1604 EXPORT_SYMBOL_GPL(register_vmap_purge_notifier);
1606 int unregister_vmap_purge_notifier(struct notifier_block *nb)
1608 return blocking_notifier_chain_unregister(&vmap_notify_list, nb);
1610 EXPORT_SYMBOL_GPL(unregister_vmap_purge_notifier);
1613 * lazy_max_pages is the maximum amount of virtual address space we gather up
1614 * before attempting to purge with a TLB flush.
1616 * There is a tradeoff here: a larger number will cover more kernel page tables
1617 * and take slightly longer to purge, but it will linearly reduce the number of
1618 * global TLB flushes that must be performed. It would seem natural to scale
1619 * this number up linearly with the number of CPUs (because vmapping activity
1620 * could also scale linearly with the number of CPUs), however it is likely
1621 * that in practice, workloads might be constrained in other ways that mean
1622 * vmap activity will not scale linearly with CPUs. Also, I want to be
1623 * conservative and not introduce a big latency on huge systems, so go with
1624 * a less aggressive log scale. It will still be an improvement over the old
1625 * code, and it will be simple to change the scale factor if we find that it
1626 * becomes a problem on bigger systems.
1628 static unsigned long lazy_max_pages(void)
1632 log = fls(num_online_cpus());
1634 return log * (32UL * 1024 * 1024 / PAGE_SIZE);
1637 static atomic_long_t vmap_lazy_nr = ATOMIC_LONG_INIT(0);
1640 * Serialize vmap purging. There is no actual critical section protected
1641 * by this look, but we want to avoid concurrent calls for performance
1642 * reasons and to make the pcpu_get_vm_areas more deterministic.
1644 static DEFINE_MUTEX(vmap_purge_lock);
1646 /* for per-CPU blocks */
1647 static void purge_fragmented_blocks_allcpus(void);
1649 #ifdef CONFIG_X86_64
1651 * called before a call to iounmap() if the caller wants vm_area_struct's
1652 * immediately freed.
1654 void set_iounmap_nonlazy(void)
1656 atomic_long_set(&vmap_lazy_nr, lazy_max_pages()+1);
1658 #endif /* CONFIG_X86_64 */
1661 * Purges all lazily-freed vmap areas.
1663 static bool __purge_vmap_area_lazy(unsigned long start, unsigned long end)
1665 unsigned long resched_threshold;
1666 struct list_head local_pure_list;
1667 struct vmap_area *va, *n_va;
1669 lockdep_assert_held(&vmap_purge_lock);
1671 spin_lock(&purge_vmap_area_lock);
1672 purge_vmap_area_root = RB_ROOT;
1673 list_replace_init(&purge_vmap_area_list, &local_pure_list);
1674 spin_unlock(&purge_vmap_area_lock);
1676 if (unlikely(list_empty(&local_pure_list)))
1680 list_first_entry(&local_pure_list,
1681 struct vmap_area, list)->va_start);
1684 list_last_entry(&local_pure_list,
1685 struct vmap_area, list)->va_end);
1687 flush_tlb_kernel_range(start, end);
1688 resched_threshold = lazy_max_pages() << 1;
1690 spin_lock(&free_vmap_area_lock);
1691 list_for_each_entry_safe(va, n_va, &local_pure_list, list) {
1692 unsigned long nr = (va->va_end - va->va_start) >> PAGE_SHIFT;
1693 unsigned long orig_start = va->va_start;
1694 unsigned long orig_end = va->va_end;
1697 * Finally insert or merge lazily-freed area. It is
1698 * detached and there is no need to "unlink" it from
1701 va = merge_or_add_vmap_area_augment(va, &free_vmap_area_root,
1702 &free_vmap_area_list);
1707 if (is_vmalloc_or_module_addr((void *)orig_start))
1708 kasan_release_vmalloc(orig_start, orig_end,
1709 va->va_start, va->va_end);
1711 atomic_long_sub(nr, &vmap_lazy_nr);
1713 if (atomic_long_read(&vmap_lazy_nr) < resched_threshold)
1714 cond_resched_lock(&free_vmap_area_lock);
1716 spin_unlock(&free_vmap_area_lock);
1721 * Kick off a purge of the outstanding lazy areas. Don't bother if somebody
1722 * is already purging.
1724 static void try_purge_vmap_area_lazy(void)
1726 if (mutex_trylock(&vmap_purge_lock)) {
1727 __purge_vmap_area_lazy(ULONG_MAX, 0);
1728 mutex_unlock(&vmap_purge_lock);
1733 * Kick off a purge of the outstanding lazy areas.
1735 static void purge_vmap_area_lazy(void)
1737 mutex_lock(&vmap_purge_lock);
1738 purge_fragmented_blocks_allcpus();
1739 __purge_vmap_area_lazy(ULONG_MAX, 0);
1740 mutex_unlock(&vmap_purge_lock);
1744 * Free a vmap area, caller ensuring that the area has been unmapped
1745 * and flush_cache_vunmap had been called for the correct range
1748 static void free_vmap_area_noflush(struct vmap_area *va)
1750 unsigned long nr_lazy;
1752 spin_lock(&vmap_area_lock);
1753 unlink_va(va, &vmap_area_root);
1754 spin_unlock(&vmap_area_lock);
1756 nr_lazy = atomic_long_add_return((va->va_end - va->va_start) >>
1757 PAGE_SHIFT, &vmap_lazy_nr);
1760 * Merge or place it to the purge tree/list.
1762 spin_lock(&purge_vmap_area_lock);
1763 merge_or_add_vmap_area(va,
1764 &purge_vmap_area_root, &purge_vmap_area_list);
1765 spin_unlock(&purge_vmap_area_lock);
1767 /* After this point, we may free va at any time */
1768 if (unlikely(nr_lazy > lazy_max_pages()))
1769 try_purge_vmap_area_lazy();
1773 * Free and unmap a vmap area
1775 static void free_unmap_vmap_area(struct vmap_area *va)
1777 flush_cache_vunmap(va->va_start, va->va_end);
1778 vunmap_range_noflush(va->va_start, va->va_end);
1779 if (debug_pagealloc_enabled_static())
1780 flush_tlb_kernel_range(va->va_start, va->va_end);
1782 free_vmap_area_noflush(va);
1785 static struct vmap_area *find_vmap_area(unsigned long addr)
1787 struct vmap_area *va;
1789 spin_lock(&vmap_area_lock);
1790 va = __find_vmap_area(addr);
1791 spin_unlock(&vmap_area_lock);
1796 /*** Per cpu kva allocator ***/
1799 * vmap space is limited especially on 32 bit architectures. Ensure there is
1800 * room for at least 16 percpu vmap blocks per CPU.
1803 * If we had a constant VMALLOC_START and VMALLOC_END, we'd like to be able
1804 * to #define VMALLOC_SPACE (VMALLOC_END-VMALLOC_START). Guess
1805 * instead (we just need a rough idea)
1807 #if BITS_PER_LONG == 32
1808 #define VMALLOC_SPACE (128UL*1024*1024)
1810 #define VMALLOC_SPACE (128UL*1024*1024*1024)
1813 #define VMALLOC_PAGES (VMALLOC_SPACE / PAGE_SIZE)
1814 #define VMAP_MAX_ALLOC BITS_PER_LONG /* 256K with 4K pages */
1815 #define VMAP_BBMAP_BITS_MAX 1024 /* 4MB with 4K pages */
1816 #define VMAP_BBMAP_BITS_MIN (VMAP_MAX_ALLOC*2)
1817 #define VMAP_MIN(x, y) ((x) < (y) ? (x) : (y)) /* can't use min() */
1818 #define VMAP_MAX(x, y) ((x) > (y) ? (x) : (y)) /* can't use max() */
1819 #define VMAP_BBMAP_BITS \
1820 VMAP_MIN(VMAP_BBMAP_BITS_MAX, \
1821 VMAP_MAX(VMAP_BBMAP_BITS_MIN, \
1822 VMALLOC_PAGES / roundup_pow_of_two(NR_CPUS) / 16))
1824 #define VMAP_BLOCK_SIZE (VMAP_BBMAP_BITS * PAGE_SIZE)
1826 struct vmap_block_queue {
1828 struct list_head free;
1833 struct vmap_area *va;
1834 unsigned long free, dirty;
1835 unsigned long dirty_min, dirty_max; /*< dirty range */
1836 struct list_head free_list;
1837 struct rcu_head rcu_head;
1838 struct list_head purge;
1841 /* Queue of free and dirty vmap blocks, for allocation and flushing purposes */
1842 static DEFINE_PER_CPU(struct vmap_block_queue, vmap_block_queue);
1845 * XArray of vmap blocks, indexed by address, to quickly find a vmap block
1846 * in the free path. Could get rid of this if we change the API to return a
1847 * "cookie" from alloc, to be passed to free. But no big deal yet.
1849 static DEFINE_XARRAY(vmap_blocks);
1852 * We should probably have a fallback mechanism to allocate virtual memory
1853 * out of partially filled vmap blocks. However vmap block sizing should be
1854 * fairly reasonable according to the vmalloc size, so it shouldn't be a
1858 static unsigned long addr_to_vb_idx(unsigned long addr)
1860 addr -= VMALLOC_START & ~(VMAP_BLOCK_SIZE-1);
1861 addr /= VMAP_BLOCK_SIZE;
1865 static void *vmap_block_vaddr(unsigned long va_start, unsigned long pages_off)
1869 addr = va_start + (pages_off << PAGE_SHIFT);
1870 BUG_ON(addr_to_vb_idx(addr) != addr_to_vb_idx(va_start));
1871 return (void *)addr;
1875 * new_vmap_block - allocates new vmap_block and occupies 2^order pages in this
1876 * block. Of course pages number can't exceed VMAP_BBMAP_BITS
1877 * @order: how many 2^order pages should be occupied in newly allocated block
1878 * @gfp_mask: flags for the page level allocator
1880 * Return: virtual address in a newly allocated block or ERR_PTR(-errno)
1882 static void *new_vmap_block(unsigned int order, gfp_t gfp_mask)
1884 struct vmap_block_queue *vbq;
1885 struct vmap_block *vb;
1886 struct vmap_area *va;
1887 unsigned long vb_idx;
1891 node = numa_node_id();
1893 vb = kmalloc_node(sizeof(struct vmap_block),
1894 gfp_mask & GFP_RECLAIM_MASK, node);
1896 return ERR_PTR(-ENOMEM);
1898 va = alloc_vmap_area(VMAP_BLOCK_SIZE, VMAP_BLOCK_SIZE,
1899 VMALLOC_START, VMALLOC_END,
1903 return ERR_CAST(va);
1906 vaddr = vmap_block_vaddr(va->va_start, 0);
1907 spin_lock_init(&vb->lock);
1909 /* At least something should be left free */
1910 BUG_ON(VMAP_BBMAP_BITS <= (1UL << order));
1911 vb->free = VMAP_BBMAP_BITS - (1UL << order);
1913 vb->dirty_min = VMAP_BBMAP_BITS;
1915 INIT_LIST_HEAD(&vb->free_list);
1917 vb_idx = addr_to_vb_idx(va->va_start);
1918 err = xa_insert(&vmap_blocks, vb_idx, vb, gfp_mask);
1922 return ERR_PTR(err);
1925 vbq = &get_cpu_var(vmap_block_queue);
1926 spin_lock(&vbq->lock);
1927 list_add_tail_rcu(&vb->free_list, &vbq->free);
1928 spin_unlock(&vbq->lock);
1929 put_cpu_var(vmap_block_queue);
1934 static void free_vmap_block(struct vmap_block *vb)
1936 struct vmap_block *tmp;
1938 tmp = xa_erase(&vmap_blocks, addr_to_vb_idx(vb->va->va_start));
1941 free_vmap_area_noflush(vb->va);
1942 kfree_rcu(vb, rcu_head);
1945 static void purge_fragmented_blocks(int cpu)
1948 struct vmap_block *vb;
1949 struct vmap_block *n_vb;
1950 struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu);
1953 list_for_each_entry_rcu(vb, &vbq->free, free_list) {
1955 if (!(vb->free + vb->dirty == VMAP_BBMAP_BITS && vb->dirty != VMAP_BBMAP_BITS))
1958 spin_lock(&vb->lock);
1959 if (vb->free + vb->dirty == VMAP_BBMAP_BITS && vb->dirty != VMAP_BBMAP_BITS) {
1960 vb->free = 0; /* prevent further allocs after releasing lock */
1961 vb->dirty = VMAP_BBMAP_BITS; /* prevent purging it again */
1963 vb->dirty_max = VMAP_BBMAP_BITS;
1964 spin_lock(&vbq->lock);
1965 list_del_rcu(&vb->free_list);
1966 spin_unlock(&vbq->lock);
1967 spin_unlock(&vb->lock);
1968 list_add_tail(&vb->purge, &purge);
1970 spin_unlock(&vb->lock);
1974 list_for_each_entry_safe(vb, n_vb, &purge, purge) {
1975 list_del(&vb->purge);
1976 free_vmap_block(vb);
1980 static void purge_fragmented_blocks_allcpus(void)
1984 for_each_possible_cpu(cpu)
1985 purge_fragmented_blocks(cpu);
1988 static void *vb_alloc(unsigned long size, gfp_t gfp_mask)
1990 struct vmap_block_queue *vbq;
1991 struct vmap_block *vb;
1995 BUG_ON(offset_in_page(size));
1996 BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
1997 if (WARN_ON(size == 0)) {
1999 * Allocating 0 bytes isn't what caller wants since
2000 * get_order(0) returns funny result. Just warn and terminate
2005 order = get_order(size);
2008 vbq = &get_cpu_var(vmap_block_queue);
2009 list_for_each_entry_rcu(vb, &vbq->free, free_list) {
2010 unsigned long pages_off;
2012 spin_lock(&vb->lock);
2013 if (vb->free < (1UL << order)) {
2014 spin_unlock(&vb->lock);
2018 pages_off = VMAP_BBMAP_BITS - vb->free;
2019 vaddr = vmap_block_vaddr(vb->va->va_start, pages_off);
2020 vb->free -= 1UL << order;
2021 if (vb->free == 0) {
2022 spin_lock(&vbq->lock);
2023 list_del_rcu(&vb->free_list);
2024 spin_unlock(&vbq->lock);
2027 spin_unlock(&vb->lock);
2031 put_cpu_var(vmap_block_queue);
2034 /* Allocate new block if nothing was found */
2036 vaddr = new_vmap_block(order, gfp_mask);
2041 static void vb_free(unsigned long addr, unsigned long size)
2043 unsigned long offset;
2045 struct vmap_block *vb;
2047 BUG_ON(offset_in_page(size));
2048 BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
2050 flush_cache_vunmap(addr, addr + size);
2052 order = get_order(size);
2053 offset = (addr & (VMAP_BLOCK_SIZE - 1)) >> PAGE_SHIFT;
2054 vb = xa_load(&vmap_blocks, addr_to_vb_idx(addr));
2056 vunmap_range_noflush(addr, addr + size);
2058 if (debug_pagealloc_enabled_static())
2059 flush_tlb_kernel_range(addr, addr + size);
2061 spin_lock(&vb->lock);
2063 /* Expand dirty range */
2064 vb->dirty_min = min(vb->dirty_min, offset);
2065 vb->dirty_max = max(vb->dirty_max, offset + (1UL << order));
2067 vb->dirty += 1UL << order;
2068 if (vb->dirty == VMAP_BBMAP_BITS) {
2070 spin_unlock(&vb->lock);
2071 free_vmap_block(vb);
2073 spin_unlock(&vb->lock);
2076 static void _vm_unmap_aliases(unsigned long start, unsigned long end, int flush)
2080 if (unlikely(!vmap_initialized))
2085 for_each_possible_cpu(cpu) {
2086 struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu);
2087 struct vmap_block *vb;
2090 list_for_each_entry_rcu(vb, &vbq->free, free_list) {
2091 spin_lock(&vb->lock);
2092 if (vb->dirty && vb->dirty != VMAP_BBMAP_BITS) {
2093 unsigned long va_start = vb->va->va_start;
2096 s = va_start + (vb->dirty_min << PAGE_SHIFT);
2097 e = va_start + (vb->dirty_max << PAGE_SHIFT);
2099 start = min(s, start);
2104 spin_unlock(&vb->lock);
2109 mutex_lock(&vmap_purge_lock);
2110 purge_fragmented_blocks_allcpus();
2111 if (!__purge_vmap_area_lazy(start, end) && flush)
2112 flush_tlb_kernel_range(start, end);
2113 mutex_unlock(&vmap_purge_lock);
2117 * vm_unmap_aliases - unmap outstanding lazy aliases in the vmap layer
2119 * The vmap/vmalloc layer lazily flushes kernel virtual mappings primarily
2120 * to amortize TLB flushing overheads. What this means is that any page you
2121 * have now, may, in a former life, have been mapped into kernel virtual
2122 * address by the vmap layer and so there might be some CPUs with TLB entries
2123 * still referencing that page (additional to the regular 1:1 kernel mapping).
2125 * vm_unmap_aliases flushes all such lazy mappings. After it returns, we can
2126 * be sure that none of the pages we have control over will have any aliases
2127 * from the vmap layer.
2129 void vm_unmap_aliases(void)
2131 unsigned long start = ULONG_MAX, end = 0;
2134 _vm_unmap_aliases(start, end, flush);
2136 EXPORT_SYMBOL_GPL(vm_unmap_aliases);
2139 * vm_unmap_ram - unmap linear kernel address space set up by vm_map_ram
2140 * @mem: the pointer returned by vm_map_ram
2141 * @count: the count passed to that vm_map_ram call (cannot unmap partial)
2143 void vm_unmap_ram(const void *mem, unsigned int count)
2145 unsigned long size = (unsigned long)count << PAGE_SHIFT;
2146 unsigned long addr = (unsigned long)mem;
2147 struct vmap_area *va;
2151 BUG_ON(addr < VMALLOC_START);
2152 BUG_ON(addr > VMALLOC_END);
2153 BUG_ON(!PAGE_ALIGNED(addr));
2155 kasan_poison_vmalloc(mem, size);
2157 if (likely(count <= VMAP_MAX_ALLOC)) {
2158 debug_check_no_locks_freed(mem, size);
2159 vb_free(addr, size);
2163 va = find_vmap_area(addr);
2165 debug_check_no_locks_freed((void *)va->va_start,
2166 (va->va_end - va->va_start));
2167 free_unmap_vmap_area(va);
2169 EXPORT_SYMBOL(vm_unmap_ram);
2172 * vm_map_ram - map pages linearly into kernel virtual address (vmalloc space)
2173 * @pages: an array of pointers to the pages to be mapped
2174 * @count: number of pages
2175 * @node: prefer to allocate data structures on this node
2177 * If you use this function for less than VMAP_MAX_ALLOC pages, it could be
2178 * faster than vmap so it's good. But if you mix long-life and short-life
2179 * objects with vm_map_ram(), it could consume lots of address space through
2180 * fragmentation (especially on a 32bit machine). You could see failures in
2181 * the end. Please use this function for short-lived objects.
2183 * Returns: a pointer to the address that has been mapped, or %NULL on failure
2185 void *vm_map_ram(struct page **pages, unsigned int count, int node)
2187 unsigned long size = (unsigned long)count << PAGE_SHIFT;
2191 if (likely(count <= VMAP_MAX_ALLOC)) {
2192 mem = vb_alloc(size, GFP_KERNEL);
2195 addr = (unsigned long)mem;
2197 struct vmap_area *va;
2198 va = alloc_vmap_area(size, PAGE_SIZE,
2199 VMALLOC_START, VMALLOC_END, node, GFP_KERNEL);
2203 addr = va->va_start;
2207 kasan_unpoison_vmalloc(mem, size);
2209 if (vmap_pages_range(addr, addr + size, PAGE_KERNEL,
2210 pages, PAGE_SHIFT) < 0) {
2211 vm_unmap_ram(mem, count);
2217 EXPORT_SYMBOL(vm_map_ram);
2219 static struct vm_struct *vmlist __initdata;
2221 static inline unsigned int vm_area_page_order(struct vm_struct *vm)
2223 #ifdef CONFIG_HAVE_ARCH_HUGE_VMALLOC
2224 return vm->page_order;
2230 static inline void set_vm_area_page_order(struct vm_struct *vm, unsigned int order)
2232 #ifdef CONFIG_HAVE_ARCH_HUGE_VMALLOC
2233 vm->page_order = order;
2240 * vm_area_add_early - add vmap area early during boot
2241 * @vm: vm_struct to add
2243 * This function is used to add fixed kernel vm area to vmlist before
2244 * vmalloc_init() is called. @vm->addr, @vm->size, and @vm->flags
2245 * should contain proper values and the other fields should be zero.
2247 * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING.
2249 void __init vm_area_add_early(struct vm_struct *vm)
2251 struct vm_struct *tmp, **p;
2253 BUG_ON(vmap_initialized);
2254 for (p = &vmlist; (tmp = *p) != NULL; p = &tmp->next) {
2255 if (tmp->addr >= vm->addr) {
2256 BUG_ON(tmp->addr < vm->addr + vm->size);
2259 BUG_ON(tmp->addr + tmp->size > vm->addr);
2266 * vm_area_register_early - register vmap area early during boot
2267 * @vm: vm_struct to register
2268 * @align: requested alignment
2270 * This function is used to register kernel vm area before
2271 * vmalloc_init() is called. @vm->size and @vm->flags should contain
2272 * proper values on entry and other fields should be zero. On return,
2273 * vm->addr contains the allocated address.
2275 * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING.
2277 void __init vm_area_register_early(struct vm_struct *vm, size_t align)
2279 static size_t vm_init_off __initdata;
2282 addr = ALIGN(VMALLOC_START + vm_init_off, align);
2283 vm_init_off = PFN_ALIGN(addr + vm->size) - VMALLOC_START;
2285 vm->addr = (void *)addr;
2287 vm_area_add_early(vm);
2290 static void vmap_init_free_space(void)
2292 unsigned long vmap_start = 1;
2293 const unsigned long vmap_end = ULONG_MAX;
2294 struct vmap_area *busy, *free;
2298 * -|-----|.....|-----|-----|-----|.....|-
2300 * |<--------------------------------->|
2302 list_for_each_entry(busy, &vmap_area_list, list) {
2303 if (busy->va_start - vmap_start > 0) {
2304 free = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
2305 if (!WARN_ON_ONCE(!free)) {
2306 free->va_start = vmap_start;
2307 free->va_end = busy->va_start;
2309 insert_vmap_area_augment(free, NULL,
2310 &free_vmap_area_root,
2311 &free_vmap_area_list);
2315 vmap_start = busy->va_end;
2318 if (vmap_end - vmap_start > 0) {
2319 free = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
2320 if (!WARN_ON_ONCE(!free)) {
2321 free->va_start = vmap_start;
2322 free->va_end = vmap_end;
2324 insert_vmap_area_augment(free, NULL,
2325 &free_vmap_area_root,
2326 &free_vmap_area_list);
2331 void __init vmalloc_init(void)
2333 struct vmap_area *va;
2334 struct vm_struct *tmp;
2338 * Create the cache for vmap_area objects.
2340 vmap_area_cachep = KMEM_CACHE(vmap_area, SLAB_PANIC);
2342 for_each_possible_cpu(i) {
2343 struct vmap_block_queue *vbq;
2344 struct vfree_deferred *p;
2346 vbq = &per_cpu(vmap_block_queue, i);
2347 spin_lock_init(&vbq->lock);
2348 INIT_LIST_HEAD(&vbq->free);
2349 p = &per_cpu(vfree_deferred, i);
2350 init_llist_head(&p->list);
2351 INIT_WORK(&p->wq, free_work);
2354 /* Import existing vmlist entries. */
2355 for (tmp = vmlist; tmp; tmp = tmp->next) {
2356 va = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
2357 if (WARN_ON_ONCE(!va))
2360 va->va_start = (unsigned long)tmp->addr;
2361 va->va_end = va->va_start + tmp->size;
2363 insert_vmap_area(va, &vmap_area_root, &vmap_area_list);
2367 * Now we can initialize a free vmap space.
2369 vmap_init_free_space();
2370 vmap_initialized = true;
2373 static inline void setup_vmalloc_vm_locked(struct vm_struct *vm,
2374 struct vmap_area *va, unsigned long flags, const void *caller)
2377 vm->addr = (void *)va->va_start;
2378 vm->size = va->va_end - va->va_start;
2379 vm->caller = caller;
2383 static void setup_vmalloc_vm(struct vm_struct *vm, struct vmap_area *va,
2384 unsigned long flags, const void *caller)
2386 spin_lock(&vmap_area_lock);
2387 setup_vmalloc_vm_locked(vm, va, flags, caller);
2388 spin_unlock(&vmap_area_lock);
2391 static void clear_vm_uninitialized_flag(struct vm_struct *vm)
2394 * Before removing VM_UNINITIALIZED,
2395 * we should make sure that vm has proper values.
2396 * Pair with smp_rmb() in show_numa_info().
2399 vm->flags &= ~VM_UNINITIALIZED;
2402 static struct vm_struct *__get_vm_area_node(unsigned long size,
2403 unsigned long align, unsigned long shift, unsigned long flags,
2404 unsigned long start, unsigned long end, int node,
2405 gfp_t gfp_mask, const void *caller)
2407 struct vmap_area *va;
2408 struct vm_struct *area;
2409 unsigned long requested_size = size;
2411 BUG_ON(in_interrupt());
2412 size = ALIGN(size, 1ul << shift);
2413 if (unlikely(!size))
2416 if (flags & VM_IOREMAP)
2417 align = 1ul << clamp_t(int, get_count_order_long(size),
2418 PAGE_SHIFT, IOREMAP_MAX_ORDER);
2420 area = kzalloc_node(sizeof(*area), gfp_mask & GFP_RECLAIM_MASK, node);
2421 if (unlikely(!area))
2424 if (!(flags & VM_NO_GUARD))
2427 va = alloc_vmap_area(size, align, start, end, node, gfp_mask);
2433 kasan_unpoison_vmalloc((void *)va->va_start, requested_size);
2435 setup_vmalloc_vm(area, va, flags, caller);
2440 struct vm_struct *__get_vm_area_caller(unsigned long size, unsigned long flags,
2441 unsigned long start, unsigned long end,
2444 return __get_vm_area_node(size, 1, PAGE_SHIFT, flags, start, end,
2445 NUMA_NO_NODE, GFP_KERNEL, caller);
2449 * get_vm_area - reserve a contiguous kernel virtual area
2450 * @size: size of the area
2451 * @flags: %VM_IOREMAP for I/O mappings or VM_ALLOC
2453 * Search an area of @size in the kernel virtual mapping area,
2454 * and reserved it for out purposes. Returns the area descriptor
2455 * on success or %NULL on failure.
2457 * Return: the area descriptor on success or %NULL on failure.
2459 struct vm_struct *get_vm_area(unsigned long size, unsigned long flags)
2461 return __get_vm_area_node(size, 1, PAGE_SHIFT, flags,
2462 VMALLOC_START, VMALLOC_END,
2463 NUMA_NO_NODE, GFP_KERNEL,
2464 __builtin_return_address(0));
2467 struct vm_struct *get_vm_area_caller(unsigned long size, unsigned long flags,
2470 return __get_vm_area_node(size, 1, PAGE_SHIFT, flags,
2471 VMALLOC_START, VMALLOC_END,
2472 NUMA_NO_NODE, GFP_KERNEL, caller);
2476 * find_vm_area - find a continuous kernel virtual area
2477 * @addr: base address
2479 * Search for the kernel VM area starting at @addr, and return it.
2480 * It is up to the caller to do all required locking to keep the returned
2483 * Return: the area descriptor on success or %NULL on failure.
2485 struct vm_struct *find_vm_area(const void *addr)
2487 struct vmap_area *va;
2489 va = find_vmap_area((unsigned long)addr);
2497 * remove_vm_area - find and remove a continuous kernel virtual area
2498 * @addr: base address
2500 * Search for the kernel VM area starting at @addr, and remove it.
2501 * This function returns the found VM area, but using it is NOT safe
2502 * on SMP machines, except for its size or flags.
2504 * Return: the area descriptor on success or %NULL on failure.
2506 struct vm_struct *remove_vm_area(const void *addr)
2508 struct vmap_area *va;
2512 spin_lock(&vmap_area_lock);
2513 va = __find_vmap_area((unsigned long)addr);
2515 struct vm_struct *vm = va->vm;
2518 spin_unlock(&vmap_area_lock);
2520 kasan_free_shadow(vm);
2521 free_unmap_vmap_area(va);
2526 spin_unlock(&vmap_area_lock);
2530 static inline void set_area_direct_map(const struct vm_struct *area,
2531 int (*set_direct_map)(struct page *page))
2535 /* HUGE_VMALLOC passes small pages to set_direct_map */
2536 for (i = 0; i < area->nr_pages; i++)
2537 if (page_address(area->pages[i]))
2538 set_direct_map(area->pages[i]);
2541 /* Handle removing and resetting vm mappings related to the vm_struct. */
2542 static void vm_remove_mappings(struct vm_struct *area, int deallocate_pages)
2544 unsigned long start = ULONG_MAX, end = 0;
2545 unsigned int page_order = vm_area_page_order(area);
2546 int flush_reset = area->flags & VM_FLUSH_RESET_PERMS;
2550 remove_vm_area(area->addr);
2552 /* If this is not VM_FLUSH_RESET_PERMS memory, no need for the below. */
2557 * If not deallocating pages, just do the flush of the VM area and
2560 if (!deallocate_pages) {
2566 * If execution gets here, flush the vm mapping and reset the direct
2567 * map. Find the start and end range of the direct mappings to make sure
2568 * the vm_unmap_aliases() flush includes the direct map.
2570 for (i = 0; i < area->nr_pages; i += 1U << page_order) {
2571 unsigned long addr = (unsigned long)page_address(area->pages[i]);
2573 unsigned long page_size;
2575 page_size = PAGE_SIZE << page_order;
2576 start = min(addr, start);
2577 end = max(addr + page_size, end);
2583 * Set direct map to something invalid so that it won't be cached if
2584 * there are any accesses after the TLB flush, then flush the TLB and
2585 * reset the direct map permissions to the default.
2587 set_area_direct_map(area, set_direct_map_invalid_noflush);
2588 _vm_unmap_aliases(start, end, flush_dmap);
2589 set_area_direct_map(area, set_direct_map_default_noflush);
2592 static void __vunmap(const void *addr, int deallocate_pages)
2594 struct vm_struct *area;
2599 if (WARN(!PAGE_ALIGNED(addr), "Trying to vfree() bad address (%p)\n",
2603 area = find_vm_area(addr);
2604 if (unlikely(!area)) {
2605 WARN(1, KERN_ERR "Trying to vfree() nonexistent vm area (%p)\n",
2610 debug_check_no_locks_freed(area->addr, get_vm_area_size(area));
2611 debug_check_no_obj_freed(area->addr, get_vm_area_size(area));
2613 kasan_poison_vmalloc(area->addr, get_vm_area_size(area));
2615 vm_remove_mappings(area, deallocate_pages);
2617 if (deallocate_pages) {
2618 unsigned int page_order = vm_area_page_order(area);
2621 for (i = 0; i < area->nr_pages; i += 1U << page_order) {
2622 struct page *page = area->pages[i];
2625 __free_pages(page, page_order);
2628 atomic_long_sub(area->nr_pages, &nr_vmalloc_pages);
2630 kvfree(area->pages);
2636 static inline void __vfree_deferred(const void *addr)
2639 * Use raw_cpu_ptr() because this can be called from preemptible
2640 * context. Preemption is absolutely fine here, because the llist_add()
2641 * implementation is lockless, so it works even if we are adding to
2642 * another cpu's list. schedule_work() should be fine with this too.
2644 struct vfree_deferred *p = raw_cpu_ptr(&vfree_deferred);
2646 if (llist_add((struct llist_node *)addr, &p->list))
2647 schedule_work(&p->wq);
2651 * vfree_atomic - release memory allocated by vmalloc()
2652 * @addr: memory base address
2654 * This one is just like vfree() but can be called in any atomic context
2657 void vfree_atomic(const void *addr)
2661 kmemleak_free(addr);
2665 __vfree_deferred(addr);
2668 static void __vfree(const void *addr)
2670 if (unlikely(in_interrupt()))
2671 __vfree_deferred(addr);
2677 * vfree - Release memory allocated by vmalloc()
2678 * @addr: Memory base address
2680 * Free the virtually continuous memory area starting at @addr, as obtained
2681 * from one of the vmalloc() family of APIs. This will usually also free the
2682 * physical memory underlying the virtual allocation, but that memory is
2683 * reference counted, so it will not be freed until the last user goes away.
2685 * If @addr is NULL, no operation is performed.
2688 * May sleep if called *not* from interrupt context.
2689 * Must not be called in NMI context (strictly speaking, it could be
2690 * if we have CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG, but making the calling
2691 * conventions for vfree() arch-dependent would be a really bad idea).
2693 void vfree(const void *addr)
2697 kmemleak_free(addr);
2699 might_sleep_if(!in_interrupt());
2706 EXPORT_SYMBOL(vfree);
2709 * vunmap - release virtual mapping obtained by vmap()
2710 * @addr: memory base address
2712 * Free the virtually contiguous memory area starting at @addr,
2713 * which was created from the page array passed to vmap().
2715 * Must not be called in interrupt context.
2717 void vunmap(const void *addr)
2719 BUG_ON(in_interrupt());
2724 EXPORT_SYMBOL(vunmap);
2727 * vmap - map an array of pages into virtually contiguous space
2728 * @pages: array of page pointers
2729 * @count: number of pages to map
2730 * @flags: vm_area->flags
2731 * @prot: page protection for the mapping
2733 * Maps @count pages from @pages into contiguous kernel virtual space.
2734 * If @flags contains %VM_MAP_PUT_PAGES the ownership of the pages array itself
2735 * (which must be kmalloc or vmalloc memory) and one reference per pages in it
2736 * are transferred from the caller to vmap(), and will be freed / dropped when
2737 * vfree() is called on the return value.
2739 * Return: the address of the area or %NULL on failure
2741 void *vmap(struct page **pages, unsigned int count,
2742 unsigned long flags, pgprot_t prot)
2744 struct vm_struct *area;
2746 unsigned long size; /* In bytes */
2751 * Your top guard is someone else's bottom guard. Not having a top
2752 * guard compromises someone else's mappings too.
2754 if (WARN_ON_ONCE(flags & VM_NO_GUARD))
2755 flags &= ~VM_NO_GUARD;
2757 if (count > totalram_pages())
2760 size = (unsigned long)count << PAGE_SHIFT;
2761 area = get_vm_area_caller(size, flags, __builtin_return_address(0));
2765 addr = (unsigned long)area->addr;
2766 if (vmap_pages_range(addr, addr + size, pgprot_nx(prot),
2767 pages, PAGE_SHIFT) < 0) {
2772 if (flags & VM_MAP_PUT_PAGES) {
2773 area->pages = pages;
2774 area->nr_pages = count;
2778 EXPORT_SYMBOL(vmap);
2780 #ifdef CONFIG_VMAP_PFN
2781 struct vmap_pfn_data {
2782 unsigned long *pfns;
2787 static int vmap_pfn_apply(pte_t *pte, unsigned long addr, void *private)
2789 struct vmap_pfn_data *data = private;
2791 if (WARN_ON_ONCE(pfn_valid(data->pfns[data->idx])))
2793 *pte = pte_mkspecial(pfn_pte(data->pfns[data->idx++], data->prot));
2798 * vmap_pfn - map an array of PFNs into virtually contiguous space
2799 * @pfns: array of PFNs
2800 * @count: number of pages to map
2801 * @prot: page protection for the mapping
2803 * Maps @count PFNs from @pfns into contiguous kernel virtual space and returns
2804 * the start address of the mapping.
2806 void *vmap_pfn(unsigned long *pfns, unsigned int count, pgprot_t prot)
2808 struct vmap_pfn_data data = { .pfns = pfns, .prot = pgprot_nx(prot) };
2809 struct vm_struct *area;
2811 area = get_vm_area_caller(count * PAGE_SIZE, VM_IOREMAP,
2812 __builtin_return_address(0));
2815 if (apply_to_page_range(&init_mm, (unsigned long)area->addr,
2816 count * PAGE_SIZE, vmap_pfn_apply, &data)) {
2822 EXPORT_SYMBOL_GPL(vmap_pfn);
2823 #endif /* CONFIG_VMAP_PFN */
2825 static inline unsigned int
2826 vm_area_alloc_pages(gfp_t gfp, int nid,
2827 unsigned int order, unsigned int nr_pages, struct page **pages)
2829 unsigned int nr_allocated = 0;
2834 * For order-0 pages we make use of bulk allocator, if
2835 * the page array is partly or not at all populated due
2836 * to fails, fallback to a single page allocator that is
2839 if (!order && nid != NUMA_NO_NODE) {
2840 while (nr_allocated < nr_pages) {
2841 unsigned int nr, nr_pages_request;
2844 * A maximum allowed request is hard-coded and is 100
2845 * pages per call. That is done in order to prevent a
2846 * long preemption off scenario in the bulk-allocator
2847 * so the range is [1:100].
2849 nr_pages_request = min(100U, nr_pages - nr_allocated);
2851 nr = alloc_pages_bulk_array_node(gfp, nid,
2852 nr_pages_request, pages + nr_allocated);
2858 * If zero or pages were obtained partly,
2859 * fallback to a single page allocator.
2861 if (nr != nr_pages_request)
2866 * Compound pages required for remap_vmalloc_page if
2871 /* High-order pages or fallback path if "bulk" fails. */
2873 while (nr_allocated < nr_pages) {
2874 if (fatal_signal_pending(current))
2877 if (nid == NUMA_NO_NODE)
2878 page = alloc_pages(gfp, order);
2880 page = alloc_pages_node(nid, gfp, order);
2881 if (unlikely(!page))
2885 * Careful, we allocate and map page-order pages, but
2886 * tracking is done per PAGE_SIZE page so as to keep the
2887 * vm_struct APIs independent of the physical/mapped size.
2889 for (i = 0; i < (1U << order); i++)
2890 pages[nr_allocated + i] = page + i;
2893 nr_allocated += 1U << order;
2896 return nr_allocated;
2899 static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask,
2900 pgprot_t prot, unsigned int page_shift,
2903 const gfp_t nested_gfp = (gfp_mask & GFP_RECLAIM_MASK) | __GFP_ZERO;
2904 const gfp_t orig_gfp_mask = gfp_mask;
2905 unsigned long addr = (unsigned long)area->addr;
2906 unsigned long size = get_vm_area_size(area);
2907 unsigned long array_size;
2908 unsigned int nr_small_pages = size >> PAGE_SHIFT;
2909 unsigned int page_order;
2911 array_size = (unsigned long)nr_small_pages * sizeof(struct page *);
2912 gfp_mask |= __GFP_NOWARN;
2913 if (!(gfp_mask & (GFP_DMA | GFP_DMA32)))
2914 gfp_mask |= __GFP_HIGHMEM;
2916 /* Please note that the recursion is strictly bounded. */
2917 if (array_size > PAGE_SIZE) {
2918 area->pages = __vmalloc_node(array_size, 1, nested_gfp, node,
2921 area->pages = kmalloc_node(array_size, nested_gfp, node);
2925 warn_alloc(orig_gfp_mask, NULL,
2926 "vmalloc error: size %lu, failed to allocated page array size %lu",
2927 nr_small_pages * PAGE_SIZE, array_size);
2932 set_vm_area_page_order(area, page_shift - PAGE_SHIFT);
2933 page_order = vm_area_page_order(area);
2935 area->nr_pages = vm_area_alloc_pages(gfp_mask, node,
2936 page_order, nr_small_pages, area->pages);
2938 atomic_long_add(area->nr_pages, &nr_vmalloc_pages);
2941 * If not enough pages were obtained to accomplish an
2942 * allocation request, free them via __vfree() if any.
2944 if (area->nr_pages != nr_small_pages) {
2945 warn_alloc(orig_gfp_mask, NULL,
2946 "vmalloc error: size %lu, page order %u, failed to allocate pages",
2947 area->nr_pages * PAGE_SIZE, page_order);
2951 if (vmap_pages_range(addr, addr + size, prot, area->pages,
2953 warn_alloc(orig_gfp_mask, NULL,
2954 "vmalloc error: size %lu, failed to map pages",
2955 area->nr_pages * PAGE_SIZE);
2962 __vfree(area->addr);
2967 * __vmalloc_node_range - allocate virtually contiguous memory
2968 * @size: allocation size
2969 * @align: desired alignment
2970 * @start: vm area range start
2971 * @end: vm area range end
2972 * @gfp_mask: flags for the page level allocator
2973 * @prot: protection mask for the allocated pages
2974 * @vm_flags: additional vm area flags (e.g. %VM_NO_GUARD)
2975 * @node: node to use for allocation or NUMA_NO_NODE
2976 * @caller: caller's return address
2978 * Allocate enough pages to cover @size from the page level
2979 * allocator with @gfp_mask flags. Map them into contiguous
2980 * kernel virtual space, using a pagetable protection of @prot.
2982 * Return: the address of the area or %NULL on failure
2984 void *__vmalloc_node_range(unsigned long size, unsigned long align,
2985 unsigned long start, unsigned long end, gfp_t gfp_mask,
2986 pgprot_t prot, unsigned long vm_flags, int node,
2989 struct vm_struct *area;
2991 unsigned long real_size = size;
2992 unsigned long real_align = align;
2993 unsigned int shift = PAGE_SHIFT;
2995 if (WARN_ON_ONCE(!size))
2998 if ((size >> PAGE_SHIFT) > totalram_pages()) {
2999 warn_alloc(gfp_mask, NULL,
3000 "vmalloc error: size %lu, exceeds total pages",
3005 if (vmap_allow_huge && !(vm_flags & VM_NO_HUGE_VMAP)) {
3006 unsigned long size_per_node;
3009 * Try huge pages. Only try for PAGE_KERNEL allocations,
3010 * others like modules don't yet expect huge pages in
3011 * their allocations due to apply_to_page_range not
3015 size_per_node = size;
3016 if (node == NUMA_NO_NODE)
3017 size_per_node /= num_online_nodes();
3018 if (arch_vmap_pmd_supported(prot) && size_per_node >= PMD_SIZE)
3021 shift = arch_vmap_pte_supported_shift(size_per_node);
3023 align = max(real_align, 1UL << shift);
3024 size = ALIGN(real_size, 1UL << shift);
3028 area = __get_vm_area_node(real_size, align, shift, VM_ALLOC |
3029 VM_UNINITIALIZED | vm_flags, start, end, node,
3032 warn_alloc(gfp_mask, NULL,
3033 "vmalloc error: size %lu, vm_struct allocation failed",
3038 addr = __vmalloc_area_node(area, gfp_mask, prot, shift, node);
3043 * In this function, newly allocated vm_struct has VM_UNINITIALIZED
3044 * flag. It means that vm_struct is not fully initialized.
3045 * Now, it is fully initialized, so remove this flag here.
3047 clear_vm_uninitialized_flag(area);
3049 size = PAGE_ALIGN(size);
3050 kmemleak_vmalloc(area, size, gfp_mask);
3055 if (shift > PAGE_SHIFT) {
3066 * __vmalloc_node - allocate virtually contiguous memory
3067 * @size: allocation size
3068 * @align: desired alignment
3069 * @gfp_mask: flags for the page level allocator
3070 * @node: node to use for allocation or NUMA_NO_NODE
3071 * @caller: caller's return address
3073 * Allocate enough pages to cover @size from the page level allocator with
3074 * @gfp_mask flags. Map them into contiguous kernel virtual space.
3076 * Reclaim modifiers in @gfp_mask - __GFP_NORETRY, __GFP_RETRY_MAYFAIL
3077 * and __GFP_NOFAIL are not supported
3079 * Any use of gfp flags outside of GFP_KERNEL should be consulted
3082 * Return: pointer to the allocated memory or %NULL on error
3084 void *__vmalloc_node(unsigned long size, unsigned long align,
3085 gfp_t gfp_mask, int node, const void *caller)
3087 return __vmalloc_node_range(size, align, VMALLOC_START, VMALLOC_END,
3088 gfp_mask, PAGE_KERNEL, 0, node, caller);
3091 * This is only for performance analysis of vmalloc and stress purpose.
3092 * It is required by vmalloc test module, therefore do not use it other
3095 #ifdef CONFIG_TEST_VMALLOC_MODULE
3096 EXPORT_SYMBOL_GPL(__vmalloc_node);
3099 void *__vmalloc(unsigned long size, gfp_t gfp_mask)
3101 return __vmalloc_node(size, 1, gfp_mask, NUMA_NO_NODE,
3102 __builtin_return_address(0));
3104 EXPORT_SYMBOL(__vmalloc);
3107 * vmalloc - allocate virtually contiguous memory
3108 * @size: allocation size
3110 * Allocate enough pages to cover @size from the page level
3111 * allocator and map them into contiguous kernel virtual space.
3113 * For tight control over page level allocator and protection flags
3114 * use __vmalloc() instead.
3116 * Return: pointer to the allocated memory or %NULL on error
3118 void *vmalloc(unsigned long size)
3120 return __vmalloc_node(size, 1, GFP_KERNEL, NUMA_NO_NODE,
3121 __builtin_return_address(0));
3123 EXPORT_SYMBOL(vmalloc);
3126 * vmalloc_no_huge - allocate virtually contiguous memory using small pages
3127 * @size: allocation size
3129 * Allocate enough non-huge pages to cover @size from the page level
3130 * allocator and map them into contiguous kernel virtual space.
3132 * Return: pointer to the allocated memory or %NULL on error
3134 void *vmalloc_no_huge(unsigned long size)
3136 return __vmalloc_node_range(size, 1, VMALLOC_START, VMALLOC_END,
3137 GFP_KERNEL, PAGE_KERNEL, VM_NO_HUGE_VMAP,
3138 NUMA_NO_NODE, __builtin_return_address(0));
3140 EXPORT_SYMBOL(vmalloc_no_huge);
3143 * vzalloc - allocate virtually contiguous memory with zero fill
3144 * @size: allocation size
3146 * Allocate enough pages to cover @size from the page level
3147 * allocator and map them into contiguous kernel virtual space.
3148 * The memory allocated is set to zero.
3150 * For tight control over page level allocator and protection flags
3151 * use __vmalloc() instead.
3153 * Return: pointer to the allocated memory or %NULL on error
3155 void *vzalloc(unsigned long size)
3157 return __vmalloc_node(size, 1, GFP_KERNEL | __GFP_ZERO, NUMA_NO_NODE,
3158 __builtin_return_address(0));
3160 EXPORT_SYMBOL(vzalloc);
3163 * vmalloc_user - allocate zeroed virtually contiguous memory for userspace
3164 * @size: allocation size
3166 * The resulting memory area is zeroed so it can be mapped to userspace
3167 * without leaking data.
3169 * Return: pointer to the allocated memory or %NULL on error
3171 void *vmalloc_user(unsigned long size)
3173 return __vmalloc_node_range(size, SHMLBA, VMALLOC_START, VMALLOC_END,
3174 GFP_KERNEL | __GFP_ZERO, PAGE_KERNEL,
3175 VM_USERMAP, NUMA_NO_NODE,
3176 __builtin_return_address(0));
3178 EXPORT_SYMBOL(vmalloc_user);
3181 * vmalloc_node - allocate memory on a specific node
3182 * @size: allocation size
3185 * Allocate enough pages to cover @size from the page level
3186 * allocator and map them into contiguous kernel virtual space.
3188 * For tight control over page level allocator and protection flags
3189 * use __vmalloc() instead.
3191 * Return: pointer to the allocated memory or %NULL on error
3193 void *vmalloc_node(unsigned long size, int node)
3195 return __vmalloc_node(size, 1, GFP_KERNEL, node,
3196 __builtin_return_address(0));
3198 EXPORT_SYMBOL(vmalloc_node);
3201 * vzalloc_node - allocate memory on a specific node with zero fill
3202 * @size: allocation size
3205 * Allocate enough pages to cover @size from the page level
3206 * allocator and map them into contiguous kernel virtual space.
3207 * The memory allocated is set to zero.
3209 * Return: pointer to the allocated memory or %NULL on error
3211 void *vzalloc_node(unsigned long size, int node)
3213 return __vmalloc_node(size, 1, GFP_KERNEL | __GFP_ZERO, node,
3214 __builtin_return_address(0));
3216 EXPORT_SYMBOL(vzalloc_node);
3218 #if defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA32)
3219 #define GFP_VMALLOC32 (GFP_DMA32 | GFP_KERNEL)
3220 #elif defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA)
3221 #define GFP_VMALLOC32 (GFP_DMA | GFP_KERNEL)
3224 * 64b systems should always have either DMA or DMA32 zones. For others
3225 * GFP_DMA32 should do the right thing and use the normal zone.
3227 #define GFP_VMALLOC32 (GFP_DMA32 | GFP_KERNEL)
3231 * vmalloc_32 - allocate virtually contiguous memory (32bit addressable)
3232 * @size: allocation size
3234 * Allocate enough 32bit PA addressable pages to cover @size from the
3235 * page level allocator and map them into contiguous kernel virtual space.
3237 * Return: pointer to the allocated memory or %NULL on error
3239 void *vmalloc_32(unsigned long size)
3241 return __vmalloc_node(size, 1, GFP_VMALLOC32, NUMA_NO_NODE,
3242 __builtin_return_address(0));
3244 EXPORT_SYMBOL(vmalloc_32);
3247 * vmalloc_32_user - allocate zeroed virtually contiguous 32bit memory
3248 * @size: allocation size
3250 * The resulting memory area is 32bit addressable and zeroed so it can be
3251 * mapped to userspace without leaking data.
3253 * Return: pointer to the allocated memory or %NULL on error
3255 void *vmalloc_32_user(unsigned long size)
3257 return __vmalloc_node_range(size, SHMLBA, VMALLOC_START, VMALLOC_END,
3258 GFP_VMALLOC32 | __GFP_ZERO, PAGE_KERNEL,
3259 VM_USERMAP, NUMA_NO_NODE,
3260 __builtin_return_address(0));
3262 EXPORT_SYMBOL(vmalloc_32_user);
3265 * small helper routine , copy contents to buf from addr.
3266 * If the page is not present, fill zero.
3269 static int aligned_vread(char *buf, char *addr, unsigned long count)
3275 unsigned long offset, length;
3277 offset = offset_in_page(addr);
3278 length = PAGE_SIZE - offset;
3281 p = vmalloc_to_page(addr);
3283 * To do safe access to this _mapped_ area, we need
3284 * lock. But adding lock here means that we need to add
3285 * overhead of vmalloc()/vfree() calls for this _debug_
3286 * interface, rarely used. Instead of that, we'll use
3287 * kmap() and get small overhead in this access function.
3290 /* We can expect USER0 is not used -- see vread() */
3291 void *map = kmap_atomic(p);
3292 memcpy(buf, map + offset, length);
3295 memset(buf, 0, length);
3306 * vread() - read vmalloc area in a safe way.
3307 * @buf: buffer for reading data
3308 * @addr: vm address.
3309 * @count: number of bytes to be read.
3311 * This function checks that addr is a valid vmalloc'ed area, and
3312 * copy data from that area to a given buffer. If the given memory range
3313 * of [addr...addr+count) includes some valid address, data is copied to
3314 * proper area of @buf. If there are memory holes, they'll be zero-filled.
3315 * IOREMAP area is treated as memory hole and no copy is done.
3317 * If [addr...addr+count) doesn't includes any intersects with alive
3318 * vm_struct area, returns 0. @buf should be kernel's buffer.
3320 * Note: In usual ops, vread() is never necessary because the caller
3321 * should know vmalloc() area is valid and can use memcpy().
3322 * This is for routines which have to access vmalloc area without
3323 * any information, as /proc/kcore.
3325 * Return: number of bytes for which addr and buf should be increased
3326 * (same number as @count) or %0 if [addr...addr+count) doesn't
3327 * include any intersection with valid vmalloc area
3329 long vread(char *buf, char *addr, unsigned long count)
3331 struct vmap_area *va;
3332 struct vm_struct *vm;
3333 char *vaddr, *buf_start = buf;
3334 unsigned long buflen = count;
3337 /* Don't allow overflow */
3338 if ((unsigned long) addr + count < count)
3339 count = -(unsigned long) addr;
3341 spin_lock(&vmap_area_lock);
3342 va = find_vmap_area_exceed_addr((unsigned long)addr);
3346 /* no intersects with alive vmap_area */
3347 if ((unsigned long)addr + count <= va->va_start)
3350 list_for_each_entry_from(va, &vmap_area_list, list) {
3358 vaddr = (char *) vm->addr;
3359 if (addr >= vaddr + get_vm_area_size(vm))
3361 while (addr < vaddr) {
3369 n = vaddr + get_vm_area_size(vm) - addr;
3372 if (!(vm->flags & VM_IOREMAP))
3373 aligned_vread(buf, addr, n);
3374 else /* IOREMAP area is treated as memory hole */
3381 spin_unlock(&vmap_area_lock);
3383 if (buf == buf_start)
3385 /* zero-fill memory holes */
3386 if (buf != buf_start + buflen)
3387 memset(buf, 0, buflen - (buf - buf_start));
3393 * remap_vmalloc_range_partial - map vmalloc pages to userspace
3394 * @vma: vma to cover
3395 * @uaddr: target user address to start at
3396 * @kaddr: virtual address of vmalloc kernel memory
3397 * @pgoff: offset from @kaddr to start at
3398 * @size: size of map area
3400 * Returns: 0 for success, -Exxx on failure
3402 * This function checks that @kaddr is a valid vmalloc'ed area,
3403 * and that it is big enough to cover the range starting at
3404 * @uaddr in @vma. Will return failure if that criteria isn't
3407 * Similar to remap_pfn_range() (see mm/memory.c)
3409 int remap_vmalloc_range_partial(struct vm_area_struct *vma, unsigned long uaddr,
3410 void *kaddr, unsigned long pgoff,
3413 struct vm_struct *area;
3415 unsigned long end_index;
3417 if (check_shl_overflow(pgoff, PAGE_SHIFT, &off))
3420 size = PAGE_ALIGN(size);
3422 if (!PAGE_ALIGNED(uaddr) || !PAGE_ALIGNED(kaddr))
3425 area = find_vm_area(kaddr);
3429 if (!(area->flags & (VM_USERMAP | VM_DMA_COHERENT)))
3432 if (check_add_overflow(size, off, &end_index) ||
3433 end_index > get_vm_area_size(area))
3438 struct page *page = vmalloc_to_page(kaddr);
3441 ret = vm_insert_page(vma, uaddr, page);
3450 vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
3456 * remap_vmalloc_range - map vmalloc pages to userspace
3457 * @vma: vma to cover (map full range of vma)
3458 * @addr: vmalloc memory
3459 * @pgoff: number of pages into addr before first page to map
3461 * Returns: 0 for success, -Exxx on failure
3463 * This function checks that addr is a valid vmalloc'ed area, and
3464 * that it is big enough to cover the vma. Will return failure if
3465 * that criteria isn't met.
3467 * Similar to remap_pfn_range() (see mm/memory.c)
3469 int remap_vmalloc_range(struct vm_area_struct *vma, void *addr,
3470 unsigned long pgoff)
3472 return remap_vmalloc_range_partial(vma, vma->vm_start,
3474 vma->vm_end - vma->vm_start);
3476 EXPORT_SYMBOL(remap_vmalloc_range);
3478 void free_vm_area(struct vm_struct *area)
3480 struct vm_struct *ret;
3481 ret = remove_vm_area(area->addr);
3482 BUG_ON(ret != area);
3485 EXPORT_SYMBOL_GPL(free_vm_area);
3488 static struct vmap_area *node_to_va(struct rb_node *n)
3490 return rb_entry_safe(n, struct vmap_area, rb_node);
3494 * pvm_find_va_enclose_addr - find the vmap_area @addr belongs to
3495 * @addr: target address
3497 * Returns: vmap_area if it is found. If there is no such area
3498 * the first highest(reverse order) vmap_area is returned
3499 * i.e. va->va_start < addr && va->va_end < addr or NULL
3500 * if there are no any areas before @addr.
3502 static struct vmap_area *
3503 pvm_find_va_enclose_addr(unsigned long addr)
3505 struct vmap_area *va, *tmp;
3508 n = free_vmap_area_root.rb_node;
3512 tmp = rb_entry(n, struct vmap_area, rb_node);
3513 if (tmp->va_start <= addr) {
3515 if (tmp->va_end >= addr)
3528 * pvm_determine_end_from_reverse - find the highest aligned address
3529 * of free block below VMALLOC_END
3531 * in - the VA we start the search(reverse order);
3532 * out - the VA with the highest aligned end address.
3533 * @align: alignment for required highest address
3535 * Returns: determined end address within vmap_area
3537 static unsigned long
3538 pvm_determine_end_from_reverse(struct vmap_area **va, unsigned long align)
3540 unsigned long vmalloc_end = VMALLOC_END & ~(align - 1);
3544 list_for_each_entry_from_reverse((*va),
3545 &free_vmap_area_list, list) {
3546 addr = min((*va)->va_end & ~(align - 1), vmalloc_end);
3547 if ((*va)->va_start < addr)
3556 * pcpu_get_vm_areas - allocate vmalloc areas for percpu allocator
3557 * @offsets: array containing offset of each area
3558 * @sizes: array containing size of each area
3559 * @nr_vms: the number of areas to allocate
3560 * @align: alignment, all entries in @offsets and @sizes must be aligned to this
3562 * Returns: kmalloc'd vm_struct pointer array pointing to allocated
3563 * vm_structs on success, %NULL on failure
3565 * Percpu allocator wants to use congruent vm areas so that it can
3566 * maintain the offsets among percpu areas. This function allocates
3567 * congruent vmalloc areas for it with GFP_KERNEL. These areas tend to
3568 * be scattered pretty far, distance between two areas easily going up
3569 * to gigabytes. To avoid interacting with regular vmallocs, these
3570 * areas are allocated from top.
3572 * Despite its complicated look, this allocator is rather simple. It
3573 * does everything top-down and scans free blocks from the end looking
3574 * for matching base. While scanning, if any of the areas do not fit the
3575 * base address is pulled down to fit the area. Scanning is repeated till
3576 * all the areas fit and then all necessary data structures are inserted
3577 * and the result is returned.
3579 struct vm_struct **pcpu_get_vm_areas(const unsigned long *offsets,
3580 const size_t *sizes, int nr_vms,
3583 const unsigned long vmalloc_start = ALIGN(VMALLOC_START, align);
3584 const unsigned long vmalloc_end = VMALLOC_END & ~(align - 1);
3585 struct vmap_area **vas, *va;
3586 struct vm_struct **vms;
3587 int area, area2, last_area, term_area;
3588 unsigned long base, start, size, end, last_end, orig_start, orig_end;
3589 bool purged = false;
3592 /* verify parameters and allocate data structures */
3593 BUG_ON(offset_in_page(align) || !is_power_of_2(align));
3594 for (last_area = 0, area = 0; area < nr_vms; area++) {
3595 start = offsets[area];
3596 end = start + sizes[area];
3598 /* is everything aligned properly? */
3599 BUG_ON(!IS_ALIGNED(offsets[area], align));
3600 BUG_ON(!IS_ALIGNED(sizes[area], align));
3602 /* detect the area with the highest address */
3603 if (start > offsets[last_area])
3606 for (area2 = area + 1; area2 < nr_vms; area2++) {
3607 unsigned long start2 = offsets[area2];
3608 unsigned long end2 = start2 + sizes[area2];
3610 BUG_ON(start2 < end && start < end2);
3613 last_end = offsets[last_area] + sizes[last_area];
3615 if (vmalloc_end - vmalloc_start < last_end) {
3620 vms = kcalloc(nr_vms, sizeof(vms[0]), GFP_KERNEL);
3621 vas = kcalloc(nr_vms, sizeof(vas[0]), GFP_KERNEL);
3625 for (area = 0; area < nr_vms; area++) {
3626 vas[area] = kmem_cache_zalloc(vmap_area_cachep, GFP_KERNEL);
3627 vms[area] = kzalloc(sizeof(struct vm_struct), GFP_KERNEL);
3628 if (!vas[area] || !vms[area])
3632 spin_lock(&free_vmap_area_lock);
3634 /* start scanning - we scan from the top, begin with the last area */
3635 area = term_area = last_area;
3636 start = offsets[area];
3637 end = start + sizes[area];
3639 va = pvm_find_va_enclose_addr(vmalloc_end);
3640 base = pvm_determine_end_from_reverse(&va, align) - end;
3644 * base might have underflowed, add last_end before
3647 if (base + last_end < vmalloc_start + last_end)
3651 * Fitting base has not been found.
3657 * If required width exceeds current VA block, move
3658 * base downwards and then recheck.
3660 if (base + end > va->va_end) {
3661 base = pvm_determine_end_from_reverse(&va, align) - end;
3667 * If this VA does not fit, move base downwards and recheck.
3669 if (base + start < va->va_start) {
3670 va = node_to_va(rb_prev(&va->rb_node));
3671 base = pvm_determine_end_from_reverse(&va, align) - end;
3677 * This area fits, move on to the previous one. If
3678 * the previous one is the terminal one, we're done.
3680 area = (area + nr_vms - 1) % nr_vms;
3681 if (area == term_area)
3684 start = offsets[area];
3685 end = start + sizes[area];
3686 va = pvm_find_va_enclose_addr(base + end);
3689 /* we've found a fitting base, insert all va's */
3690 for (area = 0; area < nr_vms; area++) {
3693 start = base + offsets[area];
3696 va = pvm_find_va_enclose_addr(start);
3697 if (WARN_ON_ONCE(va == NULL))
3698 /* It is a BUG(), but trigger recovery instead. */
3701 type = classify_va_fit_type(va, start, size);
3702 if (WARN_ON_ONCE(type == NOTHING_FIT))
3703 /* It is a BUG(), but trigger recovery instead. */
3706 ret = adjust_va_to_fit_type(va, start, size, type);
3710 /* Allocated area. */
3712 va->va_start = start;
3713 va->va_end = start + size;
3716 spin_unlock(&free_vmap_area_lock);
3718 /* populate the kasan shadow space */
3719 for (area = 0; area < nr_vms; area++) {
3720 if (kasan_populate_vmalloc(vas[area]->va_start, sizes[area]))
3721 goto err_free_shadow;
3723 kasan_unpoison_vmalloc((void *)vas[area]->va_start,
3727 /* insert all vm's */
3728 spin_lock(&vmap_area_lock);
3729 for (area = 0; area < nr_vms; area++) {
3730 insert_vmap_area(vas[area], &vmap_area_root, &vmap_area_list);
3732 setup_vmalloc_vm_locked(vms[area], vas[area], VM_ALLOC,
3735 spin_unlock(&vmap_area_lock);
3742 * Remove previously allocated areas. There is no
3743 * need in removing these areas from the busy tree,
3744 * because they are inserted only on the final step
3745 * and when pcpu_get_vm_areas() is success.
3748 orig_start = vas[area]->va_start;
3749 orig_end = vas[area]->va_end;
3750 va = merge_or_add_vmap_area_augment(vas[area], &free_vmap_area_root,
3751 &free_vmap_area_list);
3753 kasan_release_vmalloc(orig_start, orig_end,
3754 va->va_start, va->va_end);
3759 spin_unlock(&free_vmap_area_lock);
3761 purge_vmap_area_lazy();
3764 /* Before "retry", check if we recover. */
3765 for (area = 0; area < nr_vms; area++) {
3769 vas[area] = kmem_cache_zalloc(
3770 vmap_area_cachep, GFP_KERNEL);
3779 for (area = 0; area < nr_vms; area++) {
3781 kmem_cache_free(vmap_area_cachep, vas[area]);
3791 spin_lock(&free_vmap_area_lock);
3793 * We release all the vmalloc shadows, even the ones for regions that
3794 * hadn't been successfully added. This relies on kasan_release_vmalloc
3795 * being able to tolerate this case.
3797 for (area = 0; area < nr_vms; area++) {
3798 orig_start = vas[area]->va_start;
3799 orig_end = vas[area]->va_end;
3800 va = merge_or_add_vmap_area_augment(vas[area], &free_vmap_area_root,
3801 &free_vmap_area_list);
3803 kasan_release_vmalloc(orig_start, orig_end,
3804 va->va_start, va->va_end);
3808 spin_unlock(&free_vmap_area_lock);
3815 * pcpu_free_vm_areas - free vmalloc areas for percpu allocator
3816 * @vms: vm_struct pointer array returned by pcpu_get_vm_areas()
3817 * @nr_vms: the number of allocated areas
3819 * Free vm_structs and the array allocated by pcpu_get_vm_areas().
3821 void pcpu_free_vm_areas(struct vm_struct **vms, int nr_vms)
3825 for (i = 0; i < nr_vms; i++)
3826 free_vm_area(vms[i]);
3829 #endif /* CONFIG_SMP */
3831 #ifdef CONFIG_PRINTK
3832 bool vmalloc_dump_obj(void *object)
3834 struct vm_struct *vm;
3835 void *objp = (void *)PAGE_ALIGN((unsigned long)object);
3837 vm = find_vm_area(objp);
3840 pr_cont(" %u-page vmalloc region starting at %#lx allocated at %pS\n",
3841 vm->nr_pages, (unsigned long)vm->addr, vm->caller);
3846 #ifdef CONFIG_PROC_FS
3847 static void *s_start(struct seq_file *m, loff_t *pos)
3848 __acquires(&vmap_purge_lock)
3849 __acquires(&vmap_area_lock)
3851 mutex_lock(&vmap_purge_lock);
3852 spin_lock(&vmap_area_lock);
3854 return seq_list_start(&vmap_area_list, *pos);
3857 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
3859 return seq_list_next(p, &vmap_area_list, pos);
3862 static void s_stop(struct seq_file *m, void *p)
3863 __releases(&vmap_area_lock)
3864 __releases(&vmap_purge_lock)
3866 spin_unlock(&vmap_area_lock);
3867 mutex_unlock(&vmap_purge_lock);
3870 static void show_numa_info(struct seq_file *m, struct vm_struct *v)
3872 if (IS_ENABLED(CONFIG_NUMA)) {
3873 unsigned int nr, *counters = m->private;
3874 unsigned int step = 1U << vm_area_page_order(v);
3879 if (v->flags & VM_UNINITIALIZED)
3881 /* Pair with smp_wmb() in clear_vm_uninitialized_flag() */
3884 memset(counters, 0, nr_node_ids * sizeof(unsigned int));
3886 for (nr = 0; nr < v->nr_pages; nr += step)
3887 counters[page_to_nid(v->pages[nr])] += step;
3888 for_each_node_state(nr, N_HIGH_MEMORY)
3890 seq_printf(m, " N%u=%u", nr, counters[nr]);
3894 static void show_purge_info(struct seq_file *m)
3896 struct vmap_area *va;
3898 spin_lock(&purge_vmap_area_lock);
3899 list_for_each_entry(va, &purge_vmap_area_list, list) {
3900 seq_printf(m, "0x%pK-0x%pK %7ld unpurged vm_area\n",
3901 (void *)va->va_start, (void *)va->va_end,
3902 va->va_end - va->va_start);
3904 spin_unlock(&purge_vmap_area_lock);
3907 static int s_show(struct seq_file *m, void *p)
3909 struct vmap_area *va;
3910 struct vm_struct *v;
3912 va = list_entry(p, struct vmap_area, list);
3915 * s_show can encounter race with remove_vm_area, !vm on behalf
3916 * of vmap area is being tear down or vm_map_ram allocation.
3919 seq_printf(m, "0x%pK-0x%pK %7ld vm_map_ram\n",
3920 (void *)va->va_start, (void *)va->va_end,
3921 va->va_end - va->va_start);
3928 seq_printf(m, "0x%pK-0x%pK %7ld",
3929 v->addr, v->addr + v->size, v->size);
3932 seq_printf(m, " %pS", v->caller);
3935 seq_printf(m, " pages=%d", v->nr_pages);
3938 seq_printf(m, " phys=%pa", &v->phys_addr);
3940 if (v->flags & VM_IOREMAP)
3941 seq_puts(m, " ioremap");
3943 if (v->flags & VM_ALLOC)
3944 seq_puts(m, " vmalloc");
3946 if (v->flags & VM_MAP)
3947 seq_puts(m, " vmap");
3949 if (v->flags & VM_USERMAP)
3950 seq_puts(m, " user");
3952 if (v->flags & VM_DMA_COHERENT)
3953 seq_puts(m, " dma-coherent");
3955 if (is_vmalloc_addr(v->pages))
3956 seq_puts(m, " vpages");
3958 show_numa_info(m, v);
3962 * As a final step, dump "unpurged" areas.
3965 if (list_is_last(&va->list, &vmap_area_list))
3971 static const struct seq_operations vmalloc_op = {
3978 static int __init proc_vmalloc_init(void)
3980 if (IS_ENABLED(CONFIG_NUMA))
3981 proc_create_seq_private("vmallocinfo", 0400, NULL,
3983 nr_node_ids * sizeof(unsigned int), NULL);
3985 proc_create_seq("vmallocinfo", 0400, NULL, &vmalloc_op);
3988 module_init(proc_vmalloc_init);