4 * Copyright (C) 1993 Linus Torvalds
5 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
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 VM_LAZY_FREE 0x02
329 #define VM_VM_AREA 0x04
331 static DEFINE_SPINLOCK(vmap_area_lock);
332 /* Export for kexec only */
333 LIST_HEAD(vmap_area_list);
334 static LLIST_HEAD(vmap_purge_list);
335 static struct rb_root vmap_area_root = RB_ROOT;
336 static bool vmap_initialized __read_mostly;
339 * This kmem_cache is used for vmap_area objects. Instead of
340 * allocating from slab we reuse an object from this cache to
341 * make things faster. Especially in "no edge" splitting of
344 static struct kmem_cache *vmap_area_cachep;
347 * This linked list is used in pair with free_vmap_area_root.
348 * It gives O(1) access to prev/next to perform fast coalescing.
350 static LIST_HEAD(free_vmap_area_list);
353 * This augment red-black tree represents the free vmap space.
354 * All vmap_area objects in this tree are sorted by va->va_start
355 * address. It is used for allocation and merging when a vmap
356 * object is released.
358 * Each vmap_area node contains a maximum available free block
359 * of its sub-tree, right or left. Therefore it is possible to
360 * find a lowest match of free area.
362 static struct rb_root free_vmap_area_root = RB_ROOT;
364 static __always_inline unsigned long
365 va_size(struct vmap_area *va)
367 return (va->va_end - va->va_start);
370 static __always_inline unsigned long
371 get_subtree_max_size(struct rb_node *node)
373 struct vmap_area *va;
375 va = rb_entry_safe(node, struct vmap_area, rb_node);
376 return va ? va->subtree_max_size : 0;
380 * Gets called when remove the node and rotate.
382 static __always_inline unsigned long
383 compute_subtree_max_size(struct vmap_area *va)
385 return max3(va_size(va),
386 get_subtree_max_size(va->rb_node.rb_left),
387 get_subtree_max_size(va->rb_node.rb_right));
390 RB_DECLARE_CALLBACKS(static, free_vmap_area_rb_augment_cb,
391 struct vmap_area, rb_node, unsigned long, subtree_max_size,
392 compute_subtree_max_size)
394 static void purge_vmap_area_lazy(void);
395 static BLOCKING_NOTIFIER_HEAD(vmap_notify_list);
396 static unsigned long lazy_max_pages(void);
398 static struct vmap_area *__find_vmap_area(unsigned long addr)
400 struct rb_node *n = vmap_area_root.rb_node;
403 struct vmap_area *va;
405 va = rb_entry(n, struct vmap_area, rb_node);
406 if (addr < va->va_start)
408 else if (addr >= va->va_end)
418 * This function returns back addresses of parent node
419 * and its left or right link for further processing.
421 static __always_inline struct rb_node **
422 find_va_links(struct vmap_area *va,
423 struct rb_root *root, struct rb_node *from,
424 struct rb_node **parent)
426 struct vmap_area *tmp_va;
427 struct rb_node **link;
430 link = &root->rb_node;
431 if (unlikely(!*link)) {
440 * Go to the bottom of the tree. When we hit the last point
441 * we end up with parent rb_node and correct direction, i name
442 * it link, where the new va->rb_node will be attached to.
445 tmp_va = rb_entry(*link, struct vmap_area, rb_node);
448 * During the traversal we also do some sanity check.
449 * Trigger the BUG() if there are sides(left/right)
452 if (va->va_start < tmp_va->va_end &&
453 va->va_end <= tmp_va->va_start)
454 link = &(*link)->rb_left;
455 else if (va->va_end > tmp_va->va_start &&
456 va->va_start >= tmp_va->va_end)
457 link = &(*link)->rb_right;
462 *parent = &tmp_va->rb_node;
466 static __always_inline struct list_head *
467 get_va_next_sibling(struct rb_node *parent, struct rb_node **link)
469 struct list_head *list;
471 if (unlikely(!parent))
473 * The red-black tree where we try to find VA neighbors
474 * before merging or inserting is empty, i.e. it means
475 * there is no free vmap space. Normally it does not
476 * happen but we handle this case anyway.
480 list = &rb_entry(parent, struct vmap_area, rb_node)->list;
481 return (&parent->rb_right == link ? list->next : list);
484 static __always_inline void
485 link_va(struct vmap_area *va, struct rb_root *root,
486 struct rb_node *parent, struct rb_node **link, struct list_head *head)
489 * VA is still not in the list, but we can
490 * identify its future previous list_head node.
492 if (likely(parent)) {
493 head = &rb_entry(parent, struct vmap_area, rb_node)->list;
494 if (&parent->rb_right != link)
498 /* Insert to the rb-tree */
499 rb_link_node(&va->rb_node, parent, link);
500 if (root == &free_vmap_area_root) {
502 * Some explanation here. Just perform simple insertion
503 * to the tree. We do not set va->subtree_max_size to
504 * its current size before calling rb_insert_augmented().
505 * It is because of we populate the tree from the bottom
506 * to parent levels when the node _is_ in the tree.
508 * Therefore we set subtree_max_size to zero after insertion,
509 * to let __augment_tree_propagate_from() puts everything to
510 * the correct order later on.
512 rb_insert_augmented(&va->rb_node,
513 root, &free_vmap_area_rb_augment_cb);
514 va->subtree_max_size = 0;
516 rb_insert_color(&va->rb_node, root);
519 /* Address-sort this list */
520 list_add(&va->list, head);
523 static __always_inline void
524 unlink_va(struct vmap_area *va, struct rb_root *root)
527 * During merging a VA node can be empty, therefore
528 * not linked with the tree nor list. Just check it.
530 if (!RB_EMPTY_NODE(&va->rb_node)) {
531 if (root == &free_vmap_area_root)
532 rb_erase_augmented(&va->rb_node,
533 root, &free_vmap_area_rb_augment_cb);
535 rb_erase(&va->rb_node, root);
538 RB_CLEAR_NODE(&va->rb_node);
543 * This function populates subtree_max_size from bottom to upper
544 * levels starting from VA point. The propagation must be done
545 * when VA size is modified by changing its va_start/va_end. Or
546 * in case of newly inserting of VA to the tree.
548 * It means that __augment_tree_propagate_from() must be called:
549 * - After VA has been inserted to the tree(free path);
550 * - After VA has been shrunk(allocation path);
551 * - After VA has been increased(merging path).
553 * Please note that, it does not mean that upper parent nodes
554 * and their subtree_max_size are recalculated all the time up
563 * For example if we modify the node 4, shrinking it to 2, then
564 * no any modification is required. If we shrink the node 2 to 1
565 * its subtree_max_size is updated only, and set to 1. If we shrink
566 * the node 8 to 6, then its subtree_max_size is set to 6 and parent
569 static __always_inline void
570 augment_tree_propagate_from(struct vmap_area *va)
572 struct rb_node *node = &va->rb_node;
573 unsigned long new_va_sub_max_size;
576 va = rb_entry(node, struct vmap_area, rb_node);
577 new_va_sub_max_size = compute_subtree_max_size(va);
580 * If the newly calculated maximum available size of the
581 * subtree is equal to the current one, then it means that
582 * the tree is propagated correctly. So we have to stop at
583 * this point to save cycles.
585 if (va->subtree_max_size == new_va_sub_max_size)
588 va->subtree_max_size = new_va_sub_max_size;
589 node = rb_parent(&va->rb_node);
594 insert_vmap_area(struct vmap_area *va,
595 struct rb_root *root, struct list_head *head)
597 struct rb_node **link;
598 struct rb_node *parent;
600 link = find_va_links(va, root, NULL, &parent);
601 link_va(va, root, parent, link, head);
605 insert_vmap_area_augment(struct vmap_area *va,
606 struct rb_node *from, struct rb_root *root,
607 struct list_head *head)
609 struct rb_node **link;
610 struct rb_node *parent;
613 link = find_va_links(va, NULL, from, &parent);
615 link = find_va_links(va, root, NULL, &parent);
617 link_va(va, root, parent, link, head);
618 augment_tree_propagate_from(va);
622 * Merge de-allocated chunk of VA memory with previous
623 * and next free blocks. If coalesce is not done a new
624 * free area is inserted. If VA has been merged, it is
627 static __always_inline void
628 merge_or_add_vmap_area(struct vmap_area *va,
629 struct rb_root *root, struct list_head *head)
631 struct vmap_area *sibling;
632 struct list_head *next;
633 struct rb_node **link;
634 struct rb_node *parent;
638 * Find a place in the tree where VA potentially will be
639 * inserted, unless it is merged with its sibling/siblings.
641 link = find_va_links(va, root, NULL, &parent);
644 * Get next node of VA to check if merging can be done.
646 next = get_va_next_sibling(parent, link);
647 if (unlikely(next == NULL))
653 * |<------VA------>|<-----Next----->|
658 sibling = list_entry(next, struct vmap_area, list);
659 if (sibling->va_start == va->va_end) {
660 sibling->va_start = va->va_start;
662 /* Check and update the tree if needed. */
663 augment_tree_propagate_from(sibling);
665 /* Remove this VA, it has been merged. */
668 /* Free vmap_area object. */
669 kmem_cache_free(vmap_area_cachep, va);
671 /* Point to the new merged area. */
680 * |<-----Prev----->|<------VA------>|
684 if (next->prev != head) {
685 sibling = list_entry(next->prev, struct vmap_area, list);
686 if (sibling->va_end == va->va_start) {
687 sibling->va_end = va->va_end;
689 /* Check and update the tree if needed. */
690 augment_tree_propagate_from(sibling);
692 /* Remove this VA, it has been merged. */
695 /* Free vmap_area object. */
696 kmem_cache_free(vmap_area_cachep, va);
704 link_va(va, root, parent, link, head);
705 augment_tree_propagate_from(va);
709 static __always_inline bool
710 is_within_this_va(struct vmap_area *va, unsigned long size,
711 unsigned long align, unsigned long vstart)
713 unsigned long nva_start_addr;
715 if (va->va_start > vstart)
716 nva_start_addr = ALIGN(va->va_start, align);
718 nva_start_addr = ALIGN(vstart, align);
720 /* Can be overflowed due to big size or alignment. */
721 if (nva_start_addr + size < nva_start_addr ||
722 nva_start_addr < vstart)
725 return (nva_start_addr + size <= va->va_end);
729 * Find the first free block(lowest start address) in the tree,
730 * that will accomplish the request corresponding to passing
733 static __always_inline struct vmap_area *
734 find_vmap_lowest_match(unsigned long size,
735 unsigned long align, unsigned long vstart)
737 struct vmap_area *va;
738 struct rb_node *node;
739 unsigned long length;
741 /* Start from the root. */
742 node = free_vmap_area_root.rb_node;
744 /* Adjust the search size for alignment overhead. */
745 length = size + align - 1;
748 va = rb_entry(node, struct vmap_area, rb_node);
750 if (get_subtree_max_size(node->rb_left) >= length &&
751 vstart < va->va_start) {
752 node = node->rb_left;
754 if (is_within_this_va(va, size, align, vstart))
758 * Does not make sense to go deeper towards the right
759 * sub-tree if it does not have a free block that is
760 * equal or bigger to the requested search length.
762 if (get_subtree_max_size(node->rb_right) >= length) {
763 node = node->rb_right;
768 * OK. We roll back and find the fist right sub-tree,
769 * that will satisfy the search criteria. It can happen
770 * only once due to "vstart" restriction.
772 while ((node = rb_parent(node))) {
773 va = rb_entry(node, struct vmap_area, rb_node);
774 if (is_within_this_va(va, size, align, vstart))
777 if (get_subtree_max_size(node->rb_right) >= length &&
778 vstart <= va->va_start) {
779 node = node->rb_right;
791 FL_FIT_TYPE = 1, /* full fit */
792 LE_FIT_TYPE = 2, /* left edge fit */
793 RE_FIT_TYPE = 3, /* right edge fit */
794 NE_FIT_TYPE = 4 /* no edge fit */
797 static __always_inline enum fit_type
798 classify_va_fit_type(struct vmap_area *va,
799 unsigned long nva_start_addr, unsigned long size)
803 /* Check if it is within VA. */
804 if (nva_start_addr < va->va_start ||
805 nva_start_addr + size > va->va_end)
809 if (va->va_start == nva_start_addr) {
810 if (va->va_end == nva_start_addr + size)
814 } else if (va->va_end == nva_start_addr + size) {
823 static __always_inline int
824 adjust_va_to_fit_type(struct vmap_area *va,
825 unsigned long nva_start_addr, unsigned long size,
828 struct vmap_area *lva;
830 if (type == FL_FIT_TYPE) {
832 * No need to split VA, it fully fits.
838 unlink_va(va, &free_vmap_area_root);
839 kmem_cache_free(vmap_area_cachep, va);
840 } else if (type == LE_FIT_TYPE) {
842 * Split left edge of fit VA.
848 va->va_start += size;
849 } else if (type == RE_FIT_TYPE) {
851 * Split right edge of fit VA.
857 va->va_end = nva_start_addr;
858 } else if (type == NE_FIT_TYPE) {
860 * Split no edge of fit VA.
866 lva = kmem_cache_alloc(vmap_area_cachep, GFP_NOWAIT);
871 * Build the remainder.
873 lva->va_start = va->va_start;
874 lva->va_end = nva_start_addr;
877 * Shrink this VA to remaining size.
879 va->va_start = nva_start_addr + size;
884 if (type != FL_FIT_TYPE) {
885 augment_tree_propagate_from(va);
887 if (type == NE_FIT_TYPE)
888 insert_vmap_area_augment(lva, &va->rb_node,
889 &free_vmap_area_root, &free_vmap_area_list);
896 * Returns a start address of the newly allocated area, if success.
897 * Otherwise a vend is returned that indicates failure.
899 static __always_inline unsigned long
900 __alloc_vmap_area(unsigned long size, unsigned long align,
901 unsigned long vstart, unsigned long vend, int node)
903 unsigned long nva_start_addr;
904 struct vmap_area *va;
908 va = find_vmap_lowest_match(size, align, vstart);
912 if (va->va_start > vstart)
913 nva_start_addr = ALIGN(va->va_start, align);
915 nva_start_addr = ALIGN(vstart, align);
917 /* Check the "vend" restriction. */
918 if (nva_start_addr + size > vend)
921 /* Classify what we have found. */
922 type = classify_va_fit_type(va, nva_start_addr, size);
923 if (WARN_ON_ONCE(type == NOTHING_FIT))
926 /* Update the free vmap_area. */
927 ret = adjust_va_to_fit_type(va, nva_start_addr, size, type);
931 return nva_start_addr;
935 * Allocate a region of KVA of the specified size and alignment, within the
938 static struct vmap_area *alloc_vmap_area(unsigned long size,
940 unsigned long vstart, unsigned long vend,
941 int node, gfp_t gfp_mask)
943 struct vmap_area *va;
948 BUG_ON(offset_in_page(size));
949 BUG_ON(!is_power_of_2(align));
951 if (unlikely(!vmap_initialized))
952 return ERR_PTR(-EBUSY);
956 va = kmem_cache_alloc_node(vmap_area_cachep,
957 gfp_mask & GFP_RECLAIM_MASK, node);
959 return ERR_PTR(-ENOMEM);
962 * Only scan the relevant parts containing pointers to other objects
963 * to avoid false negatives.
965 kmemleak_scan_area(&va->rb_node, SIZE_MAX, gfp_mask & GFP_RECLAIM_MASK);
968 spin_lock(&vmap_area_lock);
971 * If an allocation fails, the "vend" address is
972 * returned. Therefore trigger the overflow path.
974 addr = __alloc_vmap_area(size, align, vstart, vend, node);
975 if (unlikely(addr == vend))
979 va->va_end = addr + size;
981 insert_vmap_area(va, &vmap_area_root, &vmap_area_list);
983 spin_unlock(&vmap_area_lock);
985 BUG_ON(!IS_ALIGNED(va->va_start, align));
986 BUG_ON(va->va_start < vstart);
987 BUG_ON(va->va_end > vend);
992 spin_unlock(&vmap_area_lock);
994 purge_vmap_area_lazy();
999 if (gfpflags_allow_blocking(gfp_mask)) {
1000 unsigned long freed = 0;
1001 blocking_notifier_call_chain(&vmap_notify_list, 0, &freed);
1008 if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit())
1009 pr_warn("vmap allocation for size %lu failed: use vmalloc=<size> to increase size\n",
1012 kmem_cache_free(vmap_area_cachep, va);
1013 return ERR_PTR(-EBUSY);
1016 int register_vmap_purge_notifier(struct notifier_block *nb)
1018 return blocking_notifier_chain_register(&vmap_notify_list, nb);
1020 EXPORT_SYMBOL_GPL(register_vmap_purge_notifier);
1022 int unregister_vmap_purge_notifier(struct notifier_block *nb)
1024 return blocking_notifier_chain_unregister(&vmap_notify_list, nb);
1026 EXPORT_SYMBOL_GPL(unregister_vmap_purge_notifier);
1028 static void __free_vmap_area(struct vmap_area *va)
1030 BUG_ON(RB_EMPTY_NODE(&va->rb_node));
1033 * Remove from the busy tree/list.
1035 unlink_va(va, &vmap_area_root);
1038 * Merge VA with its neighbors, otherwise just add it.
1040 merge_or_add_vmap_area(va,
1041 &free_vmap_area_root, &free_vmap_area_list);
1045 * Free a region of KVA allocated by alloc_vmap_area
1047 static void free_vmap_area(struct vmap_area *va)
1049 spin_lock(&vmap_area_lock);
1050 __free_vmap_area(va);
1051 spin_unlock(&vmap_area_lock);
1055 * Clear the pagetable entries of a given vmap_area
1057 static void unmap_vmap_area(struct vmap_area *va)
1059 vunmap_page_range(va->va_start, va->va_end);
1063 * lazy_max_pages is the maximum amount of virtual address space we gather up
1064 * before attempting to purge with a TLB flush.
1066 * There is a tradeoff here: a larger number will cover more kernel page tables
1067 * and take slightly longer to purge, but it will linearly reduce the number of
1068 * global TLB flushes that must be performed. It would seem natural to scale
1069 * this number up linearly with the number of CPUs (because vmapping activity
1070 * could also scale linearly with the number of CPUs), however it is likely
1071 * that in practice, workloads might be constrained in other ways that mean
1072 * vmap activity will not scale linearly with CPUs. Also, I want to be
1073 * conservative and not introduce a big latency on huge systems, so go with
1074 * a less aggressive log scale. It will still be an improvement over the old
1075 * code, and it will be simple to change the scale factor if we find that it
1076 * becomes a problem on bigger systems.
1078 static unsigned long lazy_max_pages(void)
1082 log = fls(num_online_cpus());
1084 return log * (32UL * 1024 * 1024 / PAGE_SIZE);
1087 static atomic_long_t vmap_lazy_nr = ATOMIC_LONG_INIT(0);
1090 * Serialize vmap purging. There is no actual criticial section protected
1091 * by this look, but we want to avoid concurrent calls for performance
1092 * reasons and to make the pcpu_get_vm_areas more deterministic.
1094 static DEFINE_MUTEX(vmap_purge_lock);
1096 /* for per-CPU blocks */
1097 static void purge_fragmented_blocks_allcpus(void);
1100 * called before a call to iounmap() if the caller wants vm_area_struct's
1101 * immediately freed.
1103 void set_iounmap_nonlazy(void)
1105 atomic_long_set(&vmap_lazy_nr, lazy_max_pages()+1);
1109 * Purges all lazily-freed vmap areas.
1111 static bool __purge_vmap_area_lazy(unsigned long start, unsigned long end)
1113 unsigned long resched_threshold;
1114 struct llist_node *valist;
1115 struct vmap_area *va;
1116 struct vmap_area *n_va;
1118 lockdep_assert_held(&vmap_purge_lock);
1120 valist = llist_del_all(&vmap_purge_list);
1121 if (unlikely(valist == NULL))
1125 * TODO: to calculate a flush range without looping.
1126 * The list can be up to lazy_max_pages() elements.
1128 llist_for_each_entry(va, valist, purge_list) {
1129 if (va->va_start < start)
1130 start = va->va_start;
1131 if (va->va_end > end)
1135 flush_tlb_kernel_range(start, end);
1136 resched_threshold = lazy_max_pages() << 1;
1138 spin_lock(&vmap_area_lock);
1139 llist_for_each_entry_safe(va, n_va, valist, purge_list) {
1140 unsigned long nr = (va->va_end - va->va_start) >> PAGE_SHIFT;
1142 __free_vmap_area(va);
1143 atomic_long_sub(nr, &vmap_lazy_nr);
1145 if (atomic_long_read(&vmap_lazy_nr) < resched_threshold)
1146 cond_resched_lock(&vmap_area_lock);
1148 spin_unlock(&vmap_area_lock);
1153 * Kick off a purge of the outstanding lazy areas. Don't bother if somebody
1154 * is already purging.
1156 static void try_purge_vmap_area_lazy(void)
1158 if (mutex_trylock(&vmap_purge_lock)) {
1159 __purge_vmap_area_lazy(ULONG_MAX, 0);
1160 mutex_unlock(&vmap_purge_lock);
1165 * Kick off a purge of the outstanding lazy areas.
1167 static void purge_vmap_area_lazy(void)
1169 mutex_lock(&vmap_purge_lock);
1170 purge_fragmented_blocks_allcpus();
1171 __purge_vmap_area_lazy(ULONG_MAX, 0);
1172 mutex_unlock(&vmap_purge_lock);
1176 * Free a vmap area, caller ensuring that the area has been unmapped
1177 * and flush_cache_vunmap had been called for the correct range
1180 static void free_vmap_area_noflush(struct vmap_area *va)
1182 unsigned long nr_lazy;
1184 nr_lazy = atomic_long_add_return((va->va_end - va->va_start) >>
1185 PAGE_SHIFT, &vmap_lazy_nr);
1187 /* After this point, we may free va at any time */
1188 llist_add(&va->purge_list, &vmap_purge_list);
1190 if (unlikely(nr_lazy > lazy_max_pages()))
1191 try_purge_vmap_area_lazy();
1195 * Free and unmap a vmap area
1197 static void free_unmap_vmap_area(struct vmap_area *va)
1199 flush_cache_vunmap(va->va_start, va->va_end);
1200 unmap_vmap_area(va);
1201 if (debug_pagealloc_enabled())
1202 flush_tlb_kernel_range(va->va_start, va->va_end);
1204 free_vmap_area_noflush(va);
1207 static struct vmap_area *find_vmap_area(unsigned long addr)
1209 struct vmap_area *va;
1211 spin_lock(&vmap_area_lock);
1212 va = __find_vmap_area(addr);
1213 spin_unlock(&vmap_area_lock);
1218 /*** Per cpu kva allocator ***/
1221 * vmap space is limited especially on 32 bit architectures. Ensure there is
1222 * room for at least 16 percpu vmap blocks per CPU.
1225 * If we had a constant VMALLOC_START and VMALLOC_END, we'd like to be able
1226 * to #define VMALLOC_SPACE (VMALLOC_END-VMALLOC_START). Guess
1227 * instead (we just need a rough idea)
1229 #if BITS_PER_LONG == 32
1230 #define VMALLOC_SPACE (128UL*1024*1024)
1232 #define VMALLOC_SPACE (128UL*1024*1024*1024)
1235 #define VMALLOC_PAGES (VMALLOC_SPACE / PAGE_SIZE)
1236 #define VMAP_MAX_ALLOC BITS_PER_LONG /* 256K with 4K pages */
1237 #define VMAP_BBMAP_BITS_MAX 1024 /* 4MB with 4K pages */
1238 #define VMAP_BBMAP_BITS_MIN (VMAP_MAX_ALLOC*2)
1239 #define VMAP_MIN(x, y) ((x) < (y) ? (x) : (y)) /* can't use min() */
1240 #define VMAP_MAX(x, y) ((x) > (y) ? (x) : (y)) /* can't use max() */
1241 #define VMAP_BBMAP_BITS \
1242 VMAP_MIN(VMAP_BBMAP_BITS_MAX, \
1243 VMAP_MAX(VMAP_BBMAP_BITS_MIN, \
1244 VMALLOC_PAGES / roundup_pow_of_two(NR_CPUS) / 16))
1246 #define VMAP_BLOCK_SIZE (VMAP_BBMAP_BITS * PAGE_SIZE)
1248 struct vmap_block_queue {
1250 struct list_head free;
1255 struct vmap_area *va;
1256 unsigned long free, dirty;
1257 unsigned long dirty_min, dirty_max; /*< dirty range */
1258 struct list_head free_list;
1259 struct rcu_head rcu_head;
1260 struct list_head purge;
1263 /* Queue of free and dirty vmap blocks, for allocation and flushing purposes */
1264 static DEFINE_PER_CPU(struct vmap_block_queue, vmap_block_queue);
1267 * Radix tree of vmap blocks, indexed by address, to quickly find a vmap block
1268 * in the free path. Could get rid of this if we change the API to return a
1269 * "cookie" from alloc, to be passed to free. But no big deal yet.
1271 static DEFINE_SPINLOCK(vmap_block_tree_lock);
1272 static RADIX_TREE(vmap_block_tree, GFP_ATOMIC);
1275 * We should probably have a fallback mechanism to allocate virtual memory
1276 * out of partially filled vmap blocks. However vmap block sizing should be
1277 * fairly reasonable according to the vmalloc size, so it shouldn't be a
1281 static unsigned long addr_to_vb_idx(unsigned long addr)
1283 addr -= VMALLOC_START & ~(VMAP_BLOCK_SIZE-1);
1284 addr /= VMAP_BLOCK_SIZE;
1288 static void *vmap_block_vaddr(unsigned long va_start, unsigned long pages_off)
1292 addr = va_start + (pages_off << PAGE_SHIFT);
1293 BUG_ON(addr_to_vb_idx(addr) != addr_to_vb_idx(va_start));
1294 return (void *)addr;
1298 * new_vmap_block - allocates new vmap_block and occupies 2^order pages in this
1299 * block. Of course pages number can't exceed VMAP_BBMAP_BITS
1300 * @order: how many 2^order pages should be occupied in newly allocated block
1301 * @gfp_mask: flags for the page level allocator
1303 * Return: virtual address in a newly allocated block or ERR_PTR(-errno)
1305 static void *new_vmap_block(unsigned int order, gfp_t gfp_mask)
1307 struct vmap_block_queue *vbq;
1308 struct vmap_block *vb;
1309 struct vmap_area *va;
1310 unsigned long vb_idx;
1314 node = numa_node_id();
1316 vb = kmalloc_node(sizeof(struct vmap_block),
1317 gfp_mask & GFP_RECLAIM_MASK, node);
1319 return ERR_PTR(-ENOMEM);
1321 va = alloc_vmap_area(VMAP_BLOCK_SIZE, VMAP_BLOCK_SIZE,
1322 VMALLOC_START, VMALLOC_END,
1326 return ERR_CAST(va);
1329 err = radix_tree_preload(gfp_mask);
1330 if (unlikely(err)) {
1333 return ERR_PTR(err);
1336 vaddr = vmap_block_vaddr(va->va_start, 0);
1337 spin_lock_init(&vb->lock);
1339 /* At least something should be left free */
1340 BUG_ON(VMAP_BBMAP_BITS <= (1UL << order));
1341 vb->free = VMAP_BBMAP_BITS - (1UL << order);
1343 vb->dirty_min = VMAP_BBMAP_BITS;
1345 INIT_LIST_HEAD(&vb->free_list);
1347 vb_idx = addr_to_vb_idx(va->va_start);
1348 spin_lock(&vmap_block_tree_lock);
1349 err = radix_tree_insert(&vmap_block_tree, vb_idx, vb);
1350 spin_unlock(&vmap_block_tree_lock);
1352 radix_tree_preload_end();
1354 vbq = &get_cpu_var(vmap_block_queue);
1355 spin_lock(&vbq->lock);
1356 list_add_tail_rcu(&vb->free_list, &vbq->free);
1357 spin_unlock(&vbq->lock);
1358 put_cpu_var(vmap_block_queue);
1363 static void free_vmap_block(struct vmap_block *vb)
1365 struct vmap_block *tmp;
1366 unsigned long vb_idx;
1368 vb_idx = addr_to_vb_idx(vb->va->va_start);
1369 spin_lock(&vmap_block_tree_lock);
1370 tmp = radix_tree_delete(&vmap_block_tree, vb_idx);
1371 spin_unlock(&vmap_block_tree_lock);
1374 free_vmap_area_noflush(vb->va);
1375 kfree_rcu(vb, rcu_head);
1378 static void purge_fragmented_blocks(int cpu)
1381 struct vmap_block *vb;
1382 struct vmap_block *n_vb;
1383 struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu);
1386 list_for_each_entry_rcu(vb, &vbq->free, free_list) {
1388 if (!(vb->free + vb->dirty == VMAP_BBMAP_BITS && vb->dirty != VMAP_BBMAP_BITS))
1391 spin_lock(&vb->lock);
1392 if (vb->free + vb->dirty == VMAP_BBMAP_BITS && vb->dirty != VMAP_BBMAP_BITS) {
1393 vb->free = 0; /* prevent further allocs after releasing lock */
1394 vb->dirty = VMAP_BBMAP_BITS; /* prevent purging it again */
1396 vb->dirty_max = VMAP_BBMAP_BITS;
1397 spin_lock(&vbq->lock);
1398 list_del_rcu(&vb->free_list);
1399 spin_unlock(&vbq->lock);
1400 spin_unlock(&vb->lock);
1401 list_add_tail(&vb->purge, &purge);
1403 spin_unlock(&vb->lock);
1407 list_for_each_entry_safe(vb, n_vb, &purge, purge) {
1408 list_del(&vb->purge);
1409 free_vmap_block(vb);
1413 static void purge_fragmented_blocks_allcpus(void)
1417 for_each_possible_cpu(cpu)
1418 purge_fragmented_blocks(cpu);
1421 static void *vb_alloc(unsigned long size, gfp_t gfp_mask)
1423 struct vmap_block_queue *vbq;
1424 struct vmap_block *vb;
1428 BUG_ON(offset_in_page(size));
1429 BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
1430 if (WARN_ON(size == 0)) {
1432 * Allocating 0 bytes isn't what caller wants since
1433 * get_order(0) returns funny result. Just warn and terminate
1438 order = get_order(size);
1441 vbq = &get_cpu_var(vmap_block_queue);
1442 list_for_each_entry_rcu(vb, &vbq->free, free_list) {
1443 unsigned long pages_off;
1445 spin_lock(&vb->lock);
1446 if (vb->free < (1UL << order)) {
1447 spin_unlock(&vb->lock);
1451 pages_off = VMAP_BBMAP_BITS - vb->free;
1452 vaddr = vmap_block_vaddr(vb->va->va_start, pages_off);
1453 vb->free -= 1UL << order;
1454 if (vb->free == 0) {
1455 spin_lock(&vbq->lock);
1456 list_del_rcu(&vb->free_list);
1457 spin_unlock(&vbq->lock);
1460 spin_unlock(&vb->lock);
1464 put_cpu_var(vmap_block_queue);
1467 /* Allocate new block if nothing was found */
1469 vaddr = new_vmap_block(order, gfp_mask);
1474 static void vb_free(const void *addr, unsigned long size)
1476 unsigned long offset;
1477 unsigned long vb_idx;
1479 struct vmap_block *vb;
1481 BUG_ON(offset_in_page(size));
1482 BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
1484 flush_cache_vunmap((unsigned long)addr, (unsigned long)addr + size);
1486 order = get_order(size);
1488 offset = (unsigned long)addr & (VMAP_BLOCK_SIZE - 1);
1489 offset >>= PAGE_SHIFT;
1491 vb_idx = addr_to_vb_idx((unsigned long)addr);
1493 vb = radix_tree_lookup(&vmap_block_tree, vb_idx);
1497 vunmap_page_range((unsigned long)addr, (unsigned long)addr + size);
1499 if (debug_pagealloc_enabled())
1500 flush_tlb_kernel_range((unsigned long)addr,
1501 (unsigned long)addr + size);
1503 spin_lock(&vb->lock);
1505 /* Expand dirty range */
1506 vb->dirty_min = min(vb->dirty_min, offset);
1507 vb->dirty_max = max(vb->dirty_max, offset + (1UL << order));
1509 vb->dirty += 1UL << order;
1510 if (vb->dirty == VMAP_BBMAP_BITS) {
1512 spin_unlock(&vb->lock);
1513 free_vmap_block(vb);
1515 spin_unlock(&vb->lock);
1518 static void _vm_unmap_aliases(unsigned long start, unsigned long end, int flush)
1522 if (unlikely(!vmap_initialized))
1527 for_each_possible_cpu(cpu) {
1528 struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu);
1529 struct vmap_block *vb;
1532 list_for_each_entry_rcu(vb, &vbq->free, free_list) {
1533 spin_lock(&vb->lock);
1535 unsigned long va_start = vb->va->va_start;
1538 s = va_start + (vb->dirty_min << PAGE_SHIFT);
1539 e = va_start + (vb->dirty_max << PAGE_SHIFT);
1541 start = min(s, start);
1546 spin_unlock(&vb->lock);
1551 mutex_lock(&vmap_purge_lock);
1552 purge_fragmented_blocks_allcpus();
1553 if (!__purge_vmap_area_lazy(start, end) && flush)
1554 flush_tlb_kernel_range(start, end);
1555 mutex_unlock(&vmap_purge_lock);
1559 * vm_unmap_aliases - unmap outstanding lazy aliases in the vmap layer
1561 * The vmap/vmalloc layer lazily flushes kernel virtual mappings primarily
1562 * to amortize TLB flushing overheads. What this means is that any page you
1563 * have now, may, in a former life, have been mapped into kernel virtual
1564 * address by the vmap layer and so there might be some CPUs with TLB entries
1565 * still referencing that page (additional to the regular 1:1 kernel mapping).
1567 * vm_unmap_aliases flushes all such lazy mappings. After it returns, we can
1568 * be sure that none of the pages we have control over will have any aliases
1569 * from the vmap layer.
1571 void vm_unmap_aliases(void)
1573 unsigned long start = ULONG_MAX, end = 0;
1576 _vm_unmap_aliases(start, end, flush);
1578 EXPORT_SYMBOL_GPL(vm_unmap_aliases);
1581 * vm_unmap_ram - unmap linear kernel address space set up by vm_map_ram
1582 * @mem: the pointer returned by vm_map_ram
1583 * @count: the count passed to that vm_map_ram call (cannot unmap partial)
1585 void vm_unmap_ram(const void *mem, unsigned int count)
1587 unsigned long size = (unsigned long)count << PAGE_SHIFT;
1588 unsigned long addr = (unsigned long)mem;
1589 struct vmap_area *va;
1593 BUG_ON(addr < VMALLOC_START);
1594 BUG_ON(addr > VMALLOC_END);
1595 BUG_ON(!PAGE_ALIGNED(addr));
1597 if (likely(count <= VMAP_MAX_ALLOC)) {
1598 debug_check_no_locks_freed(mem, size);
1603 va = find_vmap_area(addr);
1605 debug_check_no_locks_freed((void *)va->va_start,
1606 (va->va_end - va->va_start));
1607 free_unmap_vmap_area(va);
1609 EXPORT_SYMBOL(vm_unmap_ram);
1612 * vm_map_ram - map pages linearly into kernel virtual address (vmalloc space)
1613 * @pages: an array of pointers to the pages to be mapped
1614 * @count: number of pages
1615 * @node: prefer to allocate data structures on this node
1616 * @prot: memory protection to use. PAGE_KERNEL for regular RAM
1618 * If you use this function for less than VMAP_MAX_ALLOC pages, it could be
1619 * faster than vmap so it's good. But if you mix long-life and short-life
1620 * objects with vm_map_ram(), it could consume lots of address space through
1621 * fragmentation (especially on a 32bit machine). You could see failures in
1622 * the end. Please use this function for short-lived objects.
1624 * Returns: a pointer to the address that has been mapped, or %NULL on failure
1626 void *vm_map_ram(struct page **pages, unsigned int count, int node, pgprot_t prot)
1628 unsigned long size = (unsigned long)count << PAGE_SHIFT;
1632 if (likely(count <= VMAP_MAX_ALLOC)) {
1633 mem = vb_alloc(size, GFP_KERNEL);
1636 addr = (unsigned long)mem;
1638 struct vmap_area *va;
1639 va = alloc_vmap_area(size, PAGE_SIZE,
1640 VMALLOC_START, VMALLOC_END, node, GFP_KERNEL);
1644 addr = va->va_start;
1647 if (vmap_page_range(addr, addr + size, prot, pages) < 0) {
1648 vm_unmap_ram(mem, count);
1653 EXPORT_SYMBOL(vm_map_ram);
1655 static struct vm_struct *vmlist __initdata;
1658 * vm_area_add_early - add vmap area early during boot
1659 * @vm: vm_struct to add
1661 * This function is used to add fixed kernel vm area to vmlist before
1662 * vmalloc_init() is called. @vm->addr, @vm->size, and @vm->flags
1663 * should contain proper values and the other fields should be zero.
1665 * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING.
1667 void __init vm_area_add_early(struct vm_struct *vm)
1669 struct vm_struct *tmp, **p;
1671 BUG_ON(vmap_initialized);
1672 for (p = &vmlist; (tmp = *p) != NULL; p = &tmp->next) {
1673 if (tmp->addr >= vm->addr) {
1674 BUG_ON(tmp->addr < vm->addr + vm->size);
1677 BUG_ON(tmp->addr + tmp->size > vm->addr);
1684 * vm_area_register_early - register vmap area early during boot
1685 * @vm: vm_struct to register
1686 * @align: requested alignment
1688 * This function is used to register kernel vm area before
1689 * vmalloc_init() is called. @vm->size and @vm->flags should contain
1690 * proper values on entry and other fields should be zero. On return,
1691 * vm->addr contains the allocated address.
1693 * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING.
1695 void __init vm_area_register_early(struct vm_struct *vm, size_t align)
1697 static size_t vm_init_off __initdata;
1700 addr = ALIGN(VMALLOC_START + vm_init_off, align);
1701 vm_init_off = PFN_ALIGN(addr + vm->size) - VMALLOC_START;
1703 vm->addr = (void *)addr;
1705 vm_area_add_early(vm);
1708 static void vmap_init_free_space(void)
1710 unsigned long vmap_start = 1;
1711 const unsigned long vmap_end = ULONG_MAX;
1712 struct vmap_area *busy, *free;
1716 * -|-----|.....|-----|-----|-----|.....|-
1718 * |<--------------------------------->|
1720 list_for_each_entry(busy, &vmap_area_list, list) {
1721 if (busy->va_start - vmap_start > 0) {
1722 free = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
1723 if (!WARN_ON_ONCE(!free)) {
1724 free->va_start = vmap_start;
1725 free->va_end = busy->va_start;
1727 insert_vmap_area_augment(free, NULL,
1728 &free_vmap_area_root,
1729 &free_vmap_area_list);
1733 vmap_start = busy->va_end;
1736 if (vmap_end - vmap_start > 0) {
1737 free = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
1738 if (!WARN_ON_ONCE(!free)) {
1739 free->va_start = vmap_start;
1740 free->va_end = vmap_end;
1742 insert_vmap_area_augment(free, NULL,
1743 &free_vmap_area_root,
1744 &free_vmap_area_list);
1749 void __init vmalloc_init(void)
1751 struct vmap_area *va;
1752 struct vm_struct *tmp;
1756 * Create the cache for vmap_area objects.
1758 vmap_area_cachep = KMEM_CACHE(vmap_area, SLAB_PANIC);
1760 for_each_possible_cpu(i) {
1761 struct vmap_block_queue *vbq;
1762 struct vfree_deferred *p;
1764 vbq = &per_cpu(vmap_block_queue, i);
1765 spin_lock_init(&vbq->lock);
1766 INIT_LIST_HEAD(&vbq->free);
1767 p = &per_cpu(vfree_deferred, i);
1768 init_llist_head(&p->list);
1769 INIT_WORK(&p->wq, free_work);
1772 /* Import existing vmlist entries. */
1773 for (tmp = vmlist; tmp; tmp = tmp->next) {
1774 va = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
1775 if (WARN_ON_ONCE(!va))
1778 va->flags = VM_VM_AREA;
1779 va->va_start = (unsigned long)tmp->addr;
1780 va->va_end = va->va_start + tmp->size;
1782 insert_vmap_area(va, &vmap_area_root, &vmap_area_list);
1786 * Now we can initialize a free vmap space.
1788 vmap_init_free_space();
1789 vmap_initialized = true;
1793 * map_kernel_range_noflush - map kernel VM area with the specified pages
1794 * @addr: start of the VM area to map
1795 * @size: size of the VM area to map
1796 * @prot: page protection flags to use
1797 * @pages: pages to map
1799 * Map PFN_UP(@size) pages at @addr. The VM area @addr and @size
1800 * specify should have been allocated using get_vm_area() and its
1804 * This function does NOT do any cache flushing. The caller is
1805 * responsible for calling flush_cache_vmap() on to-be-mapped areas
1806 * before calling this function.
1809 * The number of pages mapped on success, -errno on failure.
1811 int map_kernel_range_noflush(unsigned long addr, unsigned long size,
1812 pgprot_t prot, struct page **pages)
1814 return vmap_page_range_noflush(addr, addr + size, prot, pages);
1818 * unmap_kernel_range_noflush - unmap kernel VM area
1819 * @addr: start of the VM area to unmap
1820 * @size: size of the VM area to unmap
1822 * Unmap PFN_UP(@size) pages at @addr. The VM area @addr and @size
1823 * specify should have been allocated using get_vm_area() and its
1827 * This function does NOT do any cache flushing. The caller is
1828 * responsible for calling flush_cache_vunmap() on to-be-mapped areas
1829 * before calling this function and flush_tlb_kernel_range() after.
1831 void unmap_kernel_range_noflush(unsigned long addr, unsigned long size)
1833 vunmap_page_range(addr, addr + size);
1835 EXPORT_SYMBOL_GPL(unmap_kernel_range_noflush);
1838 * unmap_kernel_range - unmap kernel VM area and flush cache and TLB
1839 * @addr: start of the VM area to unmap
1840 * @size: size of the VM area to unmap
1842 * Similar to unmap_kernel_range_noflush() but flushes vcache before
1843 * the unmapping and tlb after.
1845 void unmap_kernel_range(unsigned long addr, unsigned long size)
1847 unsigned long end = addr + size;
1849 flush_cache_vunmap(addr, end);
1850 vunmap_page_range(addr, end);
1851 flush_tlb_kernel_range(addr, end);
1853 EXPORT_SYMBOL_GPL(unmap_kernel_range);
1855 int map_vm_area(struct vm_struct *area, pgprot_t prot, struct page **pages)
1857 unsigned long addr = (unsigned long)area->addr;
1858 unsigned long end = addr + get_vm_area_size(area);
1861 err = vmap_page_range(addr, end, prot, pages);
1863 return err > 0 ? 0 : err;
1865 EXPORT_SYMBOL_GPL(map_vm_area);
1867 static void setup_vmalloc_vm(struct vm_struct *vm, struct vmap_area *va,
1868 unsigned long flags, const void *caller)
1870 spin_lock(&vmap_area_lock);
1872 vm->addr = (void *)va->va_start;
1873 vm->size = va->va_end - va->va_start;
1874 vm->caller = caller;
1876 va->flags |= VM_VM_AREA;
1877 spin_unlock(&vmap_area_lock);
1880 static void clear_vm_uninitialized_flag(struct vm_struct *vm)
1883 * Before removing VM_UNINITIALIZED,
1884 * we should make sure that vm has proper values.
1885 * Pair with smp_rmb() in show_numa_info().
1888 vm->flags &= ~VM_UNINITIALIZED;
1891 static struct vm_struct *__get_vm_area_node(unsigned long size,
1892 unsigned long align, unsigned long flags, unsigned long start,
1893 unsigned long end, int node, gfp_t gfp_mask, const void *caller)
1895 struct vmap_area *va;
1896 struct vm_struct *area;
1898 BUG_ON(in_interrupt());
1899 size = PAGE_ALIGN(size);
1900 if (unlikely(!size))
1903 if (flags & VM_IOREMAP)
1904 align = 1ul << clamp_t(int, get_count_order_long(size),
1905 PAGE_SHIFT, IOREMAP_MAX_ORDER);
1907 area = kzalloc_node(sizeof(*area), gfp_mask & GFP_RECLAIM_MASK, node);
1908 if (unlikely(!area))
1911 if (!(flags & VM_NO_GUARD))
1914 va = alloc_vmap_area(size, align, start, end, node, gfp_mask);
1920 setup_vmalloc_vm(area, va, flags, caller);
1925 struct vm_struct *__get_vm_area(unsigned long size, unsigned long flags,
1926 unsigned long start, unsigned long end)
1928 return __get_vm_area_node(size, 1, flags, start, end, NUMA_NO_NODE,
1929 GFP_KERNEL, __builtin_return_address(0));
1931 EXPORT_SYMBOL_GPL(__get_vm_area);
1933 struct vm_struct *__get_vm_area_caller(unsigned long size, unsigned long flags,
1934 unsigned long start, unsigned long end,
1937 return __get_vm_area_node(size, 1, flags, start, end, NUMA_NO_NODE,
1938 GFP_KERNEL, caller);
1942 * get_vm_area - reserve a contiguous kernel virtual area
1943 * @size: size of the area
1944 * @flags: %VM_IOREMAP for I/O mappings or VM_ALLOC
1946 * Search an area of @size in the kernel virtual mapping area,
1947 * and reserved it for out purposes. Returns the area descriptor
1948 * on success or %NULL on failure.
1950 * Return: the area descriptor on success or %NULL on failure.
1952 struct vm_struct *get_vm_area(unsigned long size, unsigned long flags)
1954 return __get_vm_area_node(size, 1, flags, VMALLOC_START, VMALLOC_END,
1955 NUMA_NO_NODE, GFP_KERNEL,
1956 __builtin_return_address(0));
1959 struct vm_struct *get_vm_area_caller(unsigned long size, unsigned long flags,
1962 return __get_vm_area_node(size, 1, flags, VMALLOC_START, VMALLOC_END,
1963 NUMA_NO_NODE, GFP_KERNEL, caller);
1967 * find_vm_area - find a continuous kernel virtual area
1968 * @addr: base address
1970 * Search for the kernel VM area starting at @addr, and return it.
1971 * It is up to the caller to do all required locking to keep the returned
1974 * Return: pointer to the found area or %NULL on faulure
1976 struct vm_struct *find_vm_area(const void *addr)
1978 struct vmap_area *va;
1980 va = find_vmap_area((unsigned long)addr);
1981 if (va && va->flags & VM_VM_AREA)
1988 * remove_vm_area - find and remove a continuous kernel virtual area
1989 * @addr: base address
1991 * Search for the kernel VM area starting at @addr, and remove it.
1992 * This function returns the found VM area, but using it is NOT safe
1993 * on SMP machines, except for its size or flags.
1995 * Return: pointer to the found area or %NULL on faulure
1997 struct vm_struct *remove_vm_area(const void *addr)
1999 struct vmap_area *va;
2003 va = find_vmap_area((unsigned long)addr);
2004 if (va && va->flags & VM_VM_AREA) {
2005 struct vm_struct *vm = va->vm;
2007 spin_lock(&vmap_area_lock);
2009 va->flags &= ~VM_VM_AREA;
2010 va->flags |= VM_LAZY_FREE;
2011 spin_unlock(&vmap_area_lock);
2013 kasan_free_shadow(vm);
2014 free_unmap_vmap_area(va);
2021 static inline void set_area_direct_map(const struct vm_struct *area,
2022 int (*set_direct_map)(struct page *page))
2026 for (i = 0; i < area->nr_pages; i++)
2027 if (page_address(area->pages[i]))
2028 set_direct_map(area->pages[i]);
2031 /* Handle removing and resetting vm mappings related to the vm_struct. */
2032 static void vm_remove_mappings(struct vm_struct *area, int deallocate_pages)
2034 unsigned long addr = (unsigned long)area->addr;
2035 unsigned long start = ULONG_MAX, end = 0;
2036 int flush_reset = area->flags & VM_FLUSH_RESET_PERMS;
2040 * The below block can be removed when all architectures that have
2041 * direct map permissions also have set_direct_map_() implementations.
2042 * This is concerned with resetting the direct map any an vm alias with
2043 * execute permissions, without leaving a RW+X window.
2045 if (flush_reset && !IS_ENABLED(CONFIG_ARCH_HAS_SET_DIRECT_MAP)) {
2046 set_memory_nx(addr, area->nr_pages);
2047 set_memory_rw(addr, area->nr_pages);
2050 remove_vm_area(area->addr);
2052 /* If this is not VM_FLUSH_RESET_PERMS memory, no need for the below. */
2057 * If not deallocating pages, just do the flush of the VM area and
2060 if (!deallocate_pages) {
2066 * If execution gets here, flush the vm mapping and reset the direct
2067 * map. Find the start and end range of the direct mappings to make sure
2068 * the vm_unmap_aliases() flush includes the direct map.
2070 for (i = 0; i < area->nr_pages; i++) {
2071 if (page_address(area->pages[i])) {
2072 start = min(addr, start);
2073 end = max(addr, end);
2078 * Set direct map to something invalid so that it won't be cached if
2079 * there are any accesses after the TLB flush, then flush the TLB and
2080 * reset the direct map permissions to the default.
2082 set_area_direct_map(area, set_direct_map_invalid_noflush);
2083 _vm_unmap_aliases(start, end, 1);
2084 set_area_direct_map(area, set_direct_map_default_noflush);
2087 static void __vunmap(const void *addr, int deallocate_pages)
2089 struct vm_struct *area;
2094 if (WARN(!PAGE_ALIGNED(addr), "Trying to vfree() bad address (%p)\n",
2098 area = find_vm_area(addr);
2099 if (unlikely(!area)) {
2100 WARN(1, KERN_ERR "Trying to vfree() nonexistent vm area (%p)\n",
2105 debug_check_no_locks_freed(area->addr, get_vm_area_size(area));
2106 debug_check_no_obj_freed(area->addr, get_vm_area_size(area));
2108 vm_remove_mappings(area, deallocate_pages);
2110 if (deallocate_pages) {
2113 for (i = 0; i < area->nr_pages; i++) {
2114 struct page *page = area->pages[i];
2117 __free_pages(page, 0);
2120 kvfree(area->pages);
2127 static inline void __vfree_deferred(const void *addr)
2130 * Use raw_cpu_ptr() because this can be called from preemptible
2131 * context. Preemption is absolutely fine here, because the llist_add()
2132 * implementation is lockless, so it works even if we are adding to
2133 * nother cpu's list. schedule_work() should be fine with this too.
2135 struct vfree_deferred *p = raw_cpu_ptr(&vfree_deferred);
2137 if (llist_add((struct llist_node *)addr, &p->list))
2138 schedule_work(&p->wq);
2142 * vfree_atomic - release memory allocated by vmalloc()
2143 * @addr: memory base address
2145 * This one is just like vfree() but can be called in any atomic context
2148 void vfree_atomic(const void *addr)
2152 kmemleak_free(addr);
2156 __vfree_deferred(addr);
2159 static void __vfree(const void *addr)
2161 if (unlikely(in_interrupt()))
2162 __vfree_deferred(addr);
2168 * vfree - release memory allocated by vmalloc()
2169 * @addr: memory base address
2171 * Free the virtually continuous memory area starting at @addr, as
2172 * obtained from vmalloc(), vmalloc_32() or __vmalloc(). If @addr is
2173 * NULL, no operation is performed.
2175 * Must not be called in NMI context (strictly speaking, only if we don't
2176 * have CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG, but making the calling
2177 * conventions for vfree() arch-depenedent would be a really bad idea)
2179 * May sleep if called *not* from interrupt context.
2181 * NOTE: assumes that the object at @addr has a size >= sizeof(llist_node)
2183 void vfree(const void *addr)
2187 kmemleak_free(addr);
2189 might_sleep_if(!in_interrupt());
2196 EXPORT_SYMBOL(vfree);
2199 * vunmap - release virtual mapping obtained by vmap()
2200 * @addr: memory base address
2202 * Free the virtually contiguous memory area starting at @addr,
2203 * which was created from the page array passed to vmap().
2205 * Must not be called in interrupt context.
2207 void vunmap(const void *addr)
2209 BUG_ON(in_interrupt());
2214 EXPORT_SYMBOL(vunmap);
2217 * vmap - map an array of pages into virtually contiguous space
2218 * @pages: array of page pointers
2219 * @count: number of pages to map
2220 * @flags: vm_area->flags
2221 * @prot: page protection for the mapping
2223 * Maps @count pages from @pages into contiguous kernel virtual
2226 * Return: the address of the area or %NULL on failure
2228 void *vmap(struct page **pages, unsigned int count,
2229 unsigned long flags, pgprot_t prot)
2231 struct vm_struct *area;
2232 unsigned long size; /* In bytes */
2236 if (count > totalram_pages())
2239 size = (unsigned long)count << PAGE_SHIFT;
2240 area = get_vm_area_caller(size, flags, __builtin_return_address(0));
2244 if (map_vm_area(area, prot, pages)) {
2251 EXPORT_SYMBOL(vmap);
2253 static void *__vmalloc_node(unsigned long size, unsigned long align,
2254 gfp_t gfp_mask, pgprot_t prot,
2255 int node, const void *caller);
2256 static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask,
2257 pgprot_t prot, int node)
2259 struct page **pages;
2260 unsigned int nr_pages, array_size, i;
2261 const gfp_t nested_gfp = (gfp_mask & GFP_RECLAIM_MASK) | __GFP_ZERO;
2262 const gfp_t alloc_mask = gfp_mask | __GFP_NOWARN;
2263 const gfp_t highmem_mask = (gfp_mask & (GFP_DMA | GFP_DMA32)) ?
2267 nr_pages = get_vm_area_size(area) >> PAGE_SHIFT;
2268 array_size = (nr_pages * sizeof(struct page *));
2270 area->nr_pages = nr_pages;
2271 /* Please note that the recursion is strictly bounded. */
2272 if (array_size > PAGE_SIZE) {
2273 pages = __vmalloc_node(array_size, 1, nested_gfp|highmem_mask,
2274 PAGE_KERNEL, node, area->caller);
2276 pages = kmalloc_node(array_size, nested_gfp, node);
2278 area->pages = pages;
2280 remove_vm_area(area->addr);
2285 for (i = 0; i < area->nr_pages; i++) {
2288 if (node == NUMA_NO_NODE)
2289 page = alloc_page(alloc_mask|highmem_mask);
2291 page = alloc_pages_node(node, alloc_mask|highmem_mask, 0);
2293 if (unlikely(!page)) {
2294 /* Successfully allocated i pages, free them in __vunmap() */
2298 area->pages[i] = page;
2299 if (gfpflags_allow_blocking(gfp_mask|highmem_mask))
2303 if (map_vm_area(area, prot, pages))
2308 warn_alloc(gfp_mask, NULL,
2309 "vmalloc: allocation failure, allocated %ld of %ld bytes",
2310 (area->nr_pages*PAGE_SIZE), area->size);
2311 __vfree(area->addr);
2316 * __vmalloc_node_range - allocate virtually contiguous memory
2317 * @size: allocation size
2318 * @align: desired alignment
2319 * @start: vm area range start
2320 * @end: vm area range end
2321 * @gfp_mask: flags for the page level allocator
2322 * @prot: protection mask for the allocated pages
2323 * @vm_flags: additional vm area flags (e.g. %VM_NO_GUARD)
2324 * @node: node to use for allocation or NUMA_NO_NODE
2325 * @caller: caller's return address
2327 * Allocate enough pages to cover @size from the page level
2328 * allocator with @gfp_mask flags. Map them into contiguous
2329 * kernel virtual space, using a pagetable protection of @prot.
2331 * Return: the address of the area or %NULL on failure
2333 void *__vmalloc_node_range(unsigned long size, unsigned long align,
2334 unsigned long start, unsigned long end, gfp_t gfp_mask,
2335 pgprot_t prot, unsigned long vm_flags, int node,
2338 struct vm_struct *area;
2340 unsigned long real_size = size;
2342 size = PAGE_ALIGN(size);
2343 if (!size || (size >> PAGE_SHIFT) > totalram_pages())
2346 area = __get_vm_area_node(size, align, VM_ALLOC | VM_UNINITIALIZED |
2347 vm_flags, start, end, node, gfp_mask, caller);
2351 addr = __vmalloc_area_node(area, gfp_mask, prot, node);
2356 * In this function, newly allocated vm_struct has VM_UNINITIALIZED
2357 * flag. It means that vm_struct is not fully initialized.
2358 * Now, it is fully initialized, so remove this flag here.
2360 clear_vm_uninitialized_flag(area);
2362 kmemleak_vmalloc(area, size, gfp_mask);
2367 warn_alloc(gfp_mask, NULL,
2368 "vmalloc: allocation failure: %lu bytes", real_size);
2373 * This is only for performance analysis of vmalloc and stress purpose.
2374 * It is required by vmalloc test module, therefore do not use it other
2377 #ifdef CONFIG_TEST_VMALLOC_MODULE
2378 EXPORT_SYMBOL_GPL(__vmalloc_node_range);
2382 * __vmalloc_node - allocate virtually contiguous memory
2383 * @size: allocation size
2384 * @align: desired alignment
2385 * @gfp_mask: flags for the page level allocator
2386 * @prot: protection mask for the allocated pages
2387 * @node: node to use for allocation or NUMA_NO_NODE
2388 * @caller: caller's return address
2390 * Allocate enough pages to cover @size from the page level
2391 * allocator with @gfp_mask flags. Map them into contiguous
2392 * kernel virtual space, using a pagetable protection of @prot.
2394 * Reclaim modifiers in @gfp_mask - __GFP_NORETRY, __GFP_RETRY_MAYFAIL
2395 * and __GFP_NOFAIL are not supported
2397 * Any use of gfp flags outside of GFP_KERNEL should be consulted
2400 * Return: pointer to the allocated memory or %NULL on error
2402 static void *__vmalloc_node(unsigned long size, unsigned long align,
2403 gfp_t gfp_mask, pgprot_t prot,
2404 int node, const void *caller)
2406 return __vmalloc_node_range(size, align, VMALLOC_START, VMALLOC_END,
2407 gfp_mask, prot, 0, node, caller);
2410 void *__vmalloc(unsigned long size, gfp_t gfp_mask, pgprot_t prot)
2412 return __vmalloc_node(size, 1, gfp_mask, prot, NUMA_NO_NODE,
2413 __builtin_return_address(0));
2415 EXPORT_SYMBOL(__vmalloc);
2417 static inline void *__vmalloc_node_flags(unsigned long size,
2418 int node, gfp_t flags)
2420 return __vmalloc_node(size, 1, flags, PAGE_KERNEL,
2421 node, __builtin_return_address(0));
2425 void *__vmalloc_node_flags_caller(unsigned long size, int node, gfp_t flags,
2428 return __vmalloc_node(size, 1, flags, PAGE_KERNEL, node, caller);
2432 * vmalloc - allocate virtually contiguous memory
2433 * @size: allocation size
2435 * Allocate enough pages to cover @size from the page level
2436 * allocator and map them into contiguous kernel virtual space.
2438 * For tight control over page level allocator and protection flags
2439 * use __vmalloc() instead.
2441 * Return: pointer to the allocated memory or %NULL on error
2443 void *vmalloc(unsigned long size)
2445 return __vmalloc_node_flags(size, NUMA_NO_NODE,
2448 EXPORT_SYMBOL(vmalloc);
2451 * vzalloc - allocate virtually contiguous memory with zero fill
2452 * @size: allocation size
2454 * Allocate enough pages to cover @size from the page level
2455 * allocator and map them into contiguous kernel virtual space.
2456 * The memory allocated is set to zero.
2458 * For tight control over page level allocator and protection flags
2459 * use __vmalloc() instead.
2461 * Return: pointer to the allocated memory or %NULL on error
2463 void *vzalloc(unsigned long size)
2465 return __vmalloc_node_flags(size, NUMA_NO_NODE,
2466 GFP_KERNEL | __GFP_ZERO);
2468 EXPORT_SYMBOL(vzalloc);
2471 * vmalloc_user - allocate zeroed virtually contiguous memory for userspace
2472 * @size: allocation size
2474 * The resulting memory area is zeroed so it can be mapped to userspace
2475 * without leaking data.
2477 * Return: pointer to the allocated memory or %NULL on error
2479 void *vmalloc_user(unsigned long size)
2481 return __vmalloc_node_range(size, SHMLBA, VMALLOC_START, VMALLOC_END,
2482 GFP_KERNEL | __GFP_ZERO, PAGE_KERNEL,
2483 VM_USERMAP, NUMA_NO_NODE,
2484 __builtin_return_address(0));
2486 EXPORT_SYMBOL(vmalloc_user);
2489 * vmalloc_node - allocate memory on a specific node
2490 * @size: allocation size
2493 * Allocate enough pages to cover @size from the page level
2494 * allocator and map them into contiguous kernel virtual space.
2496 * For tight control over page level allocator and protection flags
2497 * use __vmalloc() instead.
2499 * Return: pointer to the allocated memory or %NULL on error
2501 void *vmalloc_node(unsigned long size, int node)
2503 return __vmalloc_node(size, 1, GFP_KERNEL, PAGE_KERNEL,
2504 node, __builtin_return_address(0));
2506 EXPORT_SYMBOL(vmalloc_node);
2509 * vzalloc_node - allocate memory on a specific node with zero fill
2510 * @size: allocation size
2513 * Allocate enough pages to cover @size from the page level
2514 * allocator and map them into contiguous kernel virtual space.
2515 * The memory allocated is set to zero.
2517 * For tight control over page level allocator and protection flags
2518 * use __vmalloc_node() instead.
2520 * Return: pointer to the allocated memory or %NULL on error
2522 void *vzalloc_node(unsigned long size, int node)
2524 return __vmalloc_node_flags(size, node,
2525 GFP_KERNEL | __GFP_ZERO);
2527 EXPORT_SYMBOL(vzalloc_node);
2530 * vmalloc_exec - allocate virtually contiguous, executable memory
2531 * @size: allocation size
2533 * Kernel-internal function to allocate enough pages to cover @size
2534 * the page level allocator and map them into contiguous and
2535 * executable kernel virtual space.
2537 * For tight control over page level allocator and protection flags
2538 * use __vmalloc() instead.
2540 * Return: pointer to the allocated memory or %NULL on error
2542 void *vmalloc_exec(unsigned long size)
2544 return __vmalloc_node_range(size, 1, VMALLOC_START, VMALLOC_END,
2545 GFP_KERNEL, PAGE_KERNEL_EXEC, VM_FLUSH_RESET_PERMS,
2546 NUMA_NO_NODE, __builtin_return_address(0));
2549 #if defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA32)
2550 #define GFP_VMALLOC32 (GFP_DMA32 | GFP_KERNEL)
2551 #elif defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA)
2552 #define GFP_VMALLOC32 (GFP_DMA | GFP_KERNEL)
2555 * 64b systems should always have either DMA or DMA32 zones. For others
2556 * GFP_DMA32 should do the right thing and use the normal zone.
2558 #define GFP_VMALLOC32 GFP_DMA32 | GFP_KERNEL
2562 * vmalloc_32 - allocate virtually contiguous memory (32bit addressable)
2563 * @size: allocation size
2565 * Allocate enough 32bit PA addressable pages to cover @size from the
2566 * page level allocator and map them into contiguous kernel virtual space.
2568 * Return: pointer to the allocated memory or %NULL on error
2570 void *vmalloc_32(unsigned long size)
2572 return __vmalloc_node(size, 1, GFP_VMALLOC32, PAGE_KERNEL,
2573 NUMA_NO_NODE, __builtin_return_address(0));
2575 EXPORT_SYMBOL(vmalloc_32);
2578 * vmalloc_32_user - allocate zeroed virtually contiguous 32bit memory
2579 * @size: allocation size
2581 * The resulting memory area is 32bit addressable and zeroed so it can be
2582 * mapped to userspace without leaking data.
2584 * Return: pointer to the allocated memory or %NULL on error
2586 void *vmalloc_32_user(unsigned long size)
2588 return __vmalloc_node_range(size, SHMLBA, VMALLOC_START, VMALLOC_END,
2589 GFP_VMALLOC32 | __GFP_ZERO, PAGE_KERNEL,
2590 VM_USERMAP, NUMA_NO_NODE,
2591 __builtin_return_address(0));
2593 EXPORT_SYMBOL(vmalloc_32_user);
2596 * small helper routine , copy contents to buf from addr.
2597 * If the page is not present, fill zero.
2600 static int aligned_vread(char *buf, char *addr, unsigned long count)
2606 unsigned long offset, length;
2608 offset = offset_in_page(addr);
2609 length = PAGE_SIZE - offset;
2612 p = vmalloc_to_page(addr);
2614 * To do safe access to this _mapped_ area, we need
2615 * lock. But adding lock here means that we need to add
2616 * overhead of vmalloc()/vfree() calles for this _debug_
2617 * interface, rarely used. Instead of that, we'll use
2618 * kmap() and get small overhead in this access function.
2622 * we can expect USER0 is not used (see vread/vwrite's
2623 * function description)
2625 void *map = kmap_atomic(p);
2626 memcpy(buf, map + offset, length);
2629 memset(buf, 0, length);
2639 static int aligned_vwrite(char *buf, char *addr, unsigned long count)
2645 unsigned long offset, length;
2647 offset = offset_in_page(addr);
2648 length = PAGE_SIZE - offset;
2651 p = vmalloc_to_page(addr);
2653 * To do safe access to this _mapped_ area, we need
2654 * lock. But adding lock here means that we need to add
2655 * overhead of vmalloc()/vfree() calles for this _debug_
2656 * interface, rarely used. Instead of that, we'll use
2657 * kmap() and get small overhead in this access function.
2661 * we can expect USER0 is not used (see vread/vwrite's
2662 * function description)
2664 void *map = kmap_atomic(p);
2665 memcpy(map + offset, buf, length);
2677 * vread() - read vmalloc area in a safe way.
2678 * @buf: buffer for reading data
2679 * @addr: vm address.
2680 * @count: number of bytes to be read.
2682 * This function checks that addr is a valid vmalloc'ed area, and
2683 * copy data from that area to a given buffer. If the given memory range
2684 * of [addr...addr+count) includes some valid address, data is copied to
2685 * proper area of @buf. If there are memory holes, they'll be zero-filled.
2686 * IOREMAP area is treated as memory hole and no copy is done.
2688 * If [addr...addr+count) doesn't includes any intersects with alive
2689 * vm_struct area, returns 0. @buf should be kernel's buffer.
2691 * Note: In usual ops, vread() is never necessary because the caller
2692 * should know vmalloc() area is valid and can use memcpy().
2693 * This is for routines which have to access vmalloc area without
2694 * any informaion, as /dev/kmem.
2696 * Return: number of bytes for which addr and buf should be increased
2697 * (same number as @count) or %0 if [addr...addr+count) doesn't
2698 * include any intersection with valid vmalloc area
2700 long vread(char *buf, char *addr, unsigned long count)
2702 struct vmap_area *va;
2703 struct vm_struct *vm;
2704 char *vaddr, *buf_start = buf;
2705 unsigned long buflen = count;
2708 /* Don't allow overflow */
2709 if ((unsigned long) addr + count < count)
2710 count = -(unsigned long) addr;
2712 spin_lock(&vmap_area_lock);
2713 list_for_each_entry(va, &vmap_area_list, list) {
2717 if (!(va->flags & VM_VM_AREA))
2721 vaddr = (char *) vm->addr;
2722 if (addr >= vaddr + get_vm_area_size(vm))
2724 while (addr < vaddr) {
2732 n = vaddr + get_vm_area_size(vm) - addr;
2735 if (!(vm->flags & VM_IOREMAP))
2736 aligned_vread(buf, addr, n);
2737 else /* IOREMAP area is treated as memory hole */
2744 spin_unlock(&vmap_area_lock);
2746 if (buf == buf_start)
2748 /* zero-fill memory holes */
2749 if (buf != buf_start + buflen)
2750 memset(buf, 0, buflen - (buf - buf_start));
2756 * vwrite() - write vmalloc area in a safe way.
2757 * @buf: buffer for source data
2758 * @addr: vm address.
2759 * @count: number of bytes to be read.
2761 * This function checks that addr is a valid vmalloc'ed area, and
2762 * copy data from a buffer to the given addr. If specified range of
2763 * [addr...addr+count) includes some valid address, data is copied from
2764 * proper area of @buf. If there are memory holes, no copy to hole.
2765 * IOREMAP area is treated as memory hole and no copy is done.
2767 * If [addr...addr+count) doesn't includes any intersects with alive
2768 * vm_struct area, returns 0. @buf should be kernel's buffer.
2770 * Note: In usual ops, vwrite() is never necessary because the caller
2771 * should know vmalloc() area is valid and can use memcpy().
2772 * This is for routines which have to access vmalloc area without
2773 * any informaion, as /dev/kmem.
2775 * Return: number of bytes for which addr and buf should be
2776 * increased (same number as @count) or %0 if [addr...addr+count)
2777 * doesn't include any intersection with valid vmalloc area
2779 long vwrite(char *buf, char *addr, unsigned long count)
2781 struct vmap_area *va;
2782 struct vm_struct *vm;
2784 unsigned long n, buflen;
2787 /* Don't allow overflow */
2788 if ((unsigned long) addr + count < count)
2789 count = -(unsigned long) addr;
2792 spin_lock(&vmap_area_lock);
2793 list_for_each_entry(va, &vmap_area_list, list) {
2797 if (!(va->flags & VM_VM_AREA))
2801 vaddr = (char *) vm->addr;
2802 if (addr >= vaddr + get_vm_area_size(vm))
2804 while (addr < vaddr) {
2811 n = vaddr + get_vm_area_size(vm) - addr;
2814 if (!(vm->flags & VM_IOREMAP)) {
2815 aligned_vwrite(buf, addr, n);
2823 spin_unlock(&vmap_area_lock);
2830 * remap_vmalloc_range_partial - map vmalloc pages to userspace
2831 * @vma: vma to cover
2832 * @uaddr: target user address to start at
2833 * @kaddr: virtual address of vmalloc kernel memory
2834 * @size: size of map area
2836 * Returns: 0 for success, -Exxx on failure
2838 * This function checks that @kaddr is a valid vmalloc'ed area,
2839 * and that it is big enough to cover the range starting at
2840 * @uaddr in @vma. Will return failure if that criteria isn't
2843 * Similar to remap_pfn_range() (see mm/memory.c)
2845 int remap_vmalloc_range_partial(struct vm_area_struct *vma, unsigned long uaddr,
2846 void *kaddr, unsigned long size)
2848 struct vm_struct *area;
2850 size = PAGE_ALIGN(size);
2852 if (!PAGE_ALIGNED(uaddr) || !PAGE_ALIGNED(kaddr))
2855 area = find_vm_area(kaddr);
2859 if (!(area->flags & VM_USERMAP))
2862 if (kaddr + size > area->addr + get_vm_area_size(area))
2866 struct page *page = vmalloc_to_page(kaddr);
2869 ret = vm_insert_page(vma, uaddr, page);
2878 vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
2882 EXPORT_SYMBOL(remap_vmalloc_range_partial);
2885 * remap_vmalloc_range - map vmalloc pages to userspace
2886 * @vma: vma to cover (map full range of vma)
2887 * @addr: vmalloc memory
2888 * @pgoff: number of pages into addr before first page to map
2890 * Returns: 0 for success, -Exxx on failure
2892 * This function checks that addr is a valid vmalloc'ed area, and
2893 * that it is big enough to cover the vma. Will return failure if
2894 * that criteria isn't met.
2896 * Similar to remap_pfn_range() (see mm/memory.c)
2898 int remap_vmalloc_range(struct vm_area_struct *vma, void *addr,
2899 unsigned long pgoff)
2901 return remap_vmalloc_range_partial(vma, vma->vm_start,
2902 addr + (pgoff << PAGE_SHIFT),
2903 vma->vm_end - vma->vm_start);
2905 EXPORT_SYMBOL(remap_vmalloc_range);
2908 * Implement a stub for vmalloc_sync_all() if the architecture chose not to
2911 void __weak vmalloc_sync_all(void)
2916 static int f(pte_t *pte, pgtable_t table, unsigned long addr, void *data)
2928 * alloc_vm_area - allocate a range of kernel address space
2929 * @size: size of the area
2930 * @ptes: returns the PTEs for the address space
2932 * Returns: NULL on failure, vm_struct on success
2934 * This function reserves a range of kernel address space, and
2935 * allocates pagetables to map that range. No actual mappings
2938 * If @ptes is non-NULL, pointers to the PTEs (in init_mm)
2939 * allocated for the VM area are returned.
2941 struct vm_struct *alloc_vm_area(size_t size, pte_t **ptes)
2943 struct vm_struct *area;
2945 area = get_vm_area_caller(size, VM_IOREMAP,
2946 __builtin_return_address(0));
2951 * This ensures that page tables are constructed for this region
2952 * of kernel virtual address space and mapped into init_mm.
2954 if (apply_to_page_range(&init_mm, (unsigned long)area->addr,
2955 size, f, ptes ? &ptes : NULL)) {
2962 EXPORT_SYMBOL_GPL(alloc_vm_area);
2964 void free_vm_area(struct vm_struct *area)
2966 struct vm_struct *ret;
2967 ret = remove_vm_area(area->addr);
2968 BUG_ON(ret != area);
2971 EXPORT_SYMBOL_GPL(free_vm_area);
2974 static struct vmap_area *node_to_va(struct rb_node *n)
2976 return rb_entry_safe(n, struct vmap_area, rb_node);
2980 * pvm_find_va_enclose_addr - find the vmap_area @addr belongs to
2981 * @addr: target address
2983 * Returns: vmap_area if it is found. If there is no such area
2984 * the first highest(reverse order) vmap_area is returned
2985 * i.e. va->va_start < addr && va->va_end < addr or NULL
2986 * if there are no any areas before @addr.
2988 static struct vmap_area *
2989 pvm_find_va_enclose_addr(unsigned long addr)
2991 struct vmap_area *va, *tmp;
2994 n = free_vmap_area_root.rb_node;
2998 tmp = rb_entry(n, struct vmap_area, rb_node);
2999 if (tmp->va_start <= addr) {
3001 if (tmp->va_end >= addr)
3014 * pvm_determine_end_from_reverse - find the highest aligned address
3015 * of free block below VMALLOC_END
3017 * in - the VA we start the search(reverse order);
3018 * out - the VA with the highest aligned end address.
3020 * Returns: determined end address within vmap_area
3022 static unsigned long
3023 pvm_determine_end_from_reverse(struct vmap_area **va, unsigned long align)
3025 unsigned long vmalloc_end = VMALLOC_END & ~(align - 1);
3029 list_for_each_entry_from_reverse((*va),
3030 &free_vmap_area_list, list) {
3031 addr = min((*va)->va_end & ~(align - 1), vmalloc_end);
3032 if ((*va)->va_start < addr)
3041 * pcpu_get_vm_areas - allocate vmalloc areas for percpu allocator
3042 * @offsets: array containing offset of each area
3043 * @sizes: array containing size of each area
3044 * @nr_vms: the number of areas to allocate
3045 * @align: alignment, all entries in @offsets and @sizes must be aligned to this
3047 * Returns: kmalloc'd vm_struct pointer array pointing to allocated
3048 * vm_structs on success, %NULL on failure
3050 * Percpu allocator wants to use congruent vm areas so that it can
3051 * maintain the offsets among percpu areas. This function allocates
3052 * congruent vmalloc areas for it with GFP_KERNEL. These areas tend to
3053 * be scattered pretty far, distance between two areas easily going up
3054 * to gigabytes. To avoid interacting with regular vmallocs, these
3055 * areas are allocated from top.
3057 * Despite its complicated look, this allocator is rather simple. It
3058 * does everything top-down and scans free blocks from the end looking
3059 * for matching base. While scanning, if any of the areas do not fit the
3060 * base address is pulled down to fit the area. Scanning is repeated till
3061 * all the areas fit and then all necessary data structures are inserted
3062 * and the result is returned.
3064 struct vm_struct **pcpu_get_vm_areas(const unsigned long *offsets,
3065 const size_t *sizes, int nr_vms,
3068 const unsigned long vmalloc_start = ALIGN(VMALLOC_START, align);
3069 const unsigned long vmalloc_end = VMALLOC_END & ~(align - 1);
3070 struct vmap_area **vas, *va;
3071 struct vm_struct **vms;
3072 int area, area2, last_area, term_area;
3073 unsigned long base, start, size, end, last_end;
3074 bool purged = false;
3077 /* verify parameters and allocate data structures */
3078 BUG_ON(offset_in_page(align) || !is_power_of_2(align));
3079 for (last_area = 0, area = 0; area < nr_vms; area++) {
3080 start = offsets[area];
3081 end = start + sizes[area];
3083 /* is everything aligned properly? */
3084 BUG_ON(!IS_ALIGNED(offsets[area], align));
3085 BUG_ON(!IS_ALIGNED(sizes[area], align));
3087 /* detect the area with the highest address */
3088 if (start > offsets[last_area])
3091 for (area2 = area + 1; area2 < nr_vms; area2++) {
3092 unsigned long start2 = offsets[area2];
3093 unsigned long end2 = start2 + sizes[area2];
3095 BUG_ON(start2 < end && start < end2);
3098 last_end = offsets[last_area] + sizes[last_area];
3100 if (vmalloc_end - vmalloc_start < last_end) {
3105 vms = kcalloc(nr_vms, sizeof(vms[0]), GFP_KERNEL);
3106 vas = kcalloc(nr_vms, sizeof(vas[0]), GFP_KERNEL);
3110 for (area = 0; area < nr_vms; area++) {
3111 vas[area] = kmem_cache_zalloc(vmap_area_cachep, GFP_KERNEL);
3112 vms[area] = kzalloc(sizeof(struct vm_struct), GFP_KERNEL);
3113 if (!vas[area] || !vms[area])
3117 spin_lock(&vmap_area_lock);
3119 /* start scanning - we scan from the top, begin with the last area */
3120 area = term_area = last_area;
3121 start = offsets[area];
3122 end = start + sizes[area];
3124 va = pvm_find_va_enclose_addr(vmalloc_end);
3125 base = pvm_determine_end_from_reverse(&va, align) - end;
3129 * base might have underflowed, add last_end before
3132 if (base + last_end < vmalloc_start + last_end)
3136 * Fitting base has not been found.
3142 * If this VA does not fit, move base downwards and recheck.
3144 if (base + start < va->va_start || base + end > va->va_end) {
3145 va = node_to_va(rb_prev(&va->rb_node));
3146 base = pvm_determine_end_from_reverse(&va, align) - end;
3152 * This area fits, move on to the previous one. If
3153 * the previous one is the terminal one, we're done.
3155 area = (area + nr_vms - 1) % nr_vms;
3156 if (area == term_area)
3159 start = offsets[area];
3160 end = start + sizes[area];
3161 va = pvm_find_va_enclose_addr(base + end);
3164 /* we've found a fitting base, insert all va's */
3165 for (area = 0; area < nr_vms; area++) {
3168 start = base + offsets[area];
3171 va = pvm_find_va_enclose_addr(start);
3172 if (WARN_ON_ONCE(va == NULL))
3173 /* It is a BUG(), but trigger recovery instead. */
3176 type = classify_va_fit_type(va, start, size);
3177 if (WARN_ON_ONCE(type == NOTHING_FIT))
3178 /* It is a BUG(), but trigger recovery instead. */
3181 ret = adjust_va_to_fit_type(va, start, size, type);
3185 /* Allocated area. */
3187 va->va_start = start;
3188 va->va_end = start + size;
3190 insert_vmap_area(va, &vmap_area_root, &vmap_area_list);
3193 spin_unlock(&vmap_area_lock);
3195 /* insert all vm's */
3196 for (area = 0; area < nr_vms; area++)
3197 setup_vmalloc_vm(vms[area], vas[area], VM_ALLOC,
3204 /* Remove previously inserted areas. */
3206 __free_vmap_area(vas[area]);
3211 spin_unlock(&vmap_area_lock);
3213 purge_vmap_area_lazy();
3216 /* Before "retry", check if we recover. */
3217 for (area = 0; area < nr_vms; area++) {
3221 vas[area] = kmem_cache_zalloc(
3222 vmap_area_cachep, GFP_KERNEL);
3231 for (area = 0; area < nr_vms; area++) {
3233 kmem_cache_free(vmap_area_cachep, vas[area]);
3244 * pcpu_free_vm_areas - free vmalloc areas for percpu allocator
3245 * @vms: vm_struct pointer array returned by pcpu_get_vm_areas()
3246 * @nr_vms: the number of allocated areas
3248 * Free vm_structs and the array allocated by pcpu_get_vm_areas().
3250 void pcpu_free_vm_areas(struct vm_struct **vms, int nr_vms)
3254 for (i = 0; i < nr_vms; i++)
3255 free_vm_area(vms[i]);
3258 #endif /* CONFIG_SMP */
3260 #ifdef CONFIG_PROC_FS
3261 static void *s_start(struct seq_file *m, loff_t *pos)
3262 __acquires(&vmap_area_lock)
3264 spin_lock(&vmap_area_lock);
3265 return seq_list_start(&vmap_area_list, *pos);
3268 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
3270 return seq_list_next(p, &vmap_area_list, pos);
3273 static void s_stop(struct seq_file *m, void *p)
3274 __releases(&vmap_area_lock)
3276 spin_unlock(&vmap_area_lock);
3279 static void show_numa_info(struct seq_file *m, struct vm_struct *v)
3281 if (IS_ENABLED(CONFIG_NUMA)) {
3282 unsigned int nr, *counters = m->private;
3287 if (v->flags & VM_UNINITIALIZED)
3289 /* Pair with smp_wmb() in clear_vm_uninitialized_flag() */
3292 memset(counters, 0, nr_node_ids * sizeof(unsigned int));
3294 for (nr = 0; nr < v->nr_pages; nr++)
3295 counters[page_to_nid(v->pages[nr])]++;
3297 for_each_node_state(nr, N_HIGH_MEMORY)
3299 seq_printf(m, " N%u=%u", nr, counters[nr]);
3303 static int s_show(struct seq_file *m, void *p)
3305 struct vmap_area *va;
3306 struct vm_struct *v;
3308 va = list_entry(p, struct vmap_area, list);
3311 * s_show can encounter race with remove_vm_area, !VM_VM_AREA on
3312 * behalf of vmap area is being tear down or vm_map_ram allocation.
3314 if (!(va->flags & VM_VM_AREA)) {
3315 seq_printf(m, "0x%pK-0x%pK %7ld %s\n",
3316 (void *)va->va_start, (void *)va->va_end,
3317 va->va_end - va->va_start,
3318 va->flags & VM_LAZY_FREE ? "unpurged vm_area" : "vm_map_ram");
3325 seq_printf(m, "0x%pK-0x%pK %7ld",
3326 v->addr, v->addr + v->size, v->size);
3329 seq_printf(m, " %pS", v->caller);
3332 seq_printf(m, " pages=%d", v->nr_pages);
3335 seq_printf(m, " phys=%pa", &v->phys_addr);
3337 if (v->flags & VM_IOREMAP)
3338 seq_puts(m, " ioremap");
3340 if (v->flags & VM_ALLOC)
3341 seq_puts(m, " vmalloc");
3343 if (v->flags & VM_MAP)
3344 seq_puts(m, " vmap");
3346 if (v->flags & VM_USERMAP)
3347 seq_puts(m, " user");
3349 if (is_vmalloc_addr(v->pages))
3350 seq_puts(m, " vpages");
3352 show_numa_info(m, v);
3357 static const struct seq_operations vmalloc_op = {
3364 static int __init proc_vmalloc_init(void)
3366 if (IS_ENABLED(CONFIG_NUMA))
3367 proc_create_seq_private("vmallocinfo", 0400, NULL,
3369 nr_node_ids * sizeof(unsigned int), NULL);
3371 proc_create_seq("vmallocinfo", 0400, NULL, &vmalloc_op);
3374 module_init(proc_vmalloc_init);