4 * Copyright (C) 1993 Linus Torvalds
5 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
6 * SMP-safe vmalloc/vfree/ioremap, Tigran Aivazian <tigran@veritas.com>, May 2000
7 * Major rework to support vmap/vunmap, Christoph Hellwig, SGI, August 2002
8 * Numa awareness, Christoph Lameter, SGI, June 2005
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/radix-tree.h>
28 #include <linux/rcupdate.h>
29 #include <linux/pfn.h>
30 #include <linux/kmemleak.h>
31 #include <linux/atomic.h>
32 #include <linux/compiler.h>
33 #include <linux/llist.h>
34 #include <linux/bitops.h>
35 #include <linux/rbtree_augmented.h>
37 #include <linux/uaccess.h>
38 #include <asm/tlbflush.h>
39 #include <asm/shmparam.h>
43 struct vfree_deferred {
44 struct llist_head list;
45 struct work_struct wq;
47 static DEFINE_PER_CPU(struct vfree_deferred, vfree_deferred);
49 static void __vunmap(const void *, int);
51 static void free_work(struct work_struct *w)
53 struct vfree_deferred *p = container_of(w, struct vfree_deferred, wq);
54 struct llist_node *t, *llnode;
56 llist_for_each_safe(llnode, t, llist_del_all(&p->list))
57 __vunmap((void *)llnode, 1);
60 /*** Page table manipulation functions ***/
62 static void vunmap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end)
66 pte = pte_offset_kernel(pmd, addr);
68 pte_t ptent = ptep_get_and_clear(&init_mm, addr, pte);
69 WARN_ON(!pte_none(ptent) && !pte_present(ptent));
70 } while (pte++, addr += PAGE_SIZE, addr != end);
73 static void vunmap_pmd_range(pud_t *pud, unsigned long addr, unsigned long end)
78 pmd = pmd_offset(pud, addr);
80 next = pmd_addr_end(addr, end);
81 if (pmd_clear_huge(pmd))
83 if (pmd_none_or_clear_bad(pmd))
85 vunmap_pte_range(pmd, addr, next);
86 } while (pmd++, addr = next, addr != end);
89 static void vunmap_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end)
94 pud = pud_offset(p4d, addr);
96 next = pud_addr_end(addr, end);
97 if (pud_clear_huge(pud))
99 if (pud_none_or_clear_bad(pud))
101 vunmap_pmd_range(pud, addr, next);
102 } while (pud++, addr = next, addr != end);
105 static void vunmap_p4d_range(pgd_t *pgd, unsigned long addr, unsigned long end)
110 p4d = p4d_offset(pgd, addr);
112 next = p4d_addr_end(addr, end);
113 if (p4d_clear_huge(p4d))
115 if (p4d_none_or_clear_bad(p4d))
117 vunmap_pud_range(p4d, addr, next);
118 } while (p4d++, addr = next, addr != end);
121 static void vunmap_page_range(unsigned long addr, unsigned long end)
127 pgd = pgd_offset_k(addr);
129 next = pgd_addr_end(addr, end);
130 if (pgd_none_or_clear_bad(pgd))
132 vunmap_p4d_range(pgd, addr, next);
133 } while (pgd++, addr = next, addr != end);
136 static int vmap_pte_range(pmd_t *pmd, unsigned long addr,
137 unsigned long end, pgprot_t prot, struct page **pages, int *nr)
142 * nr is a running index into the array which helps higher level
143 * callers keep track of where we're up to.
146 pte = pte_alloc_kernel(pmd, addr);
150 struct page *page = pages[*nr];
152 if (WARN_ON(!pte_none(*pte)))
156 set_pte_at(&init_mm, addr, pte, mk_pte(page, prot));
158 } while (pte++, addr += PAGE_SIZE, addr != end);
162 static int vmap_pmd_range(pud_t *pud, unsigned long addr,
163 unsigned long end, pgprot_t prot, struct page **pages, int *nr)
168 pmd = pmd_alloc(&init_mm, pud, addr);
172 next = pmd_addr_end(addr, end);
173 if (vmap_pte_range(pmd, addr, next, prot, pages, nr))
175 } while (pmd++, addr = next, addr != end);
179 static int vmap_pud_range(p4d_t *p4d, unsigned long addr,
180 unsigned long end, pgprot_t prot, struct page **pages, int *nr)
185 pud = pud_alloc(&init_mm, p4d, addr);
189 next = pud_addr_end(addr, end);
190 if (vmap_pmd_range(pud, addr, next, prot, pages, nr))
192 } while (pud++, addr = next, addr != end);
196 static int vmap_p4d_range(pgd_t *pgd, unsigned long addr,
197 unsigned long end, pgprot_t prot, struct page **pages, int *nr)
202 p4d = p4d_alloc(&init_mm, pgd, addr);
206 next = p4d_addr_end(addr, end);
207 if (vmap_pud_range(p4d, addr, next, prot, pages, nr))
209 } while (p4d++, addr = next, addr != end);
214 * Set up page tables in kva (addr, end). The ptes shall have prot "prot", and
215 * will have pfns corresponding to the "pages" array.
217 * Ie. pte at addr+N*PAGE_SIZE shall point to pfn corresponding to pages[N]
219 static int vmap_page_range_noflush(unsigned long start, unsigned long end,
220 pgprot_t prot, struct page **pages)
224 unsigned long addr = start;
229 pgd = pgd_offset_k(addr);
231 next = pgd_addr_end(addr, end);
232 err = vmap_p4d_range(pgd, addr, next, prot, pages, &nr);
235 } while (pgd++, addr = next, addr != end);
240 static int vmap_page_range(unsigned long start, unsigned long end,
241 pgprot_t prot, struct page **pages)
245 ret = vmap_page_range_noflush(start, end, prot, pages);
246 flush_cache_vmap(start, end);
250 int is_vmalloc_or_module_addr(const void *x)
253 * ARM, x86-64 and sparc64 put modules in a special place,
254 * and fall back on vmalloc() if that fails. Others
255 * just put it in the vmalloc space.
257 #if defined(CONFIG_MODULES) && defined(MODULES_VADDR)
258 unsigned long addr = (unsigned long)x;
259 if (addr >= MODULES_VADDR && addr < MODULES_END)
262 return is_vmalloc_addr(x);
266 * Walk a vmap address to the struct page it maps.
268 struct page *vmalloc_to_page(const void *vmalloc_addr)
270 unsigned long addr = (unsigned long) vmalloc_addr;
271 struct page *page = NULL;
272 pgd_t *pgd = pgd_offset_k(addr);
279 * XXX we might need to change this if we add VIRTUAL_BUG_ON for
280 * architectures that do not vmalloc module space
282 VIRTUAL_BUG_ON(!is_vmalloc_or_module_addr(vmalloc_addr));
286 p4d = p4d_offset(pgd, addr);
289 pud = pud_offset(p4d, addr);
292 * Don't dereference bad PUD or PMD (below) entries. This will also
293 * identify huge mappings, which we may encounter on architectures
294 * that define CONFIG_HAVE_ARCH_HUGE_VMAP=y. Such regions will be
295 * identified as vmalloc addresses by is_vmalloc_addr(), but are
296 * not [unambiguously] associated with a struct page, so there is
297 * no correct value to return for them.
299 WARN_ON_ONCE(pud_bad(*pud));
300 if (pud_none(*pud) || pud_bad(*pud))
302 pmd = pmd_offset(pud, addr);
303 WARN_ON_ONCE(pmd_bad(*pmd));
304 if (pmd_none(*pmd) || pmd_bad(*pmd))
307 ptep = pte_offset_map(pmd, addr);
309 if (pte_present(pte))
310 page = pte_page(pte);
314 EXPORT_SYMBOL(vmalloc_to_page);
317 * Map a vmalloc()-space virtual address to the physical page frame number.
319 unsigned long vmalloc_to_pfn(const void *vmalloc_addr)
321 return page_to_pfn(vmalloc_to_page(vmalloc_addr));
323 EXPORT_SYMBOL(vmalloc_to_pfn);
326 /*** Global kva allocator ***/
328 #define DEBUG_AUGMENT_PROPAGATE_CHECK 0
330 #define VM_LAZY_FREE 0x02
331 #define VM_VM_AREA 0x04
333 static DEFINE_SPINLOCK(vmap_area_lock);
334 /* Export for kexec only */
335 LIST_HEAD(vmap_area_list);
336 static LLIST_HEAD(vmap_purge_list);
337 static struct rb_root vmap_area_root = RB_ROOT;
338 static bool vmap_initialized __read_mostly;
341 * This kmem_cache is used for vmap_area objects. Instead of
342 * allocating from slab we reuse an object from this cache to
343 * make things faster. Especially in "no edge" splitting of
346 static struct kmem_cache *vmap_area_cachep;
349 * This linked list is used in pair with free_vmap_area_root.
350 * It gives O(1) access to prev/next to perform fast coalescing.
352 static LIST_HEAD(free_vmap_area_list);
355 * This augment red-black tree represents the free vmap space.
356 * All vmap_area objects in this tree are sorted by va->va_start
357 * address. It is used for allocation and merging when a vmap
358 * object is released.
360 * Each vmap_area node contains a maximum available free block
361 * of its sub-tree, right or left. Therefore it is possible to
362 * find a lowest match of free area.
364 static struct rb_root free_vmap_area_root = RB_ROOT;
366 static __always_inline unsigned long
367 va_size(struct vmap_area *va)
369 return (va->va_end - va->va_start);
372 static __always_inline unsigned long
373 get_subtree_max_size(struct rb_node *node)
375 struct vmap_area *va;
377 va = rb_entry_safe(node, struct vmap_area, rb_node);
378 return va ? va->subtree_max_size : 0;
382 * Gets called when remove the node and rotate.
384 static __always_inline unsigned long
385 compute_subtree_max_size(struct vmap_area *va)
387 return max3(va_size(va),
388 get_subtree_max_size(va->rb_node.rb_left),
389 get_subtree_max_size(va->rb_node.rb_right));
392 RB_DECLARE_CALLBACKS(static, free_vmap_area_rb_augment_cb,
393 struct vmap_area, rb_node, unsigned long, subtree_max_size,
394 compute_subtree_max_size)
396 static void purge_vmap_area_lazy(void);
397 static BLOCKING_NOTIFIER_HEAD(vmap_notify_list);
398 static unsigned long lazy_max_pages(void);
400 static struct vmap_area *__find_vmap_area(unsigned long addr)
402 struct rb_node *n = vmap_area_root.rb_node;
405 struct vmap_area *va;
407 va = rb_entry(n, struct vmap_area, rb_node);
408 if (addr < va->va_start)
410 else if (addr >= va->va_end)
420 * This function returns back addresses of parent node
421 * and its left or right link for further processing.
423 static __always_inline struct rb_node **
424 find_va_links(struct vmap_area *va,
425 struct rb_root *root, struct rb_node *from,
426 struct rb_node **parent)
428 struct vmap_area *tmp_va;
429 struct rb_node **link;
432 link = &root->rb_node;
433 if (unlikely(!*link)) {
442 * Go to the bottom of the tree. When we hit the last point
443 * we end up with parent rb_node and correct direction, i name
444 * it link, where the new va->rb_node will be attached to.
447 tmp_va = rb_entry(*link, struct vmap_area, rb_node);
450 * During the traversal we also do some sanity check.
451 * Trigger the BUG() if there are sides(left/right)
454 if (va->va_start < tmp_va->va_end &&
455 va->va_end <= tmp_va->va_start)
456 link = &(*link)->rb_left;
457 else if (va->va_end > tmp_va->va_start &&
458 va->va_start >= tmp_va->va_end)
459 link = &(*link)->rb_right;
464 *parent = &tmp_va->rb_node;
468 static __always_inline struct list_head *
469 get_va_next_sibling(struct rb_node *parent, struct rb_node **link)
471 struct list_head *list;
473 if (unlikely(!parent))
475 * The red-black tree where we try to find VA neighbors
476 * before merging or inserting is empty, i.e. it means
477 * there is no free vmap space. Normally it does not
478 * happen but we handle this case anyway.
482 list = &rb_entry(parent, struct vmap_area, rb_node)->list;
483 return (&parent->rb_right == link ? list->next : list);
486 static __always_inline void
487 link_va(struct vmap_area *va, struct rb_root *root,
488 struct rb_node *parent, struct rb_node **link, struct list_head *head)
491 * VA is still not in the list, but we can
492 * identify its future previous list_head node.
494 if (likely(parent)) {
495 head = &rb_entry(parent, struct vmap_area, rb_node)->list;
496 if (&parent->rb_right != link)
500 /* Insert to the rb-tree */
501 rb_link_node(&va->rb_node, parent, link);
502 if (root == &free_vmap_area_root) {
504 * Some explanation here. Just perform simple insertion
505 * to the tree. We do not set va->subtree_max_size to
506 * its current size before calling rb_insert_augmented().
507 * It is because of we populate the tree from the bottom
508 * to parent levels when the node _is_ in the tree.
510 * Therefore we set subtree_max_size to zero after insertion,
511 * to let __augment_tree_propagate_from() puts everything to
512 * the correct order later on.
514 rb_insert_augmented(&va->rb_node,
515 root, &free_vmap_area_rb_augment_cb);
516 va->subtree_max_size = 0;
518 rb_insert_color(&va->rb_node, root);
521 /* Address-sort this list */
522 list_add(&va->list, head);
525 static __always_inline void
526 unlink_va(struct vmap_area *va, struct rb_root *root)
529 * During merging a VA node can be empty, therefore
530 * not linked with the tree nor list. Just check it.
532 if (!RB_EMPTY_NODE(&va->rb_node)) {
533 if (root == &free_vmap_area_root)
534 rb_erase_augmented(&va->rb_node,
535 root, &free_vmap_area_rb_augment_cb);
537 rb_erase(&va->rb_node, root);
540 RB_CLEAR_NODE(&va->rb_node);
544 #if DEBUG_AUGMENT_PROPAGATE_CHECK
546 augment_tree_propagate_check(struct rb_node *n)
548 struct vmap_area *va;
549 struct rb_node *node;
556 va = rb_entry(n, struct vmap_area, rb_node);
557 size = va->subtree_max_size;
561 va = rb_entry(node, struct vmap_area, rb_node);
563 if (get_subtree_max_size(node->rb_left) == size) {
564 node = node->rb_left;
566 if (va_size(va) == size) {
571 node = node->rb_right;
576 va = rb_entry(n, struct vmap_area, rb_node);
577 pr_emerg("tree is corrupted: %lu, %lu\n",
578 va_size(va), va->subtree_max_size);
581 augment_tree_propagate_check(n->rb_left);
582 augment_tree_propagate_check(n->rb_right);
587 * This function populates subtree_max_size from bottom to upper
588 * levels starting from VA point. The propagation must be done
589 * when VA size is modified by changing its va_start/va_end. Or
590 * in case of newly inserting of VA to the tree.
592 * It means that __augment_tree_propagate_from() must be called:
593 * - After VA has been inserted to the tree(free path);
594 * - After VA has been shrunk(allocation path);
595 * - After VA has been increased(merging path).
597 * Please note that, it does not mean that upper parent nodes
598 * and their subtree_max_size are recalculated all the time up
607 * For example if we modify the node 4, shrinking it to 2, then
608 * no any modification is required. If we shrink the node 2 to 1
609 * its subtree_max_size is updated only, and set to 1. If we shrink
610 * the node 8 to 6, then its subtree_max_size is set to 6 and parent
613 static __always_inline void
614 augment_tree_propagate_from(struct vmap_area *va)
616 struct rb_node *node = &va->rb_node;
617 unsigned long new_va_sub_max_size;
620 va = rb_entry(node, struct vmap_area, rb_node);
621 new_va_sub_max_size = compute_subtree_max_size(va);
624 * If the newly calculated maximum available size of the
625 * subtree is equal to the current one, then it means that
626 * the tree is propagated correctly. So we have to stop at
627 * this point to save cycles.
629 if (va->subtree_max_size == new_va_sub_max_size)
632 va->subtree_max_size = new_va_sub_max_size;
633 node = rb_parent(&va->rb_node);
636 #if DEBUG_AUGMENT_PROPAGATE_CHECK
637 augment_tree_propagate_check(free_vmap_area_root.rb_node);
642 insert_vmap_area(struct vmap_area *va,
643 struct rb_root *root, struct list_head *head)
645 struct rb_node **link;
646 struct rb_node *parent;
648 link = find_va_links(va, root, NULL, &parent);
649 link_va(va, root, parent, link, head);
653 insert_vmap_area_augment(struct vmap_area *va,
654 struct rb_node *from, struct rb_root *root,
655 struct list_head *head)
657 struct rb_node **link;
658 struct rb_node *parent;
661 link = find_va_links(va, NULL, from, &parent);
663 link = find_va_links(va, root, NULL, &parent);
665 link_va(va, root, parent, link, head);
666 augment_tree_propagate_from(va);
670 * Merge de-allocated chunk of VA memory with previous
671 * and next free blocks. If coalesce is not done a new
672 * free area is inserted. If VA has been merged, it is
675 static __always_inline void
676 merge_or_add_vmap_area(struct vmap_area *va,
677 struct rb_root *root, struct list_head *head)
679 struct vmap_area *sibling;
680 struct list_head *next;
681 struct rb_node **link;
682 struct rb_node *parent;
686 * Find a place in the tree where VA potentially will be
687 * inserted, unless it is merged with its sibling/siblings.
689 link = find_va_links(va, root, NULL, &parent);
692 * Get next node of VA to check if merging can be done.
694 next = get_va_next_sibling(parent, link);
695 if (unlikely(next == NULL))
701 * |<------VA------>|<-----Next----->|
706 sibling = list_entry(next, struct vmap_area, list);
707 if (sibling->va_start == va->va_end) {
708 sibling->va_start = va->va_start;
710 /* Check and update the tree if needed. */
711 augment_tree_propagate_from(sibling);
713 /* Remove this VA, it has been merged. */
716 /* Free vmap_area object. */
717 kmem_cache_free(vmap_area_cachep, va);
719 /* Point to the new merged area. */
728 * |<-----Prev----->|<------VA------>|
732 if (next->prev != head) {
733 sibling = list_entry(next->prev, struct vmap_area, list);
734 if (sibling->va_end == va->va_start) {
735 sibling->va_end = va->va_end;
737 /* Check and update the tree if needed. */
738 augment_tree_propagate_from(sibling);
740 /* Remove this VA, it has been merged. */
743 /* Free vmap_area object. */
744 kmem_cache_free(vmap_area_cachep, va);
752 link_va(va, root, parent, link, head);
753 augment_tree_propagate_from(va);
757 static __always_inline bool
758 is_within_this_va(struct vmap_area *va, unsigned long size,
759 unsigned long align, unsigned long vstart)
761 unsigned long nva_start_addr;
763 if (va->va_start > vstart)
764 nva_start_addr = ALIGN(va->va_start, align);
766 nva_start_addr = ALIGN(vstart, align);
768 /* Can be overflowed due to big size or alignment. */
769 if (nva_start_addr + size < nva_start_addr ||
770 nva_start_addr < vstart)
773 return (nva_start_addr + size <= va->va_end);
777 * Find the first free block(lowest start address) in the tree,
778 * that will accomplish the request corresponding to passing
781 static __always_inline struct vmap_area *
782 find_vmap_lowest_match(unsigned long size,
783 unsigned long align, unsigned long vstart)
785 struct vmap_area *va;
786 struct rb_node *node;
787 unsigned long length;
789 /* Start from the root. */
790 node = free_vmap_area_root.rb_node;
792 /* Adjust the search size for alignment overhead. */
793 length = size + align - 1;
796 va = rb_entry(node, struct vmap_area, rb_node);
798 if (get_subtree_max_size(node->rb_left) >= length &&
799 vstart < va->va_start) {
800 node = node->rb_left;
802 if (is_within_this_va(va, size, align, vstart))
806 * Does not make sense to go deeper towards the right
807 * sub-tree if it does not have a free block that is
808 * equal or bigger to the requested search length.
810 if (get_subtree_max_size(node->rb_right) >= length) {
811 node = node->rb_right;
816 * OK. We roll back and find the fist right sub-tree,
817 * that will satisfy the search criteria. It can happen
818 * only once due to "vstart" restriction.
820 while ((node = rb_parent(node))) {
821 va = rb_entry(node, struct vmap_area, rb_node);
822 if (is_within_this_va(va, size, align, vstart))
825 if (get_subtree_max_size(node->rb_right) >= length &&
826 vstart <= va->va_start) {
827 node = node->rb_right;
839 FL_FIT_TYPE = 1, /* full fit */
840 LE_FIT_TYPE = 2, /* left edge fit */
841 RE_FIT_TYPE = 3, /* right edge fit */
842 NE_FIT_TYPE = 4 /* no edge fit */
845 static __always_inline enum fit_type
846 classify_va_fit_type(struct vmap_area *va,
847 unsigned long nva_start_addr, unsigned long size)
851 /* Check if it is within VA. */
852 if (nva_start_addr < va->va_start ||
853 nva_start_addr + size > va->va_end)
857 if (va->va_start == nva_start_addr) {
858 if (va->va_end == nva_start_addr + size)
862 } else if (va->va_end == nva_start_addr + size) {
871 static __always_inline int
872 adjust_va_to_fit_type(struct vmap_area *va,
873 unsigned long nva_start_addr, unsigned long size,
876 struct vmap_area *lva;
878 if (type == FL_FIT_TYPE) {
880 * No need to split VA, it fully fits.
886 unlink_va(va, &free_vmap_area_root);
887 kmem_cache_free(vmap_area_cachep, va);
888 } else if (type == LE_FIT_TYPE) {
890 * Split left edge of fit VA.
896 va->va_start += size;
897 } else if (type == RE_FIT_TYPE) {
899 * Split right edge of fit VA.
905 va->va_end = nva_start_addr;
906 } else if (type == NE_FIT_TYPE) {
908 * Split no edge of fit VA.
914 lva = kmem_cache_alloc(vmap_area_cachep, GFP_NOWAIT);
919 * Build the remainder.
921 lva->va_start = va->va_start;
922 lva->va_end = nva_start_addr;
925 * Shrink this VA to remaining size.
927 va->va_start = nva_start_addr + size;
932 if (type != FL_FIT_TYPE) {
933 augment_tree_propagate_from(va);
935 if (type == NE_FIT_TYPE)
936 insert_vmap_area_augment(lva, &va->rb_node,
937 &free_vmap_area_root, &free_vmap_area_list);
944 * Returns a start address of the newly allocated area, if success.
945 * Otherwise a vend is returned that indicates failure.
947 static __always_inline unsigned long
948 __alloc_vmap_area(unsigned long size, unsigned long align,
949 unsigned long vstart, unsigned long vend, int node)
951 unsigned long nva_start_addr;
952 struct vmap_area *va;
956 va = find_vmap_lowest_match(size, align, vstart);
960 if (va->va_start > vstart)
961 nva_start_addr = ALIGN(va->va_start, align);
963 nva_start_addr = ALIGN(vstart, align);
965 /* Check the "vend" restriction. */
966 if (nva_start_addr + size > vend)
969 /* Classify what we have found. */
970 type = classify_va_fit_type(va, nva_start_addr, size);
971 if (WARN_ON_ONCE(type == NOTHING_FIT))
974 /* Update the free vmap_area. */
975 ret = adjust_va_to_fit_type(va, nva_start_addr, size, type);
979 return nva_start_addr;
983 * Allocate a region of KVA of the specified size and alignment, within the
986 static struct vmap_area *alloc_vmap_area(unsigned long size,
988 unsigned long vstart, unsigned long vend,
989 int node, gfp_t gfp_mask)
991 struct vmap_area *va;
996 BUG_ON(offset_in_page(size));
997 BUG_ON(!is_power_of_2(align));
999 if (unlikely(!vmap_initialized))
1000 return ERR_PTR(-EBUSY);
1004 va = kmem_cache_alloc_node(vmap_area_cachep,
1005 gfp_mask & GFP_RECLAIM_MASK, node);
1007 return ERR_PTR(-ENOMEM);
1010 * Only scan the relevant parts containing pointers to other objects
1011 * to avoid false negatives.
1013 kmemleak_scan_area(&va->rb_node, SIZE_MAX, gfp_mask & GFP_RECLAIM_MASK);
1016 spin_lock(&vmap_area_lock);
1019 * If an allocation fails, the "vend" address is
1020 * returned. Therefore trigger the overflow path.
1022 addr = __alloc_vmap_area(size, align, vstart, vend, node);
1023 if (unlikely(addr == vend))
1026 va->va_start = addr;
1027 va->va_end = addr + size;
1029 insert_vmap_area(va, &vmap_area_root, &vmap_area_list);
1031 spin_unlock(&vmap_area_lock);
1033 BUG_ON(!IS_ALIGNED(va->va_start, align));
1034 BUG_ON(va->va_start < vstart);
1035 BUG_ON(va->va_end > vend);
1040 spin_unlock(&vmap_area_lock);
1042 purge_vmap_area_lazy();
1047 if (gfpflags_allow_blocking(gfp_mask)) {
1048 unsigned long freed = 0;
1049 blocking_notifier_call_chain(&vmap_notify_list, 0, &freed);
1056 if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit())
1057 pr_warn("vmap allocation for size %lu failed: use vmalloc=<size> to increase size\n",
1060 kmem_cache_free(vmap_area_cachep, va);
1061 return ERR_PTR(-EBUSY);
1064 int register_vmap_purge_notifier(struct notifier_block *nb)
1066 return blocking_notifier_chain_register(&vmap_notify_list, nb);
1068 EXPORT_SYMBOL_GPL(register_vmap_purge_notifier);
1070 int unregister_vmap_purge_notifier(struct notifier_block *nb)
1072 return blocking_notifier_chain_unregister(&vmap_notify_list, nb);
1074 EXPORT_SYMBOL_GPL(unregister_vmap_purge_notifier);
1076 static void __free_vmap_area(struct vmap_area *va)
1078 BUG_ON(RB_EMPTY_NODE(&va->rb_node));
1081 * Remove from the busy tree/list.
1083 unlink_va(va, &vmap_area_root);
1086 * Merge VA with its neighbors, otherwise just add it.
1088 merge_or_add_vmap_area(va,
1089 &free_vmap_area_root, &free_vmap_area_list);
1093 * Free a region of KVA allocated by alloc_vmap_area
1095 static void free_vmap_area(struct vmap_area *va)
1097 spin_lock(&vmap_area_lock);
1098 __free_vmap_area(va);
1099 spin_unlock(&vmap_area_lock);
1103 * Clear the pagetable entries of a given vmap_area
1105 static void unmap_vmap_area(struct vmap_area *va)
1107 vunmap_page_range(va->va_start, va->va_end);
1111 * lazy_max_pages is the maximum amount of virtual address space we gather up
1112 * before attempting to purge with a TLB flush.
1114 * There is a tradeoff here: a larger number will cover more kernel page tables
1115 * and take slightly longer to purge, but it will linearly reduce the number of
1116 * global TLB flushes that must be performed. It would seem natural to scale
1117 * this number up linearly with the number of CPUs (because vmapping activity
1118 * could also scale linearly with the number of CPUs), however it is likely
1119 * that in practice, workloads might be constrained in other ways that mean
1120 * vmap activity will not scale linearly with CPUs. Also, I want to be
1121 * conservative and not introduce a big latency on huge systems, so go with
1122 * a less aggressive log scale. It will still be an improvement over the old
1123 * code, and it will be simple to change the scale factor if we find that it
1124 * becomes a problem on bigger systems.
1126 static unsigned long lazy_max_pages(void)
1130 log = fls(num_online_cpus());
1132 return log * (32UL * 1024 * 1024 / PAGE_SIZE);
1135 static atomic_long_t vmap_lazy_nr = ATOMIC_LONG_INIT(0);
1138 * Serialize vmap purging. There is no actual criticial section protected
1139 * by this look, but we want to avoid concurrent calls for performance
1140 * reasons and to make the pcpu_get_vm_areas more deterministic.
1142 static DEFINE_MUTEX(vmap_purge_lock);
1144 /* for per-CPU blocks */
1145 static void purge_fragmented_blocks_allcpus(void);
1148 * called before a call to iounmap() if the caller wants vm_area_struct's
1149 * immediately freed.
1151 void set_iounmap_nonlazy(void)
1153 atomic_long_set(&vmap_lazy_nr, lazy_max_pages()+1);
1157 * Purges all lazily-freed vmap areas.
1159 static bool __purge_vmap_area_lazy(unsigned long start, unsigned long end)
1161 unsigned long resched_threshold;
1162 struct llist_node *valist;
1163 struct vmap_area *va;
1164 struct vmap_area *n_va;
1166 lockdep_assert_held(&vmap_purge_lock);
1168 valist = llist_del_all(&vmap_purge_list);
1169 if (unlikely(valist == NULL))
1173 * TODO: to calculate a flush range without looping.
1174 * The list can be up to lazy_max_pages() elements.
1176 llist_for_each_entry(va, valist, purge_list) {
1177 if (va->va_start < start)
1178 start = va->va_start;
1179 if (va->va_end > end)
1183 flush_tlb_kernel_range(start, end);
1184 resched_threshold = lazy_max_pages() << 1;
1186 spin_lock(&vmap_area_lock);
1187 llist_for_each_entry_safe(va, n_va, valist, purge_list) {
1188 unsigned long nr = (va->va_end - va->va_start) >> PAGE_SHIFT;
1190 __free_vmap_area(va);
1191 atomic_long_sub(nr, &vmap_lazy_nr);
1193 if (atomic_long_read(&vmap_lazy_nr) < resched_threshold)
1194 cond_resched_lock(&vmap_area_lock);
1196 spin_unlock(&vmap_area_lock);
1201 * Kick off a purge of the outstanding lazy areas. Don't bother if somebody
1202 * is already purging.
1204 static void try_purge_vmap_area_lazy(void)
1206 if (mutex_trylock(&vmap_purge_lock)) {
1207 __purge_vmap_area_lazy(ULONG_MAX, 0);
1208 mutex_unlock(&vmap_purge_lock);
1213 * Kick off a purge of the outstanding lazy areas.
1215 static void purge_vmap_area_lazy(void)
1217 mutex_lock(&vmap_purge_lock);
1218 purge_fragmented_blocks_allcpus();
1219 __purge_vmap_area_lazy(ULONG_MAX, 0);
1220 mutex_unlock(&vmap_purge_lock);
1224 * Free a vmap area, caller ensuring that the area has been unmapped
1225 * and flush_cache_vunmap had been called for the correct range
1228 static void free_vmap_area_noflush(struct vmap_area *va)
1230 unsigned long nr_lazy;
1232 nr_lazy = atomic_long_add_return((va->va_end - va->va_start) >>
1233 PAGE_SHIFT, &vmap_lazy_nr);
1235 /* After this point, we may free va at any time */
1236 llist_add(&va->purge_list, &vmap_purge_list);
1238 if (unlikely(nr_lazy > lazy_max_pages()))
1239 try_purge_vmap_area_lazy();
1243 * Free and unmap a vmap area
1245 static void free_unmap_vmap_area(struct vmap_area *va)
1247 flush_cache_vunmap(va->va_start, va->va_end);
1248 unmap_vmap_area(va);
1249 if (debug_pagealloc_enabled())
1250 flush_tlb_kernel_range(va->va_start, va->va_end);
1252 free_vmap_area_noflush(va);
1255 static struct vmap_area *find_vmap_area(unsigned long addr)
1257 struct vmap_area *va;
1259 spin_lock(&vmap_area_lock);
1260 va = __find_vmap_area(addr);
1261 spin_unlock(&vmap_area_lock);
1266 /*** Per cpu kva allocator ***/
1269 * vmap space is limited especially on 32 bit architectures. Ensure there is
1270 * room for at least 16 percpu vmap blocks per CPU.
1273 * If we had a constant VMALLOC_START and VMALLOC_END, we'd like to be able
1274 * to #define VMALLOC_SPACE (VMALLOC_END-VMALLOC_START). Guess
1275 * instead (we just need a rough idea)
1277 #if BITS_PER_LONG == 32
1278 #define VMALLOC_SPACE (128UL*1024*1024)
1280 #define VMALLOC_SPACE (128UL*1024*1024*1024)
1283 #define VMALLOC_PAGES (VMALLOC_SPACE / PAGE_SIZE)
1284 #define VMAP_MAX_ALLOC BITS_PER_LONG /* 256K with 4K pages */
1285 #define VMAP_BBMAP_BITS_MAX 1024 /* 4MB with 4K pages */
1286 #define VMAP_BBMAP_BITS_MIN (VMAP_MAX_ALLOC*2)
1287 #define VMAP_MIN(x, y) ((x) < (y) ? (x) : (y)) /* can't use min() */
1288 #define VMAP_MAX(x, y) ((x) > (y) ? (x) : (y)) /* can't use max() */
1289 #define VMAP_BBMAP_BITS \
1290 VMAP_MIN(VMAP_BBMAP_BITS_MAX, \
1291 VMAP_MAX(VMAP_BBMAP_BITS_MIN, \
1292 VMALLOC_PAGES / roundup_pow_of_two(NR_CPUS) / 16))
1294 #define VMAP_BLOCK_SIZE (VMAP_BBMAP_BITS * PAGE_SIZE)
1296 struct vmap_block_queue {
1298 struct list_head free;
1303 struct vmap_area *va;
1304 unsigned long free, dirty;
1305 unsigned long dirty_min, dirty_max; /*< dirty range */
1306 struct list_head free_list;
1307 struct rcu_head rcu_head;
1308 struct list_head purge;
1311 /* Queue of free and dirty vmap blocks, for allocation and flushing purposes */
1312 static DEFINE_PER_CPU(struct vmap_block_queue, vmap_block_queue);
1315 * Radix tree of vmap blocks, indexed by address, to quickly find a vmap block
1316 * in the free path. Could get rid of this if we change the API to return a
1317 * "cookie" from alloc, to be passed to free. But no big deal yet.
1319 static DEFINE_SPINLOCK(vmap_block_tree_lock);
1320 static RADIX_TREE(vmap_block_tree, GFP_ATOMIC);
1323 * We should probably have a fallback mechanism to allocate virtual memory
1324 * out of partially filled vmap blocks. However vmap block sizing should be
1325 * fairly reasonable according to the vmalloc size, so it shouldn't be a
1329 static unsigned long addr_to_vb_idx(unsigned long addr)
1331 addr -= VMALLOC_START & ~(VMAP_BLOCK_SIZE-1);
1332 addr /= VMAP_BLOCK_SIZE;
1336 static void *vmap_block_vaddr(unsigned long va_start, unsigned long pages_off)
1340 addr = va_start + (pages_off << PAGE_SHIFT);
1341 BUG_ON(addr_to_vb_idx(addr) != addr_to_vb_idx(va_start));
1342 return (void *)addr;
1346 * new_vmap_block - allocates new vmap_block and occupies 2^order pages in this
1347 * block. Of course pages number can't exceed VMAP_BBMAP_BITS
1348 * @order: how many 2^order pages should be occupied in newly allocated block
1349 * @gfp_mask: flags for the page level allocator
1351 * Return: virtual address in a newly allocated block or ERR_PTR(-errno)
1353 static void *new_vmap_block(unsigned int order, gfp_t gfp_mask)
1355 struct vmap_block_queue *vbq;
1356 struct vmap_block *vb;
1357 struct vmap_area *va;
1358 unsigned long vb_idx;
1362 node = numa_node_id();
1364 vb = kmalloc_node(sizeof(struct vmap_block),
1365 gfp_mask & GFP_RECLAIM_MASK, node);
1367 return ERR_PTR(-ENOMEM);
1369 va = alloc_vmap_area(VMAP_BLOCK_SIZE, VMAP_BLOCK_SIZE,
1370 VMALLOC_START, VMALLOC_END,
1374 return ERR_CAST(va);
1377 err = radix_tree_preload(gfp_mask);
1378 if (unlikely(err)) {
1381 return ERR_PTR(err);
1384 vaddr = vmap_block_vaddr(va->va_start, 0);
1385 spin_lock_init(&vb->lock);
1387 /* At least something should be left free */
1388 BUG_ON(VMAP_BBMAP_BITS <= (1UL << order));
1389 vb->free = VMAP_BBMAP_BITS - (1UL << order);
1391 vb->dirty_min = VMAP_BBMAP_BITS;
1393 INIT_LIST_HEAD(&vb->free_list);
1395 vb_idx = addr_to_vb_idx(va->va_start);
1396 spin_lock(&vmap_block_tree_lock);
1397 err = radix_tree_insert(&vmap_block_tree, vb_idx, vb);
1398 spin_unlock(&vmap_block_tree_lock);
1400 radix_tree_preload_end();
1402 vbq = &get_cpu_var(vmap_block_queue);
1403 spin_lock(&vbq->lock);
1404 list_add_tail_rcu(&vb->free_list, &vbq->free);
1405 spin_unlock(&vbq->lock);
1406 put_cpu_var(vmap_block_queue);
1411 static void free_vmap_block(struct vmap_block *vb)
1413 struct vmap_block *tmp;
1414 unsigned long vb_idx;
1416 vb_idx = addr_to_vb_idx(vb->va->va_start);
1417 spin_lock(&vmap_block_tree_lock);
1418 tmp = radix_tree_delete(&vmap_block_tree, vb_idx);
1419 spin_unlock(&vmap_block_tree_lock);
1422 free_vmap_area_noflush(vb->va);
1423 kfree_rcu(vb, rcu_head);
1426 static void purge_fragmented_blocks(int cpu)
1429 struct vmap_block *vb;
1430 struct vmap_block *n_vb;
1431 struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu);
1434 list_for_each_entry_rcu(vb, &vbq->free, free_list) {
1436 if (!(vb->free + vb->dirty == VMAP_BBMAP_BITS && vb->dirty != VMAP_BBMAP_BITS))
1439 spin_lock(&vb->lock);
1440 if (vb->free + vb->dirty == VMAP_BBMAP_BITS && vb->dirty != VMAP_BBMAP_BITS) {
1441 vb->free = 0; /* prevent further allocs after releasing lock */
1442 vb->dirty = VMAP_BBMAP_BITS; /* prevent purging it again */
1444 vb->dirty_max = VMAP_BBMAP_BITS;
1445 spin_lock(&vbq->lock);
1446 list_del_rcu(&vb->free_list);
1447 spin_unlock(&vbq->lock);
1448 spin_unlock(&vb->lock);
1449 list_add_tail(&vb->purge, &purge);
1451 spin_unlock(&vb->lock);
1455 list_for_each_entry_safe(vb, n_vb, &purge, purge) {
1456 list_del(&vb->purge);
1457 free_vmap_block(vb);
1461 static void purge_fragmented_blocks_allcpus(void)
1465 for_each_possible_cpu(cpu)
1466 purge_fragmented_blocks(cpu);
1469 static void *vb_alloc(unsigned long size, gfp_t gfp_mask)
1471 struct vmap_block_queue *vbq;
1472 struct vmap_block *vb;
1476 BUG_ON(offset_in_page(size));
1477 BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
1478 if (WARN_ON(size == 0)) {
1480 * Allocating 0 bytes isn't what caller wants since
1481 * get_order(0) returns funny result. Just warn and terminate
1486 order = get_order(size);
1489 vbq = &get_cpu_var(vmap_block_queue);
1490 list_for_each_entry_rcu(vb, &vbq->free, free_list) {
1491 unsigned long pages_off;
1493 spin_lock(&vb->lock);
1494 if (vb->free < (1UL << order)) {
1495 spin_unlock(&vb->lock);
1499 pages_off = VMAP_BBMAP_BITS - vb->free;
1500 vaddr = vmap_block_vaddr(vb->va->va_start, pages_off);
1501 vb->free -= 1UL << order;
1502 if (vb->free == 0) {
1503 spin_lock(&vbq->lock);
1504 list_del_rcu(&vb->free_list);
1505 spin_unlock(&vbq->lock);
1508 spin_unlock(&vb->lock);
1512 put_cpu_var(vmap_block_queue);
1515 /* Allocate new block if nothing was found */
1517 vaddr = new_vmap_block(order, gfp_mask);
1522 static void vb_free(const void *addr, unsigned long size)
1524 unsigned long offset;
1525 unsigned long vb_idx;
1527 struct vmap_block *vb;
1529 BUG_ON(offset_in_page(size));
1530 BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
1532 flush_cache_vunmap((unsigned long)addr, (unsigned long)addr + size);
1534 order = get_order(size);
1536 offset = (unsigned long)addr & (VMAP_BLOCK_SIZE - 1);
1537 offset >>= PAGE_SHIFT;
1539 vb_idx = addr_to_vb_idx((unsigned long)addr);
1541 vb = radix_tree_lookup(&vmap_block_tree, vb_idx);
1545 vunmap_page_range((unsigned long)addr, (unsigned long)addr + size);
1547 if (debug_pagealloc_enabled())
1548 flush_tlb_kernel_range((unsigned long)addr,
1549 (unsigned long)addr + size);
1551 spin_lock(&vb->lock);
1553 /* Expand dirty range */
1554 vb->dirty_min = min(vb->dirty_min, offset);
1555 vb->dirty_max = max(vb->dirty_max, offset + (1UL << order));
1557 vb->dirty += 1UL << order;
1558 if (vb->dirty == VMAP_BBMAP_BITS) {
1560 spin_unlock(&vb->lock);
1561 free_vmap_block(vb);
1563 spin_unlock(&vb->lock);
1566 static void _vm_unmap_aliases(unsigned long start, unsigned long end, int flush)
1570 if (unlikely(!vmap_initialized))
1575 for_each_possible_cpu(cpu) {
1576 struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu);
1577 struct vmap_block *vb;
1580 list_for_each_entry_rcu(vb, &vbq->free, free_list) {
1581 spin_lock(&vb->lock);
1583 unsigned long va_start = vb->va->va_start;
1586 s = va_start + (vb->dirty_min << PAGE_SHIFT);
1587 e = va_start + (vb->dirty_max << PAGE_SHIFT);
1589 start = min(s, start);
1594 spin_unlock(&vb->lock);
1599 mutex_lock(&vmap_purge_lock);
1600 purge_fragmented_blocks_allcpus();
1601 if (!__purge_vmap_area_lazy(start, end) && flush)
1602 flush_tlb_kernel_range(start, end);
1603 mutex_unlock(&vmap_purge_lock);
1607 * vm_unmap_aliases - unmap outstanding lazy aliases in the vmap layer
1609 * The vmap/vmalloc layer lazily flushes kernel virtual mappings primarily
1610 * to amortize TLB flushing overheads. What this means is that any page you
1611 * have now, may, in a former life, have been mapped into kernel virtual
1612 * address by the vmap layer and so there might be some CPUs with TLB entries
1613 * still referencing that page (additional to the regular 1:1 kernel mapping).
1615 * vm_unmap_aliases flushes all such lazy mappings. After it returns, we can
1616 * be sure that none of the pages we have control over will have any aliases
1617 * from the vmap layer.
1619 void vm_unmap_aliases(void)
1621 unsigned long start = ULONG_MAX, end = 0;
1624 _vm_unmap_aliases(start, end, flush);
1626 EXPORT_SYMBOL_GPL(vm_unmap_aliases);
1629 * vm_unmap_ram - unmap linear kernel address space set up by vm_map_ram
1630 * @mem: the pointer returned by vm_map_ram
1631 * @count: the count passed to that vm_map_ram call (cannot unmap partial)
1633 void vm_unmap_ram(const void *mem, unsigned int count)
1635 unsigned long size = (unsigned long)count << PAGE_SHIFT;
1636 unsigned long addr = (unsigned long)mem;
1637 struct vmap_area *va;
1641 BUG_ON(addr < VMALLOC_START);
1642 BUG_ON(addr > VMALLOC_END);
1643 BUG_ON(!PAGE_ALIGNED(addr));
1645 if (likely(count <= VMAP_MAX_ALLOC)) {
1646 debug_check_no_locks_freed(mem, size);
1651 va = find_vmap_area(addr);
1653 debug_check_no_locks_freed((void *)va->va_start,
1654 (va->va_end - va->va_start));
1655 free_unmap_vmap_area(va);
1657 EXPORT_SYMBOL(vm_unmap_ram);
1660 * vm_map_ram - map pages linearly into kernel virtual address (vmalloc space)
1661 * @pages: an array of pointers to the pages to be mapped
1662 * @count: number of pages
1663 * @node: prefer to allocate data structures on this node
1664 * @prot: memory protection to use. PAGE_KERNEL for regular RAM
1666 * If you use this function for less than VMAP_MAX_ALLOC pages, it could be
1667 * faster than vmap so it's good. But if you mix long-life and short-life
1668 * objects with vm_map_ram(), it could consume lots of address space through
1669 * fragmentation (especially on a 32bit machine). You could see failures in
1670 * the end. Please use this function for short-lived objects.
1672 * Returns: a pointer to the address that has been mapped, or %NULL on failure
1674 void *vm_map_ram(struct page **pages, unsigned int count, int node, pgprot_t prot)
1676 unsigned long size = (unsigned long)count << PAGE_SHIFT;
1680 if (likely(count <= VMAP_MAX_ALLOC)) {
1681 mem = vb_alloc(size, GFP_KERNEL);
1684 addr = (unsigned long)mem;
1686 struct vmap_area *va;
1687 va = alloc_vmap_area(size, PAGE_SIZE,
1688 VMALLOC_START, VMALLOC_END, node, GFP_KERNEL);
1692 addr = va->va_start;
1695 if (vmap_page_range(addr, addr + size, prot, pages) < 0) {
1696 vm_unmap_ram(mem, count);
1701 EXPORT_SYMBOL(vm_map_ram);
1703 static struct vm_struct *vmlist __initdata;
1706 * vm_area_add_early - add vmap area early during boot
1707 * @vm: vm_struct to add
1709 * This function is used to add fixed kernel vm area to vmlist before
1710 * vmalloc_init() is called. @vm->addr, @vm->size, and @vm->flags
1711 * should contain proper values and the other fields should be zero.
1713 * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING.
1715 void __init vm_area_add_early(struct vm_struct *vm)
1717 struct vm_struct *tmp, **p;
1719 BUG_ON(vmap_initialized);
1720 for (p = &vmlist; (tmp = *p) != NULL; p = &tmp->next) {
1721 if (tmp->addr >= vm->addr) {
1722 BUG_ON(tmp->addr < vm->addr + vm->size);
1725 BUG_ON(tmp->addr + tmp->size > vm->addr);
1732 * vm_area_register_early - register vmap area early during boot
1733 * @vm: vm_struct to register
1734 * @align: requested alignment
1736 * This function is used to register kernel vm area before
1737 * vmalloc_init() is called. @vm->size and @vm->flags should contain
1738 * proper values on entry and other fields should be zero. On return,
1739 * vm->addr contains the allocated address.
1741 * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING.
1743 void __init vm_area_register_early(struct vm_struct *vm, size_t align)
1745 static size_t vm_init_off __initdata;
1748 addr = ALIGN(VMALLOC_START + vm_init_off, align);
1749 vm_init_off = PFN_ALIGN(addr + vm->size) - VMALLOC_START;
1751 vm->addr = (void *)addr;
1753 vm_area_add_early(vm);
1756 static void vmap_init_free_space(void)
1758 unsigned long vmap_start = 1;
1759 const unsigned long vmap_end = ULONG_MAX;
1760 struct vmap_area *busy, *free;
1764 * -|-----|.....|-----|-----|-----|.....|-
1766 * |<--------------------------------->|
1768 list_for_each_entry(busy, &vmap_area_list, list) {
1769 if (busy->va_start - vmap_start > 0) {
1770 free = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
1771 if (!WARN_ON_ONCE(!free)) {
1772 free->va_start = vmap_start;
1773 free->va_end = busy->va_start;
1775 insert_vmap_area_augment(free, NULL,
1776 &free_vmap_area_root,
1777 &free_vmap_area_list);
1781 vmap_start = busy->va_end;
1784 if (vmap_end - vmap_start > 0) {
1785 free = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
1786 if (!WARN_ON_ONCE(!free)) {
1787 free->va_start = vmap_start;
1788 free->va_end = vmap_end;
1790 insert_vmap_area_augment(free, NULL,
1791 &free_vmap_area_root,
1792 &free_vmap_area_list);
1797 void __init vmalloc_init(void)
1799 struct vmap_area *va;
1800 struct vm_struct *tmp;
1804 * Create the cache for vmap_area objects.
1806 vmap_area_cachep = KMEM_CACHE(vmap_area, SLAB_PANIC);
1808 for_each_possible_cpu(i) {
1809 struct vmap_block_queue *vbq;
1810 struct vfree_deferred *p;
1812 vbq = &per_cpu(vmap_block_queue, i);
1813 spin_lock_init(&vbq->lock);
1814 INIT_LIST_HEAD(&vbq->free);
1815 p = &per_cpu(vfree_deferred, i);
1816 init_llist_head(&p->list);
1817 INIT_WORK(&p->wq, free_work);
1820 /* Import existing vmlist entries. */
1821 for (tmp = vmlist; tmp; tmp = tmp->next) {
1822 va = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
1823 if (WARN_ON_ONCE(!va))
1826 va->flags = VM_VM_AREA;
1827 va->va_start = (unsigned long)tmp->addr;
1828 va->va_end = va->va_start + tmp->size;
1830 insert_vmap_area(va, &vmap_area_root, &vmap_area_list);
1834 * Now we can initialize a free vmap space.
1836 vmap_init_free_space();
1837 vmap_initialized = true;
1841 * map_kernel_range_noflush - map kernel VM area with the specified pages
1842 * @addr: start of the VM area to map
1843 * @size: size of the VM area to map
1844 * @prot: page protection flags to use
1845 * @pages: pages to map
1847 * Map PFN_UP(@size) pages at @addr. The VM area @addr and @size
1848 * specify should have been allocated using get_vm_area() and its
1852 * This function does NOT do any cache flushing. The caller is
1853 * responsible for calling flush_cache_vmap() on to-be-mapped areas
1854 * before calling this function.
1857 * The number of pages mapped on success, -errno on failure.
1859 int map_kernel_range_noflush(unsigned long addr, unsigned long size,
1860 pgprot_t prot, struct page **pages)
1862 return vmap_page_range_noflush(addr, addr + size, prot, pages);
1866 * unmap_kernel_range_noflush - unmap kernel VM area
1867 * @addr: start of the VM area to unmap
1868 * @size: size of the VM area to unmap
1870 * Unmap PFN_UP(@size) pages at @addr. The VM area @addr and @size
1871 * specify should have been allocated using get_vm_area() and its
1875 * This function does NOT do any cache flushing. The caller is
1876 * responsible for calling flush_cache_vunmap() on to-be-mapped areas
1877 * before calling this function and flush_tlb_kernel_range() after.
1879 void unmap_kernel_range_noflush(unsigned long addr, unsigned long size)
1881 vunmap_page_range(addr, addr + size);
1883 EXPORT_SYMBOL_GPL(unmap_kernel_range_noflush);
1886 * unmap_kernel_range - unmap kernel VM area and flush cache and TLB
1887 * @addr: start of the VM area to unmap
1888 * @size: size of the VM area to unmap
1890 * Similar to unmap_kernel_range_noflush() but flushes vcache before
1891 * the unmapping and tlb after.
1893 void unmap_kernel_range(unsigned long addr, unsigned long size)
1895 unsigned long end = addr + size;
1897 flush_cache_vunmap(addr, end);
1898 vunmap_page_range(addr, end);
1899 flush_tlb_kernel_range(addr, end);
1901 EXPORT_SYMBOL_GPL(unmap_kernel_range);
1903 int map_vm_area(struct vm_struct *area, pgprot_t prot, struct page **pages)
1905 unsigned long addr = (unsigned long)area->addr;
1906 unsigned long end = addr + get_vm_area_size(area);
1909 err = vmap_page_range(addr, end, prot, pages);
1911 return err > 0 ? 0 : err;
1913 EXPORT_SYMBOL_GPL(map_vm_area);
1915 static void setup_vmalloc_vm(struct vm_struct *vm, struct vmap_area *va,
1916 unsigned long flags, const void *caller)
1918 spin_lock(&vmap_area_lock);
1920 vm->addr = (void *)va->va_start;
1921 vm->size = va->va_end - va->va_start;
1922 vm->caller = caller;
1924 va->flags |= VM_VM_AREA;
1925 spin_unlock(&vmap_area_lock);
1928 static void clear_vm_uninitialized_flag(struct vm_struct *vm)
1931 * Before removing VM_UNINITIALIZED,
1932 * we should make sure that vm has proper values.
1933 * Pair with smp_rmb() in show_numa_info().
1936 vm->flags &= ~VM_UNINITIALIZED;
1939 static struct vm_struct *__get_vm_area_node(unsigned long size,
1940 unsigned long align, unsigned long flags, unsigned long start,
1941 unsigned long end, int node, gfp_t gfp_mask, const void *caller)
1943 struct vmap_area *va;
1944 struct vm_struct *area;
1946 BUG_ON(in_interrupt());
1947 size = PAGE_ALIGN(size);
1948 if (unlikely(!size))
1951 if (flags & VM_IOREMAP)
1952 align = 1ul << clamp_t(int, get_count_order_long(size),
1953 PAGE_SHIFT, IOREMAP_MAX_ORDER);
1955 area = kzalloc_node(sizeof(*area), gfp_mask & GFP_RECLAIM_MASK, node);
1956 if (unlikely(!area))
1959 if (!(flags & VM_NO_GUARD))
1962 va = alloc_vmap_area(size, align, start, end, node, gfp_mask);
1968 setup_vmalloc_vm(area, va, flags, caller);
1973 struct vm_struct *__get_vm_area(unsigned long size, unsigned long flags,
1974 unsigned long start, unsigned long end)
1976 return __get_vm_area_node(size, 1, flags, start, end, NUMA_NO_NODE,
1977 GFP_KERNEL, __builtin_return_address(0));
1979 EXPORT_SYMBOL_GPL(__get_vm_area);
1981 struct vm_struct *__get_vm_area_caller(unsigned long size, unsigned long flags,
1982 unsigned long start, unsigned long end,
1985 return __get_vm_area_node(size, 1, flags, start, end, NUMA_NO_NODE,
1986 GFP_KERNEL, caller);
1990 * get_vm_area - reserve a contiguous kernel virtual area
1991 * @size: size of the area
1992 * @flags: %VM_IOREMAP for I/O mappings or VM_ALLOC
1994 * Search an area of @size in the kernel virtual mapping area,
1995 * and reserved it for out purposes. Returns the area descriptor
1996 * on success or %NULL on failure.
1998 * Return: the area descriptor on success or %NULL on failure.
2000 struct vm_struct *get_vm_area(unsigned long size, unsigned long flags)
2002 return __get_vm_area_node(size, 1, flags, VMALLOC_START, VMALLOC_END,
2003 NUMA_NO_NODE, GFP_KERNEL,
2004 __builtin_return_address(0));
2007 struct vm_struct *get_vm_area_caller(unsigned long size, unsigned long flags,
2010 return __get_vm_area_node(size, 1, flags, VMALLOC_START, VMALLOC_END,
2011 NUMA_NO_NODE, GFP_KERNEL, caller);
2015 * find_vm_area - find a continuous kernel virtual area
2016 * @addr: base address
2018 * Search for the kernel VM area starting at @addr, and return it.
2019 * It is up to the caller to do all required locking to keep the returned
2022 * Return: pointer to the found area or %NULL on faulure
2024 struct vm_struct *find_vm_area(const void *addr)
2026 struct vmap_area *va;
2028 va = find_vmap_area((unsigned long)addr);
2029 if (va && va->flags & VM_VM_AREA)
2036 * remove_vm_area - find and remove a continuous kernel virtual area
2037 * @addr: base address
2039 * Search for the kernel VM area starting at @addr, and remove it.
2040 * This function returns the found VM area, but using it is NOT safe
2041 * on SMP machines, except for its size or flags.
2043 * Return: pointer to the found area or %NULL on faulure
2045 struct vm_struct *remove_vm_area(const void *addr)
2047 struct vmap_area *va;
2051 va = find_vmap_area((unsigned long)addr);
2052 if (va && va->flags & VM_VM_AREA) {
2053 struct vm_struct *vm = va->vm;
2055 spin_lock(&vmap_area_lock);
2057 va->flags &= ~VM_VM_AREA;
2058 va->flags |= VM_LAZY_FREE;
2059 spin_unlock(&vmap_area_lock);
2061 kasan_free_shadow(vm);
2062 free_unmap_vmap_area(va);
2069 static inline void set_area_direct_map(const struct vm_struct *area,
2070 int (*set_direct_map)(struct page *page))
2074 for (i = 0; i < area->nr_pages; i++)
2075 if (page_address(area->pages[i]))
2076 set_direct_map(area->pages[i]);
2079 /* Handle removing and resetting vm mappings related to the vm_struct. */
2080 static void vm_remove_mappings(struct vm_struct *area, int deallocate_pages)
2082 unsigned long addr = (unsigned long)area->addr;
2083 unsigned long start = ULONG_MAX, end = 0;
2084 int flush_reset = area->flags & VM_FLUSH_RESET_PERMS;
2088 * The below block can be removed when all architectures that have
2089 * direct map permissions also have set_direct_map_() implementations.
2090 * This is concerned with resetting the direct map any an vm alias with
2091 * execute permissions, without leaving a RW+X window.
2093 if (flush_reset && !IS_ENABLED(CONFIG_ARCH_HAS_SET_DIRECT_MAP)) {
2094 set_memory_nx(addr, area->nr_pages);
2095 set_memory_rw(addr, area->nr_pages);
2098 remove_vm_area(area->addr);
2100 /* If this is not VM_FLUSH_RESET_PERMS memory, no need for the below. */
2105 * If not deallocating pages, just do the flush of the VM area and
2108 if (!deallocate_pages) {
2114 * If execution gets here, flush the vm mapping and reset the direct
2115 * map. Find the start and end range of the direct mappings to make sure
2116 * the vm_unmap_aliases() flush includes the direct map.
2118 for (i = 0; i < area->nr_pages; i++) {
2119 if (page_address(area->pages[i])) {
2120 start = min(addr, start);
2121 end = max(addr, end);
2126 * Set direct map to something invalid so that it won't be cached if
2127 * there are any accesses after the TLB flush, then flush the TLB and
2128 * reset the direct map permissions to the default.
2130 set_area_direct_map(area, set_direct_map_invalid_noflush);
2131 _vm_unmap_aliases(start, end, 1);
2132 set_area_direct_map(area, set_direct_map_default_noflush);
2135 static void __vunmap(const void *addr, int deallocate_pages)
2137 struct vm_struct *area;
2142 if (WARN(!PAGE_ALIGNED(addr), "Trying to vfree() bad address (%p)\n",
2146 area = find_vm_area(addr);
2147 if (unlikely(!area)) {
2148 WARN(1, KERN_ERR "Trying to vfree() nonexistent vm area (%p)\n",
2153 debug_check_no_locks_freed(area->addr, get_vm_area_size(area));
2154 debug_check_no_obj_freed(area->addr, get_vm_area_size(area));
2156 vm_remove_mappings(area, deallocate_pages);
2158 if (deallocate_pages) {
2161 for (i = 0; i < area->nr_pages; i++) {
2162 struct page *page = area->pages[i];
2165 __free_pages(page, 0);
2168 kvfree(area->pages);
2175 static inline void __vfree_deferred(const void *addr)
2178 * Use raw_cpu_ptr() because this can be called from preemptible
2179 * context. Preemption is absolutely fine here, because the llist_add()
2180 * implementation is lockless, so it works even if we are adding to
2181 * nother cpu's list. schedule_work() should be fine with this too.
2183 struct vfree_deferred *p = raw_cpu_ptr(&vfree_deferred);
2185 if (llist_add((struct llist_node *)addr, &p->list))
2186 schedule_work(&p->wq);
2190 * vfree_atomic - release memory allocated by vmalloc()
2191 * @addr: memory base address
2193 * This one is just like vfree() but can be called in any atomic context
2196 void vfree_atomic(const void *addr)
2200 kmemleak_free(addr);
2204 __vfree_deferred(addr);
2207 static void __vfree(const void *addr)
2209 if (unlikely(in_interrupt()))
2210 __vfree_deferred(addr);
2216 * vfree - release memory allocated by vmalloc()
2217 * @addr: memory base address
2219 * Free the virtually continuous memory area starting at @addr, as
2220 * obtained from vmalloc(), vmalloc_32() or __vmalloc(). If @addr is
2221 * NULL, no operation is performed.
2223 * Must not be called in NMI context (strictly speaking, only if we don't
2224 * have CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG, but making the calling
2225 * conventions for vfree() arch-depenedent would be a really bad idea)
2227 * May sleep if called *not* from interrupt context.
2229 * NOTE: assumes that the object at @addr has a size >= sizeof(llist_node)
2231 void vfree(const void *addr)
2235 kmemleak_free(addr);
2237 might_sleep_if(!in_interrupt());
2244 EXPORT_SYMBOL(vfree);
2247 * vunmap - release virtual mapping obtained by vmap()
2248 * @addr: memory base address
2250 * Free the virtually contiguous memory area starting at @addr,
2251 * which was created from the page array passed to vmap().
2253 * Must not be called in interrupt context.
2255 void vunmap(const void *addr)
2257 BUG_ON(in_interrupt());
2262 EXPORT_SYMBOL(vunmap);
2265 * vmap - map an array of pages into virtually contiguous space
2266 * @pages: array of page pointers
2267 * @count: number of pages to map
2268 * @flags: vm_area->flags
2269 * @prot: page protection for the mapping
2271 * Maps @count pages from @pages into contiguous kernel virtual
2274 * Return: the address of the area or %NULL on failure
2276 void *vmap(struct page **pages, unsigned int count,
2277 unsigned long flags, pgprot_t prot)
2279 struct vm_struct *area;
2280 unsigned long size; /* In bytes */
2284 if (count > totalram_pages())
2287 size = (unsigned long)count << PAGE_SHIFT;
2288 area = get_vm_area_caller(size, flags, __builtin_return_address(0));
2292 if (map_vm_area(area, prot, pages)) {
2299 EXPORT_SYMBOL(vmap);
2301 static void *__vmalloc_node(unsigned long size, unsigned long align,
2302 gfp_t gfp_mask, pgprot_t prot,
2303 int node, const void *caller);
2304 static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask,
2305 pgprot_t prot, int node)
2307 struct page **pages;
2308 unsigned int nr_pages, array_size, i;
2309 const gfp_t nested_gfp = (gfp_mask & GFP_RECLAIM_MASK) | __GFP_ZERO;
2310 const gfp_t alloc_mask = gfp_mask | __GFP_NOWARN;
2311 const gfp_t highmem_mask = (gfp_mask & (GFP_DMA | GFP_DMA32)) ?
2315 nr_pages = get_vm_area_size(area) >> PAGE_SHIFT;
2316 array_size = (nr_pages * sizeof(struct page *));
2318 area->nr_pages = nr_pages;
2319 /* Please note that the recursion is strictly bounded. */
2320 if (array_size > PAGE_SIZE) {
2321 pages = __vmalloc_node(array_size, 1, nested_gfp|highmem_mask,
2322 PAGE_KERNEL, node, area->caller);
2324 pages = kmalloc_node(array_size, nested_gfp, node);
2326 area->pages = pages;
2328 remove_vm_area(area->addr);
2333 for (i = 0; i < area->nr_pages; i++) {
2336 if (node == NUMA_NO_NODE)
2337 page = alloc_page(alloc_mask|highmem_mask);
2339 page = alloc_pages_node(node, alloc_mask|highmem_mask, 0);
2341 if (unlikely(!page)) {
2342 /* Successfully allocated i pages, free them in __vunmap() */
2346 area->pages[i] = page;
2347 if (gfpflags_allow_blocking(gfp_mask|highmem_mask))
2351 if (map_vm_area(area, prot, pages))
2356 warn_alloc(gfp_mask, NULL,
2357 "vmalloc: allocation failure, allocated %ld of %ld bytes",
2358 (area->nr_pages*PAGE_SIZE), area->size);
2359 __vfree(area->addr);
2364 * __vmalloc_node_range - allocate virtually contiguous memory
2365 * @size: allocation size
2366 * @align: desired alignment
2367 * @start: vm area range start
2368 * @end: vm area range end
2369 * @gfp_mask: flags for the page level allocator
2370 * @prot: protection mask for the allocated pages
2371 * @vm_flags: additional vm area flags (e.g. %VM_NO_GUARD)
2372 * @node: node to use for allocation or NUMA_NO_NODE
2373 * @caller: caller's return address
2375 * Allocate enough pages to cover @size from the page level
2376 * allocator with @gfp_mask flags. Map them into contiguous
2377 * kernel virtual space, using a pagetable protection of @prot.
2379 * Return: the address of the area or %NULL on failure
2381 void *__vmalloc_node_range(unsigned long size, unsigned long align,
2382 unsigned long start, unsigned long end, gfp_t gfp_mask,
2383 pgprot_t prot, unsigned long vm_flags, int node,
2386 struct vm_struct *area;
2388 unsigned long real_size = size;
2390 size = PAGE_ALIGN(size);
2391 if (!size || (size >> PAGE_SHIFT) > totalram_pages())
2394 area = __get_vm_area_node(size, align, VM_ALLOC | VM_UNINITIALIZED |
2395 vm_flags, start, end, node, gfp_mask, caller);
2399 addr = __vmalloc_area_node(area, gfp_mask, prot, node);
2404 * In this function, newly allocated vm_struct has VM_UNINITIALIZED
2405 * flag. It means that vm_struct is not fully initialized.
2406 * Now, it is fully initialized, so remove this flag here.
2408 clear_vm_uninitialized_flag(area);
2410 kmemleak_vmalloc(area, size, gfp_mask);
2415 warn_alloc(gfp_mask, NULL,
2416 "vmalloc: allocation failure: %lu bytes", real_size);
2421 * This is only for performance analysis of vmalloc and stress purpose.
2422 * It is required by vmalloc test module, therefore do not use it other
2425 #ifdef CONFIG_TEST_VMALLOC_MODULE
2426 EXPORT_SYMBOL_GPL(__vmalloc_node_range);
2430 * __vmalloc_node - allocate virtually contiguous memory
2431 * @size: allocation size
2432 * @align: desired alignment
2433 * @gfp_mask: flags for the page level allocator
2434 * @prot: protection mask for the allocated pages
2435 * @node: node to use for allocation or NUMA_NO_NODE
2436 * @caller: caller's return address
2438 * Allocate enough pages to cover @size from the page level
2439 * allocator with @gfp_mask flags. Map them into contiguous
2440 * kernel virtual space, using a pagetable protection of @prot.
2442 * Reclaim modifiers in @gfp_mask - __GFP_NORETRY, __GFP_RETRY_MAYFAIL
2443 * and __GFP_NOFAIL are not supported
2445 * Any use of gfp flags outside of GFP_KERNEL should be consulted
2448 * Return: pointer to the allocated memory or %NULL on error
2450 static void *__vmalloc_node(unsigned long size, unsigned long align,
2451 gfp_t gfp_mask, pgprot_t prot,
2452 int node, const void *caller)
2454 return __vmalloc_node_range(size, align, VMALLOC_START, VMALLOC_END,
2455 gfp_mask, prot, 0, node, caller);
2458 void *__vmalloc(unsigned long size, gfp_t gfp_mask, pgprot_t prot)
2460 return __vmalloc_node(size, 1, gfp_mask, prot, NUMA_NO_NODE,
2461 __builtin_return_address(0));
2463 EXPORT_SYMBOL(__vmalloc);
2465 static inline void *__vmalloc_node_flags(unsigned long size,
2466 int node, gfp_t flags)
2468 return __vmalloc_node(size, 1, flags, PAGE_KERNEL,
2469 node, __builtin_return_address(0));
2473 void *__vmalloc_node_flags_caller(unsigned long size, int node, gfp_t flags,
2476 return __vmalloc_node(size, 1, flags, PAGE_KERNEL, node, caller);
2480 * vmalloc - allocate virtually contiguous memory
2481 * @size: allocation size
2483 * Allocate enough pages to cover @size from the page level
2484 * allocator and map them into contiguous kernel virtual space.
2486 * For tight control over page level allocator and protection flags
2487 * use __vmalloc() instead.
2489 * Return: pointer to the allocated memory or %NULL on error
2491 void *vmalloc(unsigned long size)
2493 return __vmalloc_node_flags(size, NUMA_NO_NODE,
2496 EXPORT_SYMBOL(vmalloc);
2499 * vzalloc - allocate virtually contiguous memory with zero fill
2500 * @size: allocation size
2502 * Allocate enough pages to cover @size from the page level
2503 * allocator and map them into contiguous kernel virtual space.
2504 * The memory allocated is set to zero.
2506 * For tight control over page level allocator and protection flags
2507 * use __vmalloc() instead.
2509 * Return: pointer to the allocated memory or %NULL on error
2511 void *vzalloc(unsigned long size)
2513 return __vmalloc_node_flags(size, NUMA_NO_NODE,
2514 GFP_KERNEL | __GFP_ZERO);
2516 EXPORT_SYMBOL(vzalloc);
2519 * vmalloc_user - allocate zeroed virtually contiguous memory for userspace
2520 * @size: allocation size
2522 * The resulting memory area is zeroed so it can be mapped to userspace
2523 * without leaking data.
2525 * Return: pointer to the allocated memory or %NULL on error
2527 void *vmalloc_user(unsigned long size)
2529 return __vmalloc_node_range(size, SHMLBA, VMALLOC_START, VMALLOC_END,
2530 GFP_KERNEL | __GFP_ZERO, PAGE_KERNEL,
2531 VM_USERMAP, NUMA_NO_NODE,
2532 __builtin_return_address(0));
2534 EXPORT_SYMBOL(vmalloc_user);
2537 * vmalloc_node - allocate memory on a specific node
2538 * @size: allocation size
2541 * Allocate enough pages to cover @size from the page level
2542 * allocator and map them into contiguous kernel virtual space.
2544 * For tight control over page level allocator and protection flags
2545 * use __vmalloc() instead.
2547 * Return: pointer to the allocated memory or %NULL on error
2549 void *vmalloc_node(unsigned long size, int node)
2551 return __vmalloc_node(size, 1, GFP_KERNEL, PAGE_KERNEL,
2552 node, __builtin_return_address(0));
2554 EXPORT_SYMBOL(vmalloc_node);
2557 * vzalloc_node - allocate memory on a specific node with zero fill
2558 * @size: allocation size
2561 * Allocate enough pages to cover @size from the page level
2562 * allocator and map them into contiguous kernel virtual space.
2563 * The memory allocated is set to zero.
2565 * For tight control over page level allocator and protection flags
2566 * use __vmalloc_node() instead.
2568 * Return: pointer to the allocated memory or %NULL on error
2570 void *vzalloc_node(unsigned long size, int node)
2572 return __vmalloc_node_flags(size, node,
2573 GFP_KERNEL | __GFP_ZERO);
2575 EXPORT_SYMBOL(vzalloc_node);
2578 * vmalloc_exec - allocate virtually contiguous, executable memory
2579 * @size: allocation size
2581 * Kernel-internal function to allocate enough pages to cover @size
2582 * the page level allocator and map them into contiguous and
2583 * executable kernel virtual space.
2585 * For tight control over page level allocator and protection flags
2586 * use __vmalloc() instead.
2588 * Return: pointer to the allocated memory or %NULL on error
2590 void *vmalloc_exec(unsigned long size)
2592 return __vmalloc_node_range(size, 1, VMALLOC_START, VMALLOC_END,
2593 GFP_KERNEL, PAGE_KERNEL_EXEC, VM_FLUSH_RESET_PERMS,
2594 NUMA_NO_NODE, __builtin_return_address(0));
2597 #if defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA32)
2598 #define GFP_VMALLOC32 (GFP_DMA32 | GFP_KERNEL)
2599 #elif defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA)
2600 #define GFP_VMALLOC32 (GFP_DMA | GFP_KERNEL)
2603 * 64b systems should always have either DMA or DMA32 zones. For others
2604 * GFP_DMA32 should do the right thing and use the normal zone.
2606 #define GFP_VMALLOC32 GFP_DMA32 | GFP_KERNEL
2610 * vmalloc_32 - allocate virtually contiguous memory (32bit addressable)
2611 * @size: allocation size
2613 * Allocate enough 32bit PA addressable pages to cover @size from the
2614 * page level allocator and map them into contiguous kernel virtual space.
2616 * Return: pointer to the allocated memory or %NULL on error
2618 void *vmalloc_32(unsigned long size)
2620 return __vmalloc_node(size, 1, GFP_VMALLOC32, PAGE_KERNEL,
2621 NUMA_NO_NODE, __builtin_return_address(0));
2623 EXPORT_SYMBOL(vmalloc_32);
2626 * vmalloc_32_user - allocate zeroed virtually contiguous 32bit memory
2627 * @size: allocation size
2629 * The resulting memory area is 32bit addressable and zeroed so it can be
2630 * mapped to userspace without leaking data.
2632 * Return: pointer to the allocated memory or %NULL on error
2634 void *vmalloc_32_user(unsigned long size)
2636 return __vmalloc_node_range(size, SHMLBA, VMALLOC_START, VMALLOC_END,
2637 GFP_VMALLOC32 | __GFP_ZERO, PAGE_KERNEL,
2638 VM_USERMAP, NUMA_NO_NODE,
2639 __builtin_return_address(0));
2641 EXPORT_SYMBOL(vmalloc_32_user);
2644 * small helper routine , copy contents to buf from addr.
2645 * If the page is not present, fill zero.
2648 static int aligned_vread(char *buf, char *addr, unsigned long count)
2654 unsigned long offset, length;
2656 offset = offset_in_page(addr);
2657 length = PAGE_SIZE - offset;
2660 p = vmalloc_to_page(addr);
2662 * To do safe access to this _mapped_ area, we need
2663 * lock. But adding lock here means that we need to add
2664 * overhead of vmalloc()/vfree() calles for this _debug_
2665 * interface, rarely used. Instead of that, we'll use
2666 * kmap() and get small overhead in this access function.
2670 * we can expect USER0 is not used (see vread/vwrite's
2671 * function description)
2673 void *map = kmap_atomic(p);
2674 memcpy(buf, map + offset, length);
2677 memset(buf, 0, length);
2687 static int aligned_vwrite(char *buf, char *addr, unsigned long count)
2693 unsigned long offset, length;
2695 offset = offset_in_page(addr);
2696 length = PAGE_SIZE - offset;
2699 p = vmalloc_to_page(addr);
2701 * To do safe access to this _mapped_ area, we need
2702 * lock. But adding lock here means that we need to add
2703 * overhead of vmalloc()/vfree() calles for this _debug_
2704 * interface, rarely used. Instead of that, we'll use
2705 * kmap() and get small overhead in this access function.
2709 * we can expect USER0 is not used (see vread/vwrite's
2710 * function description)
2712 void *map = kmap_atomic(p);
2713 memcpy(map + offset, buf, length);
2725 * vread() - read vmalloc area in a safe way.
2726 * @buf: buffer for reading data
2727 * @addr: vm address.
2728 * @count: number of bytes to be read.
2730 * This function checks that addr is a valid vmalloc'ed area, and
2731 * copy data from that area to a given buffer. If the given memory range
2732 * of [addr...addr+count) includes some valid address, data is copied to
2733 * proper area of @buf. If there are memory holes, they'll be zero-filled.
2734 * IOREMAP area is treated as memory hole and no copy is done.
2736 * If [addr...addr+count) doesn't includes any intersects with alive
2737 * vm_struct area, returns 0. @buf should be kernel's buffer.
2739 * Note: In usual ops, vread() is never necessary because the caller
2740 * should know vmalloc() area is valid and can use memcpy().
2741 * This is for routines which have to access vmalloc area without
2742 * any informaion, as /dev/kmem.
2744 * Return: number of bytes for which addr and buf should be increased
2745 * (same number as @count) or %0 if [addr...addr+count) doesn't
2746 * include any intersection with valid vmalloc area
2748 long vread(char *buf, char *addr, unsigned long count)
2750 struct vmap_area *va;
2751 struct vm_struct *vm;
2752 char *vaddr, *buf_start = buf;
2753 unsigned long buflen = count;
2756 /* Don't allow overflow */
2757 if ((unsigned long) addr + count < count)
2758 count = -(unsigned long) addr;
2760 spin_lock(&vmap_area_lock);
2761 list_for_each_entry(va, &vmap_area_list, list) {
2765 if (!(va->flags & VM_VM_AREA))
2769 vaddr = (char *) vm->addr;
2770 if (addr >= vaddr + get_vm_area_size(vm))
2772 while (addr < vaddr) {
2780 n = vaddr + get_vm_area_size(vm) - addr;
2783 if (!(vm->flags & VM_IOREMAP))
2784 aligned_vread(buf, addr, n);
2785 else /* IOREMAP area is treated as memory hole */
2792 spin_unlock(&vmap_area_lock);
2794 if (buf == buf_start)
2796 /* zero-fill memory holes */
2797 if (buf != buf_start + buflen)
2798 memset(buf, 0, buflen - (buf - buf_start));
2804 * vwrite() - write vmalloc area in a safe way.
2805 * @buf: buffer for source data
2806 * @addr: vm address.
2807 * @count: number of bytes to be read.
2809 * This function checks that addr is a valid vmalloc'ed area, and
2810 * copy data from a buffer to the given addr. If specified range of
2811 * [addr...addr+count) includes some valid address, data is copied from
2812 * proper area of @buf. If there are memory holes, no copy to hole.
2813 * IOREMAP area is treated as memory hole and no copy is done.
2815 * If [addr...addr+count) doesn't includes any intersects with alive
2816 * vm_struct area, returns 0. @buf should be kernel's buffer.
2818 * Note: In usual ops, vwrite() is never necessary because the caller
2819 * should know vmalloc() area is valid and can use memcpy().
2820 * This is for routines which have to access vmalloc area without
2821 * any informaion, as /dev/kmem.
2823 * Return: number of bytes for which addr and buf should be
2824 * increased (same number as @count) or %0 if [addr...addr+count)
2825 * doesn't include any intersection with valid vmalloc area
2827 long vwrite(char *buf, char *addr, unsigned long count)
2829 struct vmap_area *va;
2830 struct vm_struct *vm;
2832 unsigned long n, buflen;
2835 /* Don't allow overflow */
2836 if ((unsigned long) addr + count < count)
2837 count = -(unsigned long) addr;
2840 spin_lock(&vmap_area_lock);
2841 list_for_each_entry(va, &vmap_area_list, list) {
2845 if (!(va->flags & VM_VM_AREA))
2849 vaddr = (char *) vm->addr;
2850 if (addr >= vaddr + get_vm_area_size(vm))
2852 while (addr < vaddr) {
2859 n = vaddr + get_vm_area_size(vm) - addr;
2862 if (!(vm->flags & VM_IOREMAP)) {
2863 aligned_vwrite(buf, addr, n);
2871 spin_unlock(&vmap_area_lock);
2878 * remap_vmalloc_range_partial - map vmalloc pages to userspace
2879 * @vma: vma to cover
2880 * @uaddr: target user address to start at
2881 * @kaddr: virtual address of vmalloc kernel memory
2882 * @size: size of map area
2884 * Returns: 0 for success, -Exxx on failure
2886 * This function checks that @kaddr is a valid vmalloc'ed area,
2887 * and that it is big enough to cover the range starting at
2888 * @uaddr in @vma. Will return failure if that criteria isn't
2891 * Similar to remap_pfn_range() (see mm/memory.c)
2893 int remap_vmalloc_range_partial(struct vm_area_struct *vma, unsigned long uaddr,
2894 void *kaddr, unsigned long size)
2896 struct vm_struct *area;
2898 size = PAGE_ALIGN(size);
2900 if (!PAGE_ALIGNED(uaddr) || !PAGE_ALIGNED(kaddr))
2903 area = find_vm_area(kaddr);
2907 if (!(area->flags & VM_USERMAP))
2910 if (kaddr + size > area->addr + get_vm_area_size(area))
2914 struct page *page = vmalloc_to_page(kaddr);
2917 ret = vm_insert_page(vma, uaddr, page);
2926 vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
2930 EXPORT_SYMBOL(remap_vmalloc_range_partial);
2933 * remap_vmalloc_range - map vmalloc pages to userspace
2934 * @vma: vma to cover (map full range of vma)
2935 * @addr: vmalloc memory
2936 * @pgoff: number of pages into addr before first page to map
2938 * Returns: 0 for success, -Exxx on failure
2940 * This function checks that addr is a valid vmalloc'ed area, and
2941 * that it is big enough to cover the vma. Will return failure if
2942 * that criteria isn't met.
2944 * Similar to remap_pfn_range() (see mm/memory.c)
2946 int remap_vmalloc_range(struct vm_area_struct *vma, void *addr,
2947 unsigned long pgoff)
2949 return remap_vmalloc_range_partial(vma, vma->vm_start,
2950 addr + (pgoff << PAGE_SHIFT),
2951 vma->vm_end - vma->vm_start);
2953 EXPORT_SYMBOL(remap_vmalloc_range);
2956 * Implement a stub for vmalloc_sync_all() if the architecture chose not to
2959 void __weak vmalloc_sync_all(void)
2964 static int f(pte_t *pte, pgtable_t table, unsigned long addr, void *data)
2976 * alloc_vm_area - allocate a range of kernel address space
2977 * @size: size of the area
2978 * @ptes: returns the PTEs for the address space
2980 * Returns: NULL on failure, vm_struct on success
2982 * This function reserves a range of kernel address space, and
2983 * allocates pagetables to map that range. No actual mappings
2986 * If @ptes is non-NULL, pointers to the PTEs (in init_mm)
2987 * allocated for the VM area are returned.
2989 struct vm_struct *alloc_vm_area(size_t size, pte_t **ptes)
2991 struct vm_struct *area;
2993 area = get_vm_area_caller(size, VM_IOREMAP,
2994 __builtin_return_address(0));
2999 * This ensures that page tables are constructed for this region
3000 * of kernel virtual address space and mapped into init_mm.
3002 if (apply_to_page_range(&init_mm, (unsigned long)area->addr,
3003 size, f, ptes ? &ptes : NULL)) {
3010 EXPORT_SYMBOL_GPL(alloc_vm_area);
3012 void free_vm_area(struct vm_struct *area)
3014 struct vm_struct *ret;
3015 ret = remove_vm_area(area->addr);
3016 BUG_ON(ret != area);
3019 EXPORT_SYMBOL_GPL(free_vm_area);
3022 static struct vmap_area *node_to_va(struct rb_node *n)
3024 return rb_entry_safe(n, struct vmap_area, rb_node);
3028 * pvm_find_va_enclose_addr - find the vmap_area @addr belongs to
3029 * @addr: target address
3031 * Returns: vmap_area if it is found. If there is no such area
3032 * the first highest(reverse order) vmap_area is returned
3033 * i.e. va->va_start < addr && va->va_end < addr or NULL
3034 * if there are no any areas before @addr.
3036 static struct vmap_area *
3037 pvm_find_va_enclose_addr(unsigned long addr)
3039 struct vmap_area *va, *tmp;
3042 n = free_vmap_area_root.rb_node;
3046 tmp = rb_entry(n, struct vmap_area, rb_node);
3047 if (tmp->va_start <= addr) {
3049 if (tmp->va_end >= addr)
3062 * pvm_determine_end_from_reverse - find the highest aligned address
3063 * of free block below VMALLOC_END
3065 * in - the VA we start the search(reverse order);
3066 * out - the VA with the highest aligned end address.
3068 * Returns: determined end address within vmap_area
3070 static unsigned long
3071 pvm_determine_end_from_reverse(struct vmap_area **va, unsigned long align)
3073 unsigned long vmalloc_end = VMALLOC_END & ~(align - 1);
3077 list_for_each_entry_from_reverse((*va),
3078 &free_vmap_area_list, list) {
3079 addr = min((*va)->va_end & ~(align - 1), vmalloc_end);
3080 if ((*va)->va_start < addr)
3089 * pcpu_get_vm_areas - allocate vmalloc areas for percpu allocator
3090 * @offsets: array containing offset of each area
3091 * @sizes: array containing size of each area
3092 * @nr_vms: the number of areas to allocate
3093 * @align: alignment, all entries in @offsets and @sizes must be aligned to this
3095 * Returns: kmalloc'd vm_struct pointer array pointing to allocated
3096 * vm_structs on success, %NULL on failure
3098 * Percpu allocator wants to use congruent vm areas so that it can
3099 * maintain the offsets among percpu areas. This function allocates
3100 * congruent vmalloc areas for it with GFP_KERNEL. These areas tend to
3101 * be scattered pretty far, distance between two areas easily going up
3102 * to gigabytes. To avoid interacting with regular vmallocs, these
3103 * areas are allocated from top.
3105 * Despite its complicated look, this allocator is rather simple. It
3106 * does everything top-down and scans free blocks from the end looking
3107 * for matching base. While scanning, if any of the areas do not fit the
3108 * base address is pulled down to fit the area. Scanning is repeated till
3109 * all the areas fit and then all necessary data structures are inserted
3110 * and the result is returned.
3112 struct vm_struct **pcpu_get_vm_areas(const unsigned long *offsets,
3113 const size_t *sizes, int nr_vms,
3116 const unsigned long vmalloc_start = ALIGN(VMALLOC_START, align);
3117 const unsigned long vmalloc_end = VMALLOC_END & ~(align - 1);
3118 struct vmap_area **vas, *va;
3119 struct vm_struct **vms;
3120 int area, area2, last_area, term_area;
3121 unsigned long base, start, size, end, last_end;
3122 bool purged = false;
3125 /* verify parameters and allocate data structures */
3126 BUG_ON(offset_in_page(align) || !is_power_of_2(align));
3127 for (last_area = 0, area = 0; area < nr_vms; area++) {
3128 start = offsets[area];
3129 end = start + sizes[area];
3131 /* is everything aligned properly? */
3132 BUG_ON(!IS_ALIGNED(offsets[area], align));
3133 BUG_ON(!IS_ALIGNED(sizes[area], align));
3135 /* detect the area with the highest address */
3136 if (start > offsets[last_area])
3139 for (area2 = area + 1; area2 < nr_vms; area2++) {
3140 unsigned long start2 = offsets[area2];
3141 unsigned long end2 = start2 + sizes[area2];
3143 BUG_ON(start2 < end && start < end2);
3146 last_end = offsets[last_area] + sizes[last_area];
3148 if (vmalloc_end - vmalloc_start < last_end) {
3153 vms = kcalloc(nr_vms, sizeof(vms[0]), GFP_KERNEL);
3154 vas = kcalloc(nr_vms, sizeof(vas[0]), GFP_KERNEL);
3158 for (area = 0; area < nr_vms; area++) {
3159 vas[area] = kmem_cache_zalloc(vmap_area_cachep, GFP_KERNEL);
3160 vms[area] = kzalloc(sizeof(struct vm_struct), GFP_KERNEL);
3161 if (!vas[area] || !vms[area])
3165 spin_lock(&vmap_area_lock);
3167 /* start scanning - we scan from the top, begin with the last area */
3168 area = term_area = last_area;
3169 start = offsets[area];
3170 end = start + sizes[area];
3172 va = pvm_find_va_enclose_addr(vmalloc_end);
3173 base = pvm_determine_end_from_reverse(&va, align) - end;
3177 * base might have underflowed, add last_end before
3180 if (base + last_end < vmalloc_start + last_end)
3184 * Fitting base has not been found.
3190 * If this VA does not fit, move base downwards and recheck.
3192 if (base + start < va->va_start || base + end > va->va_end) {
3193 va = node_to_va(rb_prev(&va->rb_node));
3194 base = pvm_determine_end_from_reverse(&va, align) - end;
3200 * This area fits, move on to the previous one. If
3201 * the previous one is the terminal one, we're done.
3203 area = (area + nr_vms - 1) % nr_vms;
3204 if (area == term_area)
3207 start = offsets[area];
3208 end = start + sizes[area];
3209 va = pvm_find_va_enclose_addr(base + end);
3212 /* we've found a fitting base, insert all va's */
3213 for (area = 0; area < nr_vms; area++) {
3216 start = base + offsets[area];
3219 va = pvm_find_va_enclose_addr(start);
3220 if (WARN_ON_ONCE(va == NULL))
3221 /* It is a BUG(), but trigger recovery instead. */
3224 type = classify_va_fit_type(va, start, size);
3225 if (WARN_ON_ONCE(type == NOTHING_FIT))
3226 /* It is a BUG(), but trigger recovery instead. */
3229 ret = adjust_va_to_fit_type(va, start, size, type);
3233 /* Allocated area. */
3235 va->va_start = start;
3236 va->va_end = start + size;
3238 insert_vmap_area(va, &vmap_area_root, &vmap_area_list);
3241 spin_unlock(&vmap_area_lock);
3243 /* insert all vm's */
3244 for (area = 0; area < nr_vms; area++)
3245 setup_vmalloc_vm(vms[area], vas[area], VM_ALLOC,
3252 /* Remove previously inserted areas. */
3254 __free_vmap_area(vas[area]);
3259 spin_unlock(&vmap_area_lock);
3261 purge_vmap_area_lazy();
3264 /* Before "retry", check if we recover. */
3265 for (area = 0; area < nr_vms; area++) {
3269 vas[area] = kmem_cache_zalloc(
3270 vmap_area_cachep, GFP_KERNEL);
3279 for (area = 0; area < nr_vms; area++) {
3281 kmem_cache_free(vmap_area_cachep, vas[area]);
3292 * pcpu_free_vm_areas - free vmalloc areas for percpu allocator
3293 * @vms: vm_struct pointer array returned by pcpu_get_vm_areas()
3294 * @nr_vms: the number of allocated areas
3296 * Free vm_structs and the array allocated by pcpu_get_vm_areas().
3298 void pcpu_free_vm_areas(struct vm_struct **vms, int nr_vms)
3302 for (i = 0; i < nr_vms; i++)
3303 free_vm_area(vms[i]);
3306 #endif /* CONFIG_SMP */
3308 #ifdef CONFIG_PROC_FS
3309 static void *s_start(struct seq_file *m, loff_t *pos)
3310 __acquires(&vmap_area_lock)
3312 spin_lock(&vmap_area_lock);
3313 return seq_list_start(&vmap_area_list, *pos);
3316 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
3318 return seq_list_next(p, &vmap_area_list, pos);
3321 static void s_stop(struct seq_file *m, void *p)
3322 __releases(&vmap_area_lock)
3324 spin_unlock(&vmap_area_lock);
3327 static void show_numa_info(struct seq_file *m, struct vm_struct *v)
3329 if (IS_ENABLED(CONFIG_NUMA)) {
3330 unsigned int nr, *counters = m->private;
3335 if (v->flags & VM_UNINITIALIZED)
3337 /* Pair with smp_wmb() in clear_vm_uninitialized_flag() */
3340 memset(counters, 0, nr_node_ids * sizeof(unsigned int));
3342 for (nr = 0; nr < v->nr_pages; nr++)
3343 counters[page_to_nid(v->pages[nr])]++;
3345 for_each_node_state(nr, N_HIGH_MEMORY)
3347 seq_printf(m, " N%u=%u", nr, counters[nr]);
3351 static int s_show(struct seq_file *m, void *p)
3353 struct vmap_area *va;
3354 struct vm_struct *v;
3356 va = list_entry(p, struct vmap_area, list);
3359 * s_show can encounter race with remove_vm_area, !VM_VM_AREA on
3360 * behalf of vmap area is being tear down or vm_map_ram allocation.
3362 if (!(va->flags & VM_VM_AREA)) {
3363 seq_printf(m, "0x%pK-0x%pK %7ld %s\n",
3364 (void *)va->va_start, (void *)va->va_end,
3365 va->va_end - va->va_start,
3366 va->flags & VM_LAZY_FREE ? "unpurged vm_area" : "vm_map_ram");
3373 seq_printf(m, "0x%pK-0x%pK %7ld",
3374 v->addr, v->addr + v->size, v->size);
3377 seq_printf(m, " %pS", v->caller);
3380 seq_printf(m, " pages=%d", v->nr_pages);
3383 seq_printf(m, " phys=%pa", &v->phys_addr);
3385 if (v->flags & VM_IOREMAP)
3386 seq_puts(m, " ioremap");
3388 if (v->flags & VM_ALLOC)
3389 seq_puts(m, " vmalloc");
3391 if (v->flags & VM_MAP)
3392 seq_puts(m, " vmap");
3394 if (v->flags & VM_USERMAP)
3395 seq_puts(m, " user");
3397 if (is_vmalloc_addr(v->pages))
3398 seq_puts(m, " vpages");
3400 show_numa_info(m, v);
3405 static const struct seq_operations vmalloc_op = {
3412 static int __init proc_vmalloc_init(void)
3414 if (IS_ENABLED(CONFIG_NUMA))
3415 proc_create_seq_private("vmallocinfo", 0400, NULL,
3417 nr_node_ids * sizeof(unsigned int), NULL);
3419 proc_create_seq("vmallocinfo", 0400, NULL, &vmalloc_op);
3422 module_init(proc_vmalloc_init);