aac34c2a410b34b679e590e8e385bd574b7021b1
[platform/kernel/linux-rpi.git] / mm / vmalloc.c
1 /*
2  *  linux/mm/vmalloc.c
3  *
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
9  */
10
11 #include <linux/vmalloc.h>
12 #include <linux/mm.h>
13 #include <linux/module.h>
14 #include <linux/highmem.h>
15 #include <linux/sched/signal.h>
16 #include <linux/slab.h>
17 #include <linux/spinlock.h>
18 #include <linux/interrupt.h>
19 #include <linux/proc_fs.h>
20 #include <linux/seq_file.h>
21 #include <linux/set_memory.h>
22 #include <linux/debugobjects.h>
23 #include <linux/kallsyms.h>
24 #include <linux/list.h>
25 #include <linux/notifier.h>
26 #include <linux/rbtree.h>
27 #include <linux/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>
36
37 #include <linux/uaccess.h>
38 #include <asm/tlbflush.h>
39 #include <asm/shmparam.h>
40
41 #include "internal.h"
42
43 struct vfree_deferred {
44         struct llist_head list;
45         struct work_struct wq;
46 };
47 static DEFINE_PER_CPU(struct vfree_deferred, vfree_deferred);
48
49 static void __vunmap(const void *, int);
50
51 static void free_work(struct work_struct *w)
52 {
53         struct vfree_deferred *p = container_of(w, struct vfree_deferred, wq);
54         struct llist_node *t, *llnode;
55
56         llist_for_each_safe(llnode, t, llist_del_all(&p->list))
57                 __vunmap((void *)llnode, 1);
58 }
59
60 /*** Page table manipulation functions ***/
61
62 static void vunmap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end)
63 {
64         pte_t *pte;
65
66         pte = pte_offset_kernel(pmd, addr);
67         do {
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);
71 }
72
73 static void vunmap_pmd_range(pud_t *pud, unsigned long addr, unsigned long end)
74 {
75         pmd_t *pmd;
76         unsigned long next;
77
78         pmd = pmd_offset(pud, addr);
79         do {
80                 next = pmd_addr_end(addr, end);
81                 if (pmd_clear_huge(pmd))
82                         continue;
83                 if (pmd_none_or_clear_bad(pmd))
84                         continue;
85                 vunmap_pte_range(pmd, addr, next);
86         } while (pmd++, addr = next, addr != end);
87 }
88
89 static void vunmap_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end)
90 {
91         pud_t *pud;
92         unsigned long next;
93
94         pud = pud_offset(p4d, addr);
95         do {
96                 next = pud_addr_end(addr, end);
97                 if (pud_clear_huge(pud))
98                         continue;
99                 if (pud_none_or_clear_bad(pud))
100                         continue;
101                 vunmap_pmd_range(pud, addr, next);
102         } while (pud++, addr = next, addr != end);
103 }
104
105 static void vunmap_p4d_range(pgd_t *pgd, unsigned long addr, unsigned long end)
106 {
107         p4d_t *p4d;
108         unsigned long next;
109
110         p4d = p4d_offset(pgd, addr);
111         do {
112                 next = p4d_addr_end(addr, end);
113                 if (p4d_clear_huge(p4d))
114                         continue;
115                 if (p4d_none_or_clear_bad(p4d))
116                         continue;
117                 vunmap_pud_range(p4d, addr, next);
118         } while (p4d++, addr = next, addr != end);
119 }
120
121 static void vunmap_page_range(unsigned long addr, unsigned long end)
122 {
123         pgd_t *pgd;
124         unsigned long next;
125
126         BUG_ON(addr >= end);
127         pgd = pgd_offset_k(addr);
128         do {
129                 next = pgd_addr_end(addr, end);
130                 if (pgd_none_or_clear_bad(pgd))
131                         continue;
132                 vunmap_p4d_range(pgd, addr, next);
133         } while (pgd++, addr = next, addr != end);
134 }
135
136 static int vmap_pte_range(pmd_t *pmd, unsigned long addr,
137                 unsigned long end, pgprot_t prot, struct page **pages, int *nr)
138 {
139         pte_t *pte;
140
141         /*
142          * nr is a running index into the array which helps higher level
143          * callers keep track of where we're up to.
144          */
145
146         pte = pte_alloc_kernel(pmd, addr);
147         if (!pte)
148                 return -ENOMEM;
149         do {
150                 struct page *page = pages[*nr];
151
152                 if (WARN_ON(!pte_none(*pte)))
153                         return -EBUSY;
154                 if (WARN_ON(!page))
155                         return -ENOMEM;
156                 set_pte_at(&init_mm, addr, pte, mk_pte(page, prot));
157                 (*nr)++;
158         } while (pte++, addr += PAGE_SIZE, addr != end);
159         return 0;
160 }
161
162 static int vmap_pmd_range(pud_t *pud, unsigned long addr,
163                 unsigned long end, pgprot_t prot, struct page **pages, int *nr)
164 {
165         pmd_t *pmd;
166         unsigned long next;
167
168         pmd = pmd_alloc(&init_mm, pud, addr);
169         if (!pmd)
170                 return -ENOMEM;
171         do {
172                 next = pmd_addr_end(addr, end);
173                 if (vmap_pte_range(pmd, addr, next, prot, pages, nr))
174                         return -ENOMEM;
175         } while (pmd++, addr = next, addr != end);
176         return 0;
177 }
178
179 static int vmap_pud_range(p4d_t *p4d, unsigned long addr,
180                 unsigned long end, pgprot_t prot, struct page **pages, int *nr)
181 {
182         pud_t *pud;
183         unsigned long next;
184
185         pud = pud_alloc(&init_mm, p4d, addr);
186         if (!pud)
187                 return -ENOMEM;
188         do {
189                 next = pud_addr_end(addr, end);
190                 if (vmap_pmd_range(pud, addr, next, prot, pages, nr))
191                         return -ENOMEM;
192         } while (pud++, addr = next, addr != end);
193         return 0;
194 }
195
196 static int vmap_p4d_range(pgd_t *pgd, unsigned long addr,
197                 unsigned long end, pgprot_t prot, struct page **pages, int *nr)
198 {
199         p4d_t *p4d;
200         unsigned long next;
201
202         p4d = p4d_alloc(&init_mm, pgd, addr);
203         if (!p4d)
204                 return -ENOMEM;
205         do {
206                 next = p4d_addr_end(addr, end);
207                 if (vmap_pud_range(p4d, addr, next, prot, pages, nr))
208                         return -ENOMEM;
209         } while (p4d++, addr = next, addr != end);
210         return 0;
211 }
212
213 /*
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.
216  *
217  * Ie. pte at addr+N*PAGE_SIZE shall point to pfn corresponding to pages[N]
218  */
219 static int vmap_page_range_noflush(unsigned long start, unsigned long end,
220                                    pgprot_t prot, struct page **pages)
221 {
222         pgd_t *pgd;
223         unsigned long next;
224         unsigned long addr = start;
225         int err = 0;
226         int nr = 0;
227
228         BUG_ON(addr >= end);
229         pgd = pgd_offset_k(addr);
230         do {
231                 next = pgd_addr_end(addr, end);
232                 err = vmap_p4d_range(pgd, addr, next, prot, pages, &nr);
233                 if (err)
234                         return err;
235         } while (pgd++, addr = next, addr != end);
236
237         return nr;
238 }
239
240 static int vmap_page_range(unsigned long start, unsigned long end,
241                            pgprot_t prot, struct page **pages)
242 {
243         int ret;
244
245         ret = vmap_page_range_noflush(start, end, prot, pages);
246         flush_cache_vmap(start, end);
247         return ret;
248 }
249
250 int is_vmalloc_or_module_addr(const void *x)
251 {
252         /*
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.
256          */
257 #if defined(CONFIG_MODULES) && defined(MODULES_VADDR)
258         unsigned long addr = (unsigned long)x;
259         if (addr >= MODULES_VADDR && addr < MODULES_END)
260                 return 1;
261 #endif
262         return is_vmalloc_addr(x);
263 }
264
265 /*
266  * Walk a vmap address to the struct page it maps.
267  */
268 struct page *vmalloc_to_page(const void *vmalloc_addr)
269 {
270         unsigned long addr = (unsigned long) vmalloc_addr;
271         struct page *page = NULL;
272         pgd_t *pgd = pgd_offset_k(addr);
273         p4d_t *p4d;
274         pud_t *pud;
275         pmd_t *pmd;
276         pte_t *ptep, pte;
277
278         /*
279          * XXX we might need to change this if we add VIRTUAL_BUG_ON for
280          * architectures that do not vmalloc module space
281          */
282         VIRTUAL_BUG_ON(!is_vmalloc_or_module_addr(vmalloc_addr));
283
284         if (pgd_none(*pgd))
285                 return NULL;
286         p4d = p4d_offset(pgd, addr);
287         if (p4d_none(*p4d))
288                 return NULL;
289         pud = pud_offset(p4d, addr);
290
291         /*
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.
298          */
299         WARN_ON_ONCE(pud_bad(*pud));
300         if (pud_none(*pud) || pud_bad(*pud))
301                 return NULL;
302         pmd = pmd_offset(pud, addr);
303         WARN_ON_ONCE(pmd_bad(*pmd));
304         if (pmd_none(*pmd) || pmd_bad(*pmd))
305                 return NULL;
306
307         ptep = pte_offset_map(pmd, addr);
308         pte = *ptep;
309         if (pte_present(pte))
310                 page = pte_page(pte);
311         pte_unmap(ptep);
312         return page;
313 }
314 EXPORT_SYMBOL(vmalloc_to_page);
315
316 /*
317  * Map a vmalloc()-space virtual address to the physical page frame number.
318  */
319 unsigned long vmalloc_to_pfn(const void *vmalloc_addr)
320 {
321         return page_to_pfn(vmalloc_to_page(vmalloc_addr));
322 }
323 EXPORT_SYMBOL(vmalloc_to_pfn);
324
325
326 /*** Global kva allocator ***/
327
328 #define DEBUG_AUGMENT_PROPAGATE_CHECK 0
329
330 #define VM_LAZY_FREE    0x02
331 #define VM_VM_AREA      0x04
332
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;
339
340 /*
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
344  * free block.
345  */
346 static struct kmem_cache *vmap_area_cachep;
347
348 /*
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.
351  */
352 static LIST_HEAD(free_vmap_area_list);
353
354 /*
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.
359  *
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.
363  */
364 static struct rb_root free_vmap_area_root = RB_ROOT;
365
366 static __always_inline unsigned long
367 va_size(struct vmap_area *va)
368 {
369         return (va->va_end - va->va_start);
370 }
371
372 static __always_inline unsigned long
373 get_subtree_max_size(struct rb_node *node)
374 {
375         struct vmap_area *va;
376
377         va = rb_entry_safe(node, struct vmap_area, rb_node);
378         return va ? va->subtree_max_size : 0;
379 }
380
381 /*
382  * Gets called when remove the node and rotate.
383  */
384 static __always_inline unsigned long
385 compute_subtree_max_size(struct vmap_area *va)
386 {
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));
390 }
391
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)
395
396 static void purge_vmap_area_lazy(void);
397 static BLOCKING_NOTIFIER_HEAD(vmap_notify_list);
398 static unsigned long lazy_max_pages(void);
399
400 static struct vmap_area *__find_vmap_area(unsigned long addr)
401 {
402         struct rb_node *n = vmap_area_root.rb_node;
403
404         while (n) {
405                 struct vmap_area *va;
406
407                 va = rb_entry(n, struct vmap_area, rb_node);
408                 if (addr < va->va_start)
409                         n = n->rb_left;
410                 else if (addr >= va->va_end)
411                         n = n->rb_right;
412                 else
413                         return va;
414         }
415
416         return NULL;
417 }
418
419 /*
420  * This function returns back addresses of parent node
421  * and its left or right link for further processing.
422  */
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)
427 {
428         struct vmap_area *tmp_va;
429         struct rb_node **link;
430
431         if (root) {
432                 link = &root->rb_node;
433                 if (unlikely(!*link)) {
434                         *parent = NULL;
435                         return link;
436                 }
437         } else {
438                 link = &from;
439         }
440
441         /*
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.
445          */
446         do {
447                 tmp_va = rb_entry(*link, struct vmap_area, rb_node);
448
449                 /*
450                  * During the traversal we also do some sanity check.
451                  * Trigger the BUG() if there are sides(left/right)
452                  * or full overlaps.
453                  */
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;
460                 else
461                         BUG();
462         } while (*link);
463
464         *parent = &tmp_va->rb_node;
465         return link;
466 }
467
468 static __always_inline struct list_head *
469 get_va_next_sibling(struct rb_node *parent, struct rb_node **link)
470 {
471         struct list_head *list;
472
473         if (unlikely(!parent))
474                 /*
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.
479                  */
480                 return NULL;
481
482         list = &rb_entry(parent, struct vmap_area, rb_node)->list;
483         return (&parent->rb_right == link ? list->next : list);
484 }
485
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)
489 {
490         /*
491          * VA is still not in the list, but we can
492          * identify its future previous list_head node.
493          */
494         if (likely(parent)) {
495                 head = &rb_entry(parent, struct vmap_area, rb_node)->list;
496                 if (&parent->rb_right != link)
497                         head = head->prev;
498         }
499
500         /* Insert to the rb-tree */
501         rb_link_node(&va->rb_node, parent, link);
502         if (root == &free_vmap_area_root) {
503                 /*
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.
509                  *
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.
513                  */
514                 rb_insert_augmented(&va->rb_node,
515                         root, &free_vmap_area_rb_augment_cb);
516                 va->subtree_max_size = 0;
517         } else {
518                 rb_insert_color(&va->rb_node, root);
519         }
520
521         /* Address-sort this list */
522         list_add(&va->list, head);
523 }
524
525 static __always_inline void
526 unlink_va(struct vmap_area *va, struct rb_root *root)
527 {
528         /*
529          * During merging a VA node can be empty, therefore
530          * not linked with the tree nor list. Just check it.
531          */
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);
536                 else
537                         rb_erase(&va->rb_node, root);
538
539                 list_del(&va->list);
540                 RB_CLEAR_NODE(&va->rb_node);
541         }
542 }
543
544 #if DEBUG_AUGMENT_PROPAGATE_CHECK
545 static void
546 augment_tree_propagate_check(struct rb_node *n)
547 {
548         struct vmap_area *va;
549         struct rb_node *node;
550         unsigned long size;
551         bool found = false;
552
553         if (n == NULL)
554                 return;
555
556         va = rb_entry(n, struct vmap_area, rb_node);
557         size = va->subtree_max_size;
558         node = n;
559
560         while (node) {
561                 va = rb_entry(node, struct vmap_area, rb_node);
562
563                 if (get_subtree_max_size(node->rb_left) == size) {
564                         node = node->rb_left;
565                 } else {
566                         if (va_size(va) == size) {
567                                 found = true;
568                                 break;
569                         }
570
571                         node = node->rb_right;
572                 }
573         }
574
575         if (!found) {
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);
579         }
580
581         augment_tree_propagate_check(n->rb_left);
582         augment_tree_propagate_check(n->rb_right);
583 }
584 #endif
585
586 /*
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.
591  *
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).
596  *
597  * Please note that, it does not mean that upper parent nodes
598  * and their subtree_max_size are recalculated all the time up
599  * to the root node.
600  *
601  *       4--8
602  *        /\
603  *       /  \
604  *      /    \
605  *    2--2  8--8
606  *
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
611  * node becomes 4--6.
612  */
613 static __always_inline void
614 augment_tree_propagate_from(struct vmap_area *va)
615 {
616         struct rb_node *node = &va->rb_node;
617         unsigned long new_va_sub_max_size;
618
619         while (node) {
620                 va = rb_entry(node, struct vmap_area, rb_node);
621                 new_va_sub_max_size = compute_subtree_max_size(va);
622
623                 /*
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.
628                  */
629                 if (va->subtree_max_size == new_va_sub_max_size)
630                         break;
631
632                 va->subtree_max_size = new_va_sub_max_size;
633                 node = rb_parent(&va->rb_node);
634         }
635
636 #if DEBUG_AUGMENT_PROPAGATE_CHECK
637         augment_tree_propagate_check(free_vmap_area_root.rb_node);
638 #endif
639 }
640
641 static void
642 insert_vmap_area(struct vmap_area *va,
643         struct rb_root *root, struct list_head *head)
644 {
645         struct rb_node **link;
646         struct rb_node *parent;
647
648         link = find_va_links(va, root, NULL, &parent);
649         link_va(va, root, parent, link, head);
650 }
651
652 static void
653 insert_vmap_area_augment(struct vmap_area *va,
654         struct rb_node *from, struct rb_root *root,
655         struct list_head *head)
656 {
657         struct rb_node **link;
658         struct rb_node *parent;
659
660         if (from)
661                 link = find_va_links(va, NULL, from, &parent);
662         else
663                 link = find_va_links(va, root, NULL, &parent);
664
665         link_va(va, root, parent, link, head);
666         augment_tree_propagate_from(va);
667 }
668
669 /*
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
673  * freed.
674  */
675 static __always_inline void
676 merge_or_add_vmap_area(struct vmap_area *va,
677         struct rb_root *root, struct list_head *head)
678 {
679         struct vmap_area *sibling;
680         struct list_head *next;
681         struct rb_node **link;
682         struct rb_node *parent;
683         bool merged = false;
684
685         /*
686          * Find a place in the tree where VA potentially will be
687          * inserted, unless it is merged with its sibling/siblings.
688          */
689         link = find_va_links(va, root, NULL, &parent);
690
691         /*
692          * Get next node of VA to check if merging can be done.
693          */
694         next = get_va_next_sibling(parent, link);
695         if (unlikely(next == NULL))
696                 goto insert;
697
698         /*
699          * start            end
700          * |                |
701          * |<------VA------>|<-----Next----->|
702          *                  |                |
703          *                  start            end
704          */
705         if (next != head) {
706                 sibling = list_entry(next, struct vmap_area, list);
707                 if (sibling->va_start == va->va_end) {
708                         sibling->va_start = va->va_start;
709
710                         /* Check and update the tree if needed. */
711                         augment_tree_propagate_from(sibling);
712
713                         /* Remove this VA, it has been merged. */
714                         unlink_va(va, root);
715
716                         /* Free vmap_area object. */
717                         kmem_cache_free(vmap_area_cachep, va);
718
719                         /* Point to the new merged area. */
720                         va = sibling;
721                         merged = true;
722                 }
723         }
724
725         /*
726          * start            end
727          * |                |
728          * |<-----Prev----->|<------VA------>|
729          *                  |                |
730          *                  start            end
731          */
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;
736
737                         /* Check and update the tree if needed. */
738                         augment_tree_propagate_from(sibling);
739
740                         /* Remove this VA, it has been merged. */
741                         unlink_va(va, root);
742
743                         /* Free vmap_area object. */
744                         kmem_cache_free(vmap_area_cachep, va);
745
746                         return;
747                 }
748         }
749
750 insert:
751         if (!merged) {
752                 link_va(va, root, parent, link, head);
753                 augment_tree_propagate_from(va);
754         }
755 }
756
757 static __always_inline bool
758 is_within_this_va(struct vmap_area *va, unsigned long size,
759         unsigned long align, unsigned long vstart)
760 {
761         unsigned long nva_start_addr;
762
763         if (va->va_start > vstart)
764                 nva_start_addr = ALIGN(va->va_start, align);
765         else
766                 nva_start_addr = ALIGN(vstart, align);
767
768         /* Can be overflowed due to big size or alignment. */
769         if (nva_start_addr + size < nva_start_addr ||
770                         nva_start_addr < vstart)
771                 return false;
772
773         return (nva_start_addr + size <= va->va_end);
774 }
775
776 /*
777  * Find the first free block(lowest start address) in the tree,
778  * that will accomplish the request corresponding to passing
779  * parameters.
780  */
781 static __always_inline struct vmap_area *
782 find_vmap_lowest_match(unsigned long size,
783         unsigned long align, unsigned long vstart)
784 {
785         struct vmap_area *va;
786         struct rb_node *node;
787         unsigned long length;
788
789         /* Start from the root. */
790         node = free_vmap_area_root.rb_node;
791
792         /* Adjust the search size for alignment overhead. */
793         length = size + align - 1;
794
795         while (node) {
796                 va = rb_entry(node, struct vmap_area, rb_node);
797
798                 if (get_subtree_max_size(node->rb_left) >= length &&
799                                 vstart < va->va_start) {
800                         node = node->rb_left;
801                 } else {
802                         if (is_within_this_va(va, size, align, vstart))
803                                 return va;
804
805                         /*
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.
809                          */
810                         if (get_subtree_max_size(node->rb_right) >= length) {
811                                 node = node->rb_right;
812                                 continue;
813                         }
814
815                         /*
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.
819                          */
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))
823                                         return va;
824
825                                 if (get_subtree_max_size(node->rb_right) >= length &&
826                                                 vstart <= va->va_start) {
827                                         node = node->rb_right;
828                                         break;
829                                 }
830                         }
831                 }
832         }
833
834         return NULL;
835 }
836
837 enum fit_type {
838         NOTHING_FIT = 0,
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 */
843 };
844
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)
848 {
849         enum fit_type type;
850
851         /* Check if it is within VA. */
852         if (nva_start_addr < va->va_start ||
853                         nva_start_addr + size > va->va_end)
854                 return NOTHING_FIT;
855
856         /* Now classify. */
857         if (va->va_start == nva_start_addr) {
858                 if (va->va_end == nva_start_addr + size)
859                         type = FL_FIT_TYPE;
860                 else
861                         type = LE_FIT_TYPE;
862         } else if (va->va_end == nva_start_addr + size) {
863                 type = RE_FIT_TYPE;
864         } else {
865                 type = NE_FIT_TYPE;
866         }
867
868         return type;
869 }
870
871 static __always_inline int
872 adjust_va_to_fit_type(struct vmap_area *va,
873         unsigned long nva_start_addr, unsigned long size,
874         enum fit_type type)
875 {
876         struct vmap_area *lva;
877
878         if (type == FL_FIT_TYPE) {
879                 /*
880                  * No need to split VA, it fully fits.
881                  *
882                  * |               |
883                  * V      NVA      V
884                  * |---------------|
885                  */
886                 unlink_va(va, &free_vmap_area_root);
887                 kmem_cache_free(vmap_area_cachep, va);
888         } else if (type == LE_FIT_TYPE) {
889                 /*
890                  * Split left edge of fit VA.
891                  *
892                  * |       |
893                  * V  NVA  V   R
894                  * |-------|-------|
895                  */
896                 va->va_start += size;
897         } else if (type == RE_FIT_TYPE) {
898                 /*
899                  * Split right edge of fit VA.
900                  *
901                  *         |       |
902                  *     L   V  NVA  V
903                  * |-------|-------|
904                  */
905                 va->va_end = nva_start_addr;
906         } else if (type == NE_FIT_TYPE) {
907                 /*
908                  * Split no edge of fit VA.
909                  *
910                  *     |       |
911                  *   L V  NVA  V R
912                  * |---|-------|---|
913                  */
914                 lva = kmem_cache_alloc(vmap_area_cachep, GFP_NOWAIT);
915                 if (unlikely(!lva))
916                         return -1;
917
918                 /*
919                  * Build the remainder.
920                  */
921                 lva->va_start = va->va_start;
922                 lva->va_end = nva_start_addr;
923
924                 /*
925                  * Shrink this VA to remaining size.
926                  */
927                 va->va_start = nva_start_addr + size;
928         } else {
929                 return -1;
930         }
931
932         if (type != FL_FIT_TYPE) {
933                 augment_tree_propagate_from(va);
934
935                 if (type == NE_FIT_TYPE)
936                         insert_vmap_area_augment(lva, &va->rb_node,
937                                 &free_vmap_area_root, &free_vmap_area_list);
938         }
939
940         return 0;
941 }
942
943 /*
944  * Returns a start address of the newly allocated area, if success.
945  * Otherwise a vend is returned that indicates failure.
946  */
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)
950 {
951         unsigned long nva_start_addr;
952         struct vmap_area *va;
953         enum fit_type type;
954         int ret;
955
956         va = find_vmap_lowest_match(size, align, vstart);
957         if (unlikely(!va))
958                 return vend;
959
960         if (va->va_start > vstart)
961                 nva_start_addr = ALIGN(va->va_start, align);
962         else
963                 nva_start_addr = ALIGN(vstart, align);
964
965         /* Check the "vend" restriction. */
966         if (nva_start_addr + size > vend)
967                 return vend;
968
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))
972                 return vend;
973
974         /* Update the free vmap_area. */
975         ret = adjust_va_to_fit_type(va, nva_start_addr, size, type);
976         if (ret)
977                 return vend;
978
979         return nva_start_addr;
980 }
981
982 /*
983  * Allocate a region of KVA of the specified size and alignment, within the
984  * vstart and vend.
985  */
986 static struct vmap_area *alloc_vmap_area(unsigned long size,
987                                 unsigned long align,
988                                 unsigned long vstart, unsigned long vend,
989                                 int node, gfp_t gfp_mask)
990 {
991         struct vmap_area *va;
992         unsigned long addr;
993         int purged = 0;
994
995         BUG_ON(!size);
996         BUG_ON(offset_in_page(size));
997         BUG_ON(!is_power_of_2(align));
998
999         if (unlikely(!vmap_initialized))
1000                 return ERR_PTR(-EBUSY);
1001
1002         might_sleep();
1003
1004         va = kmem_cache_alloc_node(vmap_area_cachep,
1005                         gfp_mask & GFP_RECLAIM_MASK, node);
1006         if (unlikely(!va))
1007                 return ERR_PTR(-ENOMEM);
1008
1009         /*
1010          * Only scan the relevant parts containing pointers to other objects
1011          * to avoid false negatives.
1012          */
1013         kmemleak_scan_area(&va->rb_node, SIZE_MAX, gfp_mask & GFP_RECLAIM_MASK);
1014
1015 retry:
1016         spin_lock(&vmap_area_lock);
1017
1018         /*
1019          * If an allocation fails, the "vend" address is
1020          * returned. Therefore trigger the overflow path.
1021          */
1022         addr = __alloc_vmap_area(size, align, vstart, vend, node);
1023         if (unlikely(addr == vend))
1024                 goto overflow;
1025
1026         va->va_start = addr;
1027         va->va_end = addr + size;
1028         va->flags = 0;
1029         insert_vmap_area(va, &vmap_area_root, &vmap_area_list);
1030
1031         spin_unlock(&vmap_area_lock);
1032
1033         BUG_ON(!IS_ALIGNED(va->va_start, align));
1034         BUG_ON(va->va_start < vstart);
1035         BUG_ON(va->va_end > vend);
1036
1037         return va;
1038
1039 overflow:
1040         spin_unlock(&vmap_area_lock);
1041         if (!purged) {
1042                 purge_vmap_area_lazy();
1043                 purged = 1;
1044                 goto retry;
1045         }
1046
1047         if (gfpflags_allow_blocking(gfp_mask)) {
1048                 unsigned long freed = 0;
1049                 blocking_notifier_call_chain(&vmap_notify_list, 0, &freed);
1050                 if (freed > 0) {
1051                         purged = 0;
1052                         goto retry;
1053                 }
1054         }
1055
1056         if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit())
1057                 pr_warn("vmap allocation for size %lu failed: use vmalloc=<size> to increase size\n",
1058                         size);
1059
1060         kmem_cache_free(vmap_area_cachep, va);
1061         return ERR_PTR(-EBUSY);
1062 }
1063
1064 int register_vmap_purge_notifier(struct notifier_block *nb)
1065 {
1066         return blocking_notifier_chain_register(&vmap_notify_list, nb);
1067 }
1068 EXPORT_SYMBOL_GPL(register_vmap_purge_notifier);
1069
1070 int unregister_vmap_purge_notifier(struct notifier_block *nb)
1071 {
1072         return blocking_notifier_chain_unregister(&vmap_notify_list, nb);
1073 }
1074 EXPORT_SYMBOL_GPL(unregister_vmap_purge_notifier);
1075
1076 static void __free_vmap_area(struct vmap_area *va)
1077 {
1078         BUG_ON(RB_EMPTY_NODE(&va->rb_node));
1079
1080         /*
1081          * Remove from the busy tree/list.
1082          */
1083         unlink_va(va, &vmap_area_root);
1084
1085         /*
1086          * Merge VA with its neighbors, otherwise just add it.
1087          */
1088         merge_or_add_vmap_area(va,
1089                 &free_vmap_area_root, &free_vmap_area_list);
1090 }
1091
1092 /*
1093  * Free a region of KVA allocated by alloc_vmap_area
1094  */
1095 static void free_vmap_area(struct vmap_area *va)
1096 {
1097         spin_lock(&vmap_area_lock);
1098         __free_vmap_area(va);
1099         spin_unlock(&vmap_area_lock);
1100 }
1101
1102 /*
1103  * Clear the pagetable entries of a given vmap_area
1104  */
1105 static void unmap_vmap_area(struct vmap_area *va)
1106 {
1107         vunmap_page_range(va->va_start, va->va_end);
1108 }
1109
1110 /*
1111  * lazy_max_pages is the maximum amount of virtual address space we gather up
1112  * before attempting to purge with a TLB flush.
1113  *
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.
1125  */
1126 static unsigned long lazy_max_pages(void)
1127 {
1128         unsigned int log;
1129
1130         log = fls(num_online_cpus());
1131
1132         return log * (32UL * 1024 * 1024 / PAGE_SIZE);
1133 }
1134
1135 static atomic_long_t vmap_lazy_nr = ATOMIC_LONG_INIT(0);
1136
1137 /*
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.
1141  */
1142 static DEFINE_MUTEX(vmap_purge_lock);
1143
1144 /* for per-CPU blocks */
1145 static void purge_fragmented_blocks_allcpus(void);
1146
1147 /*
1148  * called before a call to iounmap() if the caller wants vm_area_struct's
1149  * immediately freed.
1150  */
1151 void set_iounmap_nonlazy(void)
1152 {
1153         atomic_long_set(&vmap_lazy_nr, lazy_max_pages()+1);
1154 }
1155
1156 /*
1157  * Purges all lazily-freed vmap areas.
1158  */
1159 static bool __purge_vmap_area_lazy(unsigned long start, unsigned long end)
1160 {
1161         unsigned long resched_threshold;
1162         struct llist_node *valist;
1163         struct vmap_area *va;
1164         struct vmap_area *n_va;
1165
1166         lockdep_assert_held(&vmap_purge_lock);
1167
1168         valist = llist_del_all(&vmap_purge_list);
1169         if (unlikely(valist == NULL))
1170                 return false;
1171
1172         /*
1173          * TODO: to calculate a flush range without looping.
1174          * The list can be up to lazy_max_pages() elements.
1175          */
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)
1180                         end = va->va_end;
1181         }
1182
1183         flush_tlb_kernel_range(start, end);
1184         resched_threshold = lazy_max_pages() << 1;
1185
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;
1189
1190                 __free_vmap_area(va);
1191                 atomic_long_sub(nr, &vmap_lazy_nr);
1192
1193                 if (atomic_long_read(&vmap_lazy_nr) < resched_threshold)
1194                         cond_resched_lock(&vmap_area_lock);
1195         }
1196         spin_unlock(&vmap_area_lock);
1197         return true;
1198 }
1199
1200 /*
1201  * Kick off a purge of the outstanding lazy areas. Don't bother if somebody
1202  * is already purging.
1203  */
1204 static void try_purge_vmap_area_lazy(void)
1205 {
1206         if (mutex_trylock(&vmap_purge_lock)) {
1207                 __purge_vmap_area_lazy(ULONG_MAX, 0);
1208                 mutex_unlock(&vmap_purge_lock);
1209         }
1210 }
1211
1212 /*
1213  * Kick off a purge of the outstanding lazy areas.
1214  */
1215 static void purge_vmap_area_lazy(void)
1216 {
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);
1221 }
1222
1223 /*
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
1226  * previously.
1227  */
1228 static void free_vmap_area_noflush(struct vmap_area *va)
1229 {
1230         unsigned long nr_lazy;
1231
1232         nr_lazy = atomic_long_add_return((va->va_end - va->va_start) >>
1233                                 PAGE_SHIFT, &vmap_lazy_nr);
1234
1235         /* After this point, we may free va at any time */
1236         llist_add(&va->purge_list, &vmap_purge_list);
1237
1238         if (unlikely(nr_lazy > lazy_max_pages()))
1239                 try_purge_vmap_area_lazy();
1240 }
1241
1242 /*
1243  * Free and unmap a vmap area
1244  */
1245 static void free_unmap_vmap_area(struct vmap_area *va)
1246 {
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);
1251
1252         free_vmap_area_noflush(va);
1253 }
1254
1255 static struct vmap_area *find_vmap_area(unsigned long addr)
1256 {
1257         struct vmap_area *va;
1258
1259         spin_lock(&vmap_area_lock);
1260         va = __find_vmap_area(addr);
1261         spin_unlock(&vmap_area_lock);
1262
1263         return va;
1264 }
1265
1266 /*** Per cpu kva allocator ***/
1267
1268 /*
1269  * vmap space is limited especially on 32 bit architectures. Ensure there is
1270  * room for at least 16 percpu vmap blocks per CPU.
1271  */
1272 /*
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)
1276  */
1277 #if BITS_PER_LONG == 32
1278 #define VMALLOC_SPACE           (128UL*1024*1024)
1279 #else
1280 #define VMALLOC_SPACE           (128UL*1024*1024*1024)
1281 #endif
1282
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))
1293
1294 #define VMAP_BLOCK_SIZE         (VMAP_BBMAP_BITS * PAGE_SIZE)
1295
1296 struct vmap_block_queue {
1297         spinlock_t lock;
1298         struct list_head free;
1299 };
1300
1301 struct vmap_block {
1302         spinlock_t lock;
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;
1309 };
1310
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);
1313
1314 /*
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.
1318  */
1319 static DEFINE_SPINLOCK(vmap_block_tree_lock);
1320 static RADIX_TREE(vmap_block_tree, GFP_ATOMIC);
1321
1322 /*
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
1326  * big problem.
1327  */
1328
1329 static unsigned long addr_to_vb_idx(unsigned long addr)
1330 {
1331         addr -= VMALLOC_START & ~(VMAP_BLOCK_SIZE-1);
1332         addr /= VMAP_BLOCK_SIZE;
1333         return addr;
1334 }
1335
1336 static void *vmap_block_vaddr(unsigned long va_start, unsigned long pages_off)
1337 {
1338         unsigned long addr;
1339
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;
1343 }
1344
1345 /**
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
1350  *
1351  * Return: virtual address in a newly allocated block or ERR_PTR(-errno)
1352  */
1353 static void *new_vmap_block(unsigned int order, gfp_t gfp_mask)
1354 {
1355         struct vmap_block_queue *vbq;
1356         struct vmap_block *vb;
1357         struct vmap_area *va;
1358         unsigned long vb_idx;
1359         int node, err;
1360         void *vaddr;
1361
1362         node = numa_node_id();
1363
1364         vb = kmalloc_node(sizeof(struct vmap_block),
1365                         gfp_mask & GFP_RECLAIM_MASK, node);
1366         if (unlikely(!vb))
1367                 return ERR_PTR(-ENOMEM);
1368
1369         va = alloc_vmap_area(VMAP_BLOCK_SIZE, VMAP_BLOCK_SIZE,
1370                                         VMALLOC_START, VMALLOC_END,
1371                                         node, gfp_mask);
1372         if (IS_ERR(va)) {
1373                 kfree(vb);
1374                 return ERR_CAST(va);
1375         }
1376
1377         err = radix_tree_preload(gfp_mask);
1378         if (unlikely(err)) {
1379                 kfree(vb);
1380                 free_vmap_area(va);
1381                 return ERR_PTR(err);
1382         }
1383
1384         vaddr = vmap_block_vaddr(va->va_start, 0);
1385         spin_lock_init(&vb->lock);
1386         vb->va = va;
1387         /* At least something should be left free */
1388         BUG_ON(VMAP_BBMAP_BITS <= (1UL << order));
1389         vb->free = VMAP_BBMAP_BITS - (1UL << order);
1390         vb->dirty = 0;
1391         vb->dirty_min = VMAP_BBMAP_BITS;
1392         vb->dirty_max = 0;
1393         INIT_LIST_HEAD(&vb->free_list);
1394
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);
1399         BUG_ON(err);
1400         radix_tree_preload_end();
1401
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);
1407
1408         return vaddr;
1409 }
1410
1411 static void free_vmap_block(struct vmap_block *vb)
1412 {
1413         struct vmap_block *tmp;
1414         unsigned long vb_idx;
1415
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);
1420         BUG_ON(tmp != vb);
1421
1422         free_vmap_area_noflush(vb->va);
1423         kfree_rcu(vb, rcu_head);
1424 }
1425
1426 static void purge_fragmented_blocks(int cpu)
1427 {
1428         LIST_HEAD(purge);
1429         struct vmap_block *vb;
1430         struct vmap_block *n_vb;
1431         struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu);
1432
1433         rcu_read_lock();
1434         list_for_each_entry_rcu(vb, &vbq->free, free_list) {
1435
1436                 if (!(vb->free + vb->dirty == VMAP_BBMAP_BITS && vb->dirty != VMAP_BBMAP_BITS))
1437                         continue;
1438
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 */
1443                         vb->dirty_min = 0;
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);
1450                 } else
1451                         spin_unlock(&vb->lock);
1452         }
1453         rcu_read_unlock();
1454
1455         list_for_each_entry_safe(vb, n_vb, &purge, purge) {
1456                 list_del(&vb->purge);
1457                 free_vmap_block(vb);
1458         }
1459 }
1460
1461 static void purge_fragmented_blocks_allcpus(void)
1462 {
1463         int cpu;
1464
1465         for_each_possible_cpu(cpu)
1466                 purge_fragmented_blocks(cpu);
1467 }
1468
1469 static void *vb_alloc(unsigned long size, gfp_t gfp_mask)
1470 {
1471         struct vmap_block_queue *vbq;
1472         struct vmap_block *vb;
1473         void *vaddr = NULL;
1474         unsigned int order;
1475
1476         BUG_ON(offset_in_page(size));
1477         BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
1478         if (WARN_ON(size == 0)) {
1479                 /*
1480                  * Allocating 0 bytes isn't what caller wants since
1481                  * get_order(0) returns funny result. Just warn and terminate
1482                  * early.
1483                  */
1484                 return NULL;
1485         }
1486         order = get_order(size);
1487
1488         rcu_read_lock();
1489         vbq = &get_cpu_var(vmap_block_queue);
1490         list_for_each_entry_rcu(vb, &vbq->free, free_list) {
1491                 unsigned long pages_off;
1492
1493                 spin_lock(&vb->lock);
1494                 if (vb->free < (1UL << order)) {
1495                         spin_unlock(&vb->lock);
1496                         continue;
1497                 }
1498
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);
1506                 }
1507
1508                 spin_unlock(&vb->lock);
1509                 break;
1510         }
1511
1512         put_cpu_var(vmap_block_queue);
1513         rcu_read_unlock();
1514
1515         /* Allocate new block if nothing was found */
1516         if (!vaddr)
1517                 vaddr = new_vmap_block(order, gfp_mask);
1518
1519         return vaddr;
1520 }
1521
1522 static void vb_free(const void *addr, unsigned long size)
1523 {
1524         unsigned long offset;
1525         unsigned long vb_idx;
1526         unsigned int order;
1527         struct vmap_block *vb;
1528
1529         BUG_ON(offset_in_page(size));
1530         BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
1531
1532         flush_cache_vunmap((unsigned long)addr, (unsigned long)addr + size);
1533
1534         order = get_order(size);
1535
1536         offset = (unsigned long)addr & (VMAP_BLOCK_SIZE - 1);
1537         offset >>= PAGE_SHIFT;
1538
1539         vb_idx = addr_to_vb_idx((unsigned long)addr);
1540         rcu_read_lock();
1541         vb = radix_tree_lookup(&vmap_block_tree, vb_idx);
1542         rcu_read_unlock();
1543         BUG_ON(!vb);
1544
1545         vunmap_page_range((unsigned long)addr, (unsigned long)addr + size);
1546
1547         if (debug_pagealloc_enabled())
1548                 flush_tlb_kernel_range((unsigned long)addr,
1549                                         (unsigned long)addr + size);
1550
1551         spin_lock(&vb->lock);
1552
1553         /* Expand dirty range */
1554         vb->dirty_min = min(vb->dirty_min, offset);
1555         vb->dirty_max = max(vb->dirty_max, offset + (1UL << order));
1556
1557         vb->dirty += 1UL << order;
1558         if (vb->dirty == VMAP_BBMAP_BITS) {
1559                 BUG_ON(vb->free);
1560                 spin_unlock(&vb->lock);
1561                 free_vmap_block(vb);
1562         } else
1563                 spin_unlock(&vb->lock);
1564 }
1565
1566 static void _vm_unmap_aliases(unsigned long start, unsigned long end, int flush)
1567 {
1568         int cpu;
1569
1570         if (unlikely(!vmap_initialized))
1571                 return;
1572
1573         might_sleep();
1574
1575         for_each_possible_cpu(cpu) {
1576                 struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu);
1577                 struct vmap_block *vb;
1578
1579                 rcu_read_lock();
1580                 list_for_each_entry_rcu(vb, &vbq->free, free_list) {
1581                         spin_lock(&vb->lock);
1582                         if (vb->dirty) {
1583                                 unsigned long va_start = vb->va->va_start;
1584                                 unsigned long s, e;
1585
1586                                 s = va_start + (vb->dirty_min << PAGE_SHIFT);
1587                                 e = va_start + (vb->dirty_max << PAGE_SHIFT);
1588
1589                                 start = min(s, start);
1590                                 end   = max(e, end);
1591
1592                                 flush = 1;
1593                         }
1594                         spin_unlock(&vb->lock);
1595                 }
1596                 rcu_read_unlock();
1597         }
1598
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);
1604 }
1605
1606 /**
1607  * vm_unmap_aliases - unmap outstanding lazy aliases in the vmap layer
1608  *
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).
1614  *
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.
1618  */
1619 void vm_unmap_aliases(void)
1620 {
1621         unsigned long start = ULONG_MAX, end = 0;
1622         int flush = 0;
1623
1624         _vm_unmap_aliases(start, end, flush);
1625 }
1626 EXPORT_SYMBOL_GPL(vm_unmap_aliases);
1627
1628 /**
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)
1632  */
1633 void vm_unmap_ram(const void *mem, unsigned int count)
1634 {
1635         unsigned long size = (unsigned long)count << PAGE_SHIFT;
1636         unsigned long addr = (unsigned long)mem;
1637         struct vmap_area *va;
1638
1639         might_sleep();
1640         BUG_ON(!addr);
1641         BUG_ON(addr < VMALLOC_START);
1642         BUG_ON(addr > VMALLOC_END);
1643         BUG_ON(!PAGE_ALIGNED(addr));
1644
1645         if (likely(count <= VMAP_MAX_ALLOC)) {
1646                 debug_check_no_locks_freed(mem, size);
1647                 vb_free(mem, size);
1648                 return;
1649         }
1650
1651         va = find_vmap_area(addr);
1652         BUG_ON(!va);
1653         debug_check_no_locks_freed((void *)va->va_start,
1654                                     (va->va_end - va->va_start));
1655         free_unmap_vmap_area(va);
1656 }
1657 EXPORT_SYMBOL(vm_unmap_ram);
1658
1659 /**
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
1665  *
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.
1671  *
1672  * Returns: a pointer to the address that has been mapped, or %NULL on failure
1673  */
1674 void *vm_map_ram(struct page **pages, unsigned int count, int node, pgprot_t prot)
1675 {
1676         unsigned long size = (unsigned long)count << PAGE_SHIFT;
1677         unsigned long addr;
1678         void *mem;
1679
1680         if (likely(count <= VMAP_MAX_ALLOC)) {
1681                 mem = vb_alloc(size, GFP_KERNEL);
1682                 if (IS_ERR(mem))
1683                         return NULL;
1684                 addr = (unsigned long)mem;
1685         } else {
1686                 struct vmap_area *va;
1687                 va = alloc_vmap_area(size, PAGE_SIZE,
1688                                 VMALLOC_START, VMALLOC_END, node, GFP_KERNEL);
1689                 if (IS_ERR(va))
1690                         return NULL;
1691
1692                 addr = va->va_start;
1693                 mem = (void *)addr;
1694         }
1695         if (vmap_page_range(addr, addr + size, prot, pages) < 0) {
1696                 vm_unmap_ram(mem, count);
1697                 return NULL;
1698         }
1699         return mem;
1700 }
1701 EXPORT_SYMBOL(vm_map_ram);
1702
1703 static struct vm_struct *vmlist __initdata;
1704
1705 /**
1706  * vm_area_add_early - add vmap area early during boot
1707  * @vm: vm_struct to add
1708  *
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.
1712  *
1713  * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING.
1714  */
1715 void __init vm_area_add_early(struct vm_struct *vm)
1716 {
1717         struct vm_struct *tmp, **p;
1718
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);
1723                         break;
1724                 } else
1725                         BUG_ON(tmp->addr + tmp->size > vm->addr);
1726         }
1727         vm->next = *p;
1728         *p = vm;
1729 }
1730
1731 /**
1732  * vm_area_register_early - register vmap area early during boot
1733  * @vm: vm_struct to register
1734  * @align: requested alignment
1735  *
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.
1740  *
1741  * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING.
1742  */
1743 void __init vm_area_register_early(struct vm_struct *vm, size_t align)
1744 {
1745         static size_t vm_init_off __initdata;
1746         unsigned long addr;
1747
1748         addr = ALIGN(VMALLOC_START + vm_init_off, align);
1749         vm_init_off = PFN_ALIGN(addr + vm->size) - VMALLOC_START;
1750
1751         vm->addr = (void *)addr;
1752
1753         vm_area_add_early(vm);
1754 }
1755
1756 static void vmap_init_free_space(void)
1757 {
1758         unsigned long vmap_start = 1;
1759         const unsigned long vmap_end = ULONG_MAX;
1760         struct vmap_area *busy, *free;
1761
1762         /*
1763          *     B     F     B     B     B     F
1764          * -|-----|.....|-----|-----|-----|.....|-
1765          *  |           The KVA space           |
1766          *  |<--------------------------------->|
1767          */
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;
1774
1775                                 insert_vmap_area_augment(free, NULL,
1776                                         &free_vmap_area_root,
1777                                                 &free_vmap_area_list);
1778                         }
1779                 }
1780
1781                 vmap_start = busy->va_end;
1782         }
1783
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;
1789
1790                         insert_vmap_area_augment(free, NULL,
1791                                 &free_vmap_area_root,
1792                                         &free_vmap_area_list);
1793                 }
1794         }
1795 }
1796
1797 void __init vmalloc_init(void)
1798 {
1799         struct vmap_area *va;
1800         struct vm_struct *tmp;
1801         int i;
1802
1803         /*
1804          * Create the cache for vmap_area objects.
1805          */
1806         vmap_area_cachep = KMEM_CACHE(vmap_area, SLAB_PANIC);
1807
1808         for_each_possible_cpu(i) {
1809                 struct vmap_block_queue *vbq;
1810                 struct vfree_deferred *p;
1811
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);
1818         }
1819
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))
1824                         continue;
1825
1826                 va->flags = VM_VM_AREA;
1827                 va->va_start = (unsigned long)tmp->addr;
1828                 va->va_end = va->va_start + tmp->size;
1829                 va->vm = tmp;
1830                 insert_vmap_area(va, &vmap_area_root, &vmap_area_list);
1831         }
1832
1833         /*
1834          * Now we can initialize a free vmap space.
1835          */
1836         vmap_init_free_space();
1837         vmap_initialized = true;
1838 }
1839
1840 /**
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
1846  *
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
1849  * friends.
1850  *
1851  * NOTE:
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.
1855  *
1856  * RETURNS:
1857  * The number of pages mapped on success, -errno on failure.
1858  */
1859 int map_kernel_range_noflush(unsigned long addr, unsigned long size,
1860                              pgprot_t prot, struct page **pages)
1861 {
1862         return vmap_page_range_noflush(addr, addr + size, prot, pages);
1863 }
1864
1865 /**
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
1869  *
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
1872  * friends.
1873  *
1874  * NOTE:
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.
1878  */
1879 void unmap_kernel_range_noflush(unsigned long addr, unsigned long size)
1880 {
1881         vunmap_page_range(addr, addr + size);
1882 }
1883 EXPORT_SYMBOL_GPL(unmap_kernel_range_noflush);
1884
1885 /**
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
1889  *
1890  * Similar to unmap_kernel_range_noflush() but flushes vcache before
1891  * the unmapping and tlb after.
1892  */
1893 void unmap_kernel_range(unsigned long addr, unsigned long size)
1894 {
1895         unsigned long end = addr + size;
1896
1897         flush_cache_vunmap(addr, end);
1898         vunmap_page_range(addr, end);
1899         flush_tlb_kernel_range(addr, end);
1900 }
1901 EXPORT_SYMBOL_GPL(unmap_kernel_range);
1902
1903 int map_vm_area(struct vm_struct *area, pgprot_t prot, struct page **pages)
1904 {
1905         unsigned long addr = (unsigned long)area->addr;
1906         unsigned long end = addr + get_vm_area_size(area);
1907         int err;
1908
1909         err = vmap_page_range(addr, end, prot, pages);
1910
1911         return err > 0 ? 0 : err;
1912 }
1913 EXPORT_SYMBOL_GPL(map_vm_area);
1914
1915 static void setup_vmalloc_vm(struct vm_struct *vm, struct vmap_area *va,
1916                               unsigned long flags, const void *caller)
1917 {
1918         spin_lock(&vmap_area_lock);
1919         vm->flags = flags;
1920         vm->addr = (void *)va->va_start;
1921         vm->size = va->va_end - va->va_start;
1922         vm->caller = caller;
1923         va->vm = vm;
1924         va->flags |= VM_VM_AREA;
1925         spin_unlock(&vmap_area_lock);
1926 }
1927
1928 static void clear_vm_uninitialized_flag(struct vm_struct *vm)
1929 {
1930         /*
1931          * Before removing VM_UNINITIALIZED,
1932          * we should make sure that vm has proper values.
1933          * Pair with smp_rmb() in show_numa_info().
1934          */
1935         smp_wmb();
1936         vm->flags &= ~VM_UNINITIALIZED;
1937 }
1938
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)
1942 {
1943         struct vmap_area *va;
1944         struct vm_struct *area;
1945
1946         BUG_ON(in_interrupt());
1947         size = PAGE_ALIGN(size);
1948         if (unlikely(!size))
1949                 return NULL;
1950
1951         if (flags & VM_IOREMAP)
1952                 align = 1ul << clamp_t(int, get_count_order_long(size),
1953                                        PAGE_SHIFT, IOREMAP_MAX_ORDER);
1954
1955         area = kzalloc_node(sizeof(*area), gfp_mask & GFP_RECLAIM_MASK, node);
1956         if (unlikely(!area))
1957                 return NULL;
1958
1959         if (!(flags & VM_NO_GUARD))
1960                 size += PAGE_SIZE;
1961
1962         va = alloc_vmap_area(size, align, start, end, node, gfp_mask);
1963         if (IS_ERR(va)) {
1964                 kfree(area);
1965                 return NULL;
1966         }
1967
1968         setup_vmalloc_vm(area, va, flags, caller);
1969
1970         return area;
1971 }
1972
1973 struct vm_struct *__get_vm_area(unsigned long size, unsigned long flags,
1974                                 unsigned long start, unsigned long end)
1975 {
1976         return __get_vm_area_node(size, 1, flags, start, end, NUMA_NO_NODE,
1977                                   GFP_KERNEL, __builtin_return_address(0));
1978 }
1979 EXPORT_SYMBOL_GPL(__get_vm_area);
1980
1981 struct vm_struct *__get_vm_area_caller(unsigned long size, unsigned long flags,
1982                                        unsigned long start, unsigned long end,
1983                                        const void *caller)
1984 {
1985         return __get_vm_area_node(size, 1, flags, start, end, NUMA_NO_NODE,
1986                                   GFP_KERNEL, caller);
1987 }
1988
1989 /**
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
1993  *
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.
1997  *
1998  * Return: the area descriptor on success or %NULL on failure.
1999  */
2000 struct vm_struct *get_vm_area(unsigned long size, unsigned long flags)
2001 {
2002         return __get_vm_area_node(size, 1, flags, VMALLOC_START, VMALLOC_END,
2003                                   NUMA_NO_NODE, GFP_KERNEL,
2004                                   __builtin_return_address(0));
2005 }
2006
2007 struct vm_struct *get_vm_area_caller(unsigned long size, unsigned long flags,
2008                                 const void *caller)
2009 {
2010         return __get_vm_area_node(size, 1, flags, VMALLOC_START, VMALLOC_END,
2011                                   NUMA_NO_NODE, GFP_KERNEL, caller);
2012 }
2013
2014 /**
2015  * find_vm_area - find a continuous kernel virtual area
2016  * @addr:         base address
2017  *
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
2020  * pointer valid.
2021  *
2022  * Return: pointer to the found area or %NULL on faulure
2023  */
2024 struct vm_struct *find_vm_area(const void *addr)
2025 {
2026         struct vmap_area *va;
2027
2028         va = find_vmap_area((unsigned long)addr);
2029         if (va && va->flags & VM_VM_AREA)
2030                 return va->vm;
2031
2032         return NULL;
2033 }
2034
2035 /**
2036  * remove_vm_area - find and remove a continuous kernel virtual area
2037  * @addr:           base address
2038  *
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.
2042  *
2043  * Return: pointer to the found area or %NULL on faulure
2044  */
2045 struct vm_struct *remove_vm_area(const void *addr)
2046 {
2047         struct vmap_area *va;
2048
2049         might_sleep();
2050
2051         va = find_vmap_area((unsigned long)addr);
2052         if (va && va->flags & VM_VM_AREA) {
2053                 struct vm_struct *vm = va->vm;
2054
2055                 spin_lock(&vmap_area_lock);
2056                 va->vm = NULL;
2057                 va->flags &= ~VM_VM_AREA;
2058                 va->flags |= VM_LAZY_FREE;
2059                 spin_unlock(&vmap_area_lock);
2060
2061                 kasan_free_shadow(vm);
2062                 free_unmap_vmap_area(va);
2063
2064                 return vm;
2065         }
2066         return NULL;
2067 }
2068
2069 static inline void set_area_direct_map(const struct vm_struct *area,
2070                                        int (*set_direct_map)(struct page *page))
2071 {
2072         int i;
2073
2074         for (i = 0; i < area->nr_pages; i++)
2075                 if (page_address(area->pages[i]))
2076                         set_direct_map(area->pages[i]);
2077 }
2078
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)
2081 {
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;
2085         int i;
2086
2087         /*
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.
2092          */
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);
2096         }
2097
2098         remove_vm_area(area->addr);
2099
2100         /* If this is not VM_FLUSH_RESET_PERMS memory, no need for the below. */
2101         if (!flush_reset)
2102                 return;
2103
2104         /*
2105          * If not deallocating pages, just do the flush of the VM area and
2106          * return.
2107          */
2108         if (!deallocate_pages) {
2109                 vm_unmap_aliases();
2110                 return;
2111         }
2112
2113         /*
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.
2117          */
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);
2122                 }
2123         }
2124
2125         /*
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.
2129          */
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);
2133 }
2134
2135 static void __vunmap(const void *addr, int deallocate_pages)
2136 {
2137         struct vm_struct *area;
2138
2139         if (!addr)
2140                 return;
2141
2142         if (WARN(!PAGE_ALIGNED(addr), "Trying to vfree() bad address (%p)\n",
2143                         addr))
2144                 return;
2145
2146         area = find_vm_area(addr);
2147         if (unlikely(!area)) {
2148                 WARN(1, KERN_ERR "Trying to vfree() nonexistent vm area (%p)\n",
2149                                 addr);
2150                 return;
2151         }
2152
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));
2155
2156         vm_remove_mappings(area, deallocate_pages);
2157
2158         if (deallocate_pages) {
2159                 int i;
2160
2161                 for (i = 0; i < area->nr_pages; i++) {
2162                         struct page *page = area->pages[i];
2163
2164                         BUG_ON(!page);
2165                         __free_pages(page, 0);
2166                 }
2167
2168                 kvfree(area->pages);
2169         }
2170
2171         kfree(area);
2172         return;
2173 }
2174
2175 static inline void __vfree_deferred(const void *addr)
2176 {
2177         /*
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.
2182          */
2183         struct vfree_deferred *p = raw_cpu_ptr(&vfree_deferred);
2184
2185         if (llist_add((struct llist_node *)addr, &p->list))
2186                 schedule_work(&p->wq);
2187 }
2188
2189 /**
2190  * vfree_atomic - release memory allocated by vmalloc()
2191  * @addr:         memory base address
2192  *
2193  * This one is just like vfree() but can be called in any atomic context
2194  * except NMIs.
2195  */
2196 void vfree_atomic(const void *addr)
2197 {
2198         BUG_ON(in_nmi());
2199
2200         kmemleak_free(addr);
2201
2202         if (!addr)
2203                 return;
2204         __vfree_deferred(addr);
2205 }
2206
2207 static void __vfree(const void *addr)
2208 {
2209         if (unlikely(in_interrupt()))
2210                 __vfree_deferred(addr);
2211         else
2212                 __vunmap(addr, 1);
2213 }
2214
2215 /**
2216  * vfree - release memory allocated by vmalloc()
2217  * @addr:  memory base address
2218  *
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.
2222  *
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)
2226  *
2227  * May sleep if called *not* from interrupt context.
2228  *
2229  * NOTE: assumes that the object at @addr has a size >= sizeof(llist_node)
2230  */
2231 void vfree(const void *addr)
2232 {
2233         BUG_ON(in_nmi());
2234
2235         kmemleak_free(addr);
2236
2237         might_sleep_if(!in_interrupt());
2238
2239         if (!addr)
2240                 return;
2241
2242         __vfree(addr);
2243 }
2244 EXPORT_SYMBOL(vfree);
2245
2246 /**
2247  * vunmap - release virtual mapping obtained by vmap()
2248  * @addr:   memory base address
2249  *
2250  * Free the virtually contiguous memory area starting at @addr,
2251  * which was created from the page array passed to vmap().
2252  *
2253  * Must not be called in interrupt context.
2254  */
2255 void vunmap(const void *addr)
2256 {
2257         BUG_ON(in_interrupt());
2258         might_sleep();
2259         if (addr)
2260                 __vunmap(addr, 0);
2261 }
2262 EXPORT_SYMBOL(vunmap);
2263
2264 /**
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
2270  *
2271  * Maps @count pages from @pages into contiguous kernel virtual
2272  * space.
2273  *
2274  * Return: the address of the area or %NULL on failure
2275  */
2276 void *vmap(struct page **pages, unsigned int count,
2277            unsigned long flags, pgprot_t prot)
2278 {
2279         struct vm_struct *area;
2280         unsigned long size;             /* In bytes */
2281
2282         might_sleep();
2283
2284         if (count > totalram_pages())
2285                 return NULL;
2286
2287         size = (unsigned long)count << PAGE_SHIFT;
2288         area = get_vm_area_caller(size, flags, __builtin_return_address(0));
2289         if (!area)
2290                 return NULL;
2291
2292         if (map_vm_area(area, prot, pages)) {
2293                 vunmap(area->addr);
2294                 return NULL;
2295         }
2296
2297         return area->addr;
2298 }
2299 EXPORT_SYMBOL(vmap);
2300
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)
2306 {
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)) ?
2312                                         0 :
2313                                         __GFP_HIGHMEM;
2314
2315         nr_pages = get_vm_area_size(area) >> PAGE_SHIFT;
2316         array_size = (nr_pages * sizeof(struct page *));
2317
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);
2323         } else {
2324                 pages = kmalloc_node(array_size, nested_gfp, node);
2325         }
2326         area->pages = pages;
2327         if (!area->pages) {
2328                 remove_vm_area(area->addr);
2329                 kfree(area);
2330                 return NULL;
2331         }
2332
2333         for (i = 0; i < area->nr_pages; i++) {
2334                 struct page *page;
2335
2336                 if (node == NUMA_NO_NODE)
2337                         page = alloc_page(alloc_mask|highmem_mask);
2338                 else
2339                         page = alloc_pages_node(node, alloc_mask|highmem_mask, 0);
2340
2341                 if (unlikely(!page)) {
2342                         /* Successfully allocated i pages, free them in __vunmap() */
2343                         area->nr_pages = i;
2344                         goto fail;
2345                 }
2346                 area->pages[i] = page;
2347                 if (gfpflags_allow_blocking(gfp_mask|highmem_mask))
2348                         cond_resched();
2349         }
2350
2351         if (map_vm_area(area, prot, pages))
2352                 goto fail;
2353         return area->addr;
2354
2355 fail:
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);
2360         return NULL;
2361 }
2362
2363 /**
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
2374  *
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.
2378  *
2379  * Return: the address of the area or %NULL on failure
2380  */
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,
2384                         const void *caller)
2385 {
2386         struct vm_struct *area;
2387         void *addr;
2388         unsigned long real_size = size;
2389
2390         size = PAGE_ALIGN(size);
2391         if (!size || (size >> PAGE_SHIFT) > totalram_pages())
2392                 goto fail;
2393
2394         area = __get_vm_area_node(size, align, VM_ALLOC | VM_UNINITIALIZED |
2395                                 vm_flags, start, end, node, gfp_mask, caller);
2396         if (!area)
2397                 goto fail;
2398
2399         addr = __vmalloc_area_node(area, gfp_mask, prot, node);
2400         if (!addr)
2401                 return NULL;
2402
2403         /*
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.
2407          */
2408         clear_vm_uninitialized_flag(area);
2409
2410         kmemleak_vmalloc(area, size, gfp_mask);
2411
2412         return addr;
2413
2414 fail:
2415         warn_alloc(gfp_mask, NULL,
2416                           "vmalloc: allocation failure: %lu bytes", real_size);
2417         return NULL;
2418 }
2419
2420 /*
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
2423  * than that.
2424  */
2425 #ifdef CONFIG_TEST_VMALLOC_MODULE
2426 EXPORT_SYMBOL_GPL(__vmalloc_node_range);
2427 #endif
2428
2429 /**
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
2437  *
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.
2441  *
2442  * Reclaim modifiers in @gfp_mask - __GFP_NORETRY, __GFP_RETRY_MAYFAIL
2443  * and __GFP_NOFAIL are not supported
2444  *
2445  * Any use of gfp flags outside of GFP_KERNEL should be consulted
2446  * with mm people.
2447  *
2448  * Return: pointer to the allocated memory or %NULL on error
2449  */
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)
2453 {
2454         return __vmalloc_node_range(size, align, VMALLOC_START, VMALLOC_END,
2455                                 gfp_mask, prot, 0, node, caller);
2456 }
2457
2458 void *__vmalloc(unsigned long size, gfp_t gfp_mask, pgprot_t prot)
2459 {
2460         return __vmalloc_node(size, 1, gfp_mask, prot, NUMA_NO_NODE,
2461                                 __builtin_return_address(0));
2462 }
2463 EXPORT_SYMBOL(__vmalloc);
2464
2465 static inline void *__vmalloc_node_flags(unsigned long size,
2466                                         int node, gfp_t flags)
2467 {
2468         return __vmalloc_node(size, 1, flags, PAGE_KERNEL,
2469                                         node, __builtin_return_address(0));
2470 }
2471
2472
2473 void *__vmalloc_node_flags_caller(unsigned long size, int node, gfp_t flags,
2474                                   void *caller)
2475 {
2476         return __vmalloc_node(size, 1, flags, PAGE_KERNEL, node, caller);
2477 }
2478
2479 /**
2480  * vmalloc - allocate virtually contiguous memory
2481  * @size:    allocation size
2482  *
2483  * Allocate enough pages to cover @size from the page level
2484  * allocator and map them into contiguous kernel virtual space.
2485  *
2486  * For tight control over page level allocator and protection flags
2487  * use __vmalloc() instead.
2488  *
2489  * Return: pointer to the allocated memory or %NULL on error
2490  */
2491 void *vmalloc(unsigned long size)
2492 {
2493         return __vmalloc_node_flags(size, NUMA_NO_NODE,
2494                                     GFP_KERNEL);
2495 }
2496 EXPORT_SYMBOL(vmalloc);
2497
2498 /**
2499  * vzalloc - allocate virtually contiguous memory with zero fill
2500  * @size:    allocation size
2501  *
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.
2505  *
2506  * For tight control over page level allocator and protection flags
2507  * use __vmalloc() instead.
2508  *
2509  * Return: pointer to the allocated memory or %NULL on error
2510  */
2511 void *vzalloc(unsigned long size)
2512 {
2513         return __vmalloc_node_flags(size, NUMA_NO_NODE,
2514                                 GFP_KERNEL | __GFP_ZERO);
2515 }
2516 EXPORT_SYMBOL(vzalloc);
2517
2518 /**
2519  * vmalloc_user - allocate zeroed virtually contiguous memory for userspace
2520  * @size: allocation size
2521  *
2522  * The resulting memory area is zeroed so it can be mapped to userspace
2523  * without leaking data.
2524  *
2525  * Return: pointer to the allocated memory or %NULL on error
2526  */
2527 void *vmalloc_user(unsigned long size)
2528 {
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));
2533 }
2534 EXPORT_SYMBOL(vmalloc_user);
2535
2536 /**
2537  * vmalloc_node - allocate memory on a specific node
2538  * @size:         allocation size
2539  * @node:         numa node
2540  *
2541  * Allocate enough pages to cover @size from the page level
2542  * allocator and map them into contiguous kernel virtual space.
2543  *
2544  * For tight control over page level allocator and protection flags
2545  * use __vmalloc() instead.
2546  *
2547  * Return: pointer to the allocated memory or %NULL on error
2548  */
2549 void *vmalloc_node(unsigned long size, int node)
2550 {
2551         return __vmalloc_node(size, 1, GFP_KERNEL, PAGE_KERNEL,
2552                                         node, __builtin_return_address(0));
2553 }
2554 EXPORT_SYMBOL(vmalloc_node);
2555
2556 /**
2557  * vzalloc_node - allocate memory on a specific node with zero fill
2558  * @size:       allocation size
2559  * @node:       numa node
2560  *
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.
2564  *
2565  * For tight control over page level allocator and protection flags
2566  * use __vmalloc_node() instead.
2567  *
2568  * Return: pointer to the allocated memory or %NULL on error
2569  */
2570 void *vzalloc_node(unsigned long size, int node)
2571 {
2572         return __vmalloc_node_flags(size, node,
2573                          GFP_KERNEL | __GFP_ZERO);
2574 }
2575 EXPORT_SYMBOL(vzalloc_node);
2576
2577 /**
2578  * vmalloc_exec - allocate virtually contiguous, executable memory
2579  * @size:         allocation size
2580  *
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.
2584  *
2585  * For tight control over page level allocator and protection flags
2586  * use __vmalloc() instead.
2587  *
2588  * Return: pointer to the allocated memory or %NULL on error
2589  */
2590 void *vmalloc_exec(unsigned long size)
2591 {
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));
2595 }
2596
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)
2601 #else
2602 /*
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.
2605  */
2606 #define GFP_VMALLOC32 GFP_DMA32 | GFP_KERNEL
2607 #endif
2608
2609 /**
2610  * vmalloc_32 - allocate virtually contiguous memory (32bit addressable)
2611  * @size:       allocation size
2612  *
2613  * Allocate enough 32bit PA addressable pages to cover @size from the
2614  * page level allocator and map them into contiguous kernel virtual space.
2615  *
2616  * Return: pointer to the allocated memory or %NULL on error
2617  */
2618 void *vmalloc_32(unsigned long size)
2619 {
2620         return __vmalloc_node(size, 1, GFP_VMALLOC32, PAGE_KERNEL,
2621                               NUMA_NO_NODE, __builtin_return_address(0));
2622 }
2623 EXPORT_SYMBOL(vmalloc_32);
2624
2625 /**
2626  * vmalloc_32_user - allocate zeroed virtually contiguous 32bit memory
2627  * @size:            allocation size
2628  *
2629  * The resulting memory area is 32bit addressable and zeroed so it can be
2630  * mapped to userspace without leaking data.
2631  *
2632  * Return: pointer to the allocated memory or %NULL on error
2633  */
2634 void *vmalloc_32_user(unsigned long size)
2635 {
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));
2640 }
2641 EXPORT_SYMBOL(vmalloc_32_user);
2642
2643 /*
2644  * small helper routine , copy contents to buf from addr.
2645  * If the page is not present, fill zero.
2646  */
2647
2648 static int aligned_vread(char *buf, char *addr, unsigned long count)
2649 {
2650         struct page *p;
2651         int copied = 0;
2652
2653         while (count) {
2654                 unsigned long offset, length;
2655
2656                 offset = offset_in_page(addr);
2657                 length = PAGE_SIZE - offset;
2658                 if (length > count)
2659                         length = count;
2660                 p = vmalloc_to_page(addr);
2661                 /*
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.
2667                  */
2668                 if (p) {
2669                         /*
2670                          * we can expect USER0 is not used (see vread/vwrite's
2671                          * function description)
2672                          */
2673                         void *map = kmap_atomic(p);
2674                         memcpy(buf, map + offset, length);
2675                         kunmap_atomic(map);
2676                 } else
2677                         memset(buf, 0, length);
2678
2679                 addr += length;
2680                 buf += length;
2681                 copied += length;
2682                 count -= length;
2683         }
2684         return copied;
2685 }
2686
2687 static int aligned_vwrite(char *buf, char *addr, unsigned long count)
2688 {
2689         struct page *p;
2690         int copied = 0;
2691
2692         while (count) {
2693                 unsigned long offset, length;
2694
2695                 offset = offset_in_page(addr);
2696                 length = PAGE_SIZE - offset;
2697                 if (length > count)
2698                         length = count;
2699                 p = vmalloc_to_page(addr);
2700                 /*
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.
2706                  */
2707                 if (p) {
2708                         /*
2709                          * we can expect USER0 is not used (see vread/vwrite's
2710                          * function description)
2711                          */
2712                         void *map = kmap_atomic(p);
2713                         memcpy(map + offset, buf, length);
2714                         kunmap_atomic(map);
2715                 }
2716                 addr += length;
2717                 buf += length;
2718                 copied += length;
2719                 count -= length;
2720         }
2721         return copied;
2722 }
2723
2724 /**
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.
2729  *
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.
2735  *
2736  * If [addr...addr+count) doesn't includes any intersects with alive
2737  * vm_struct area, returns 0. @buf should be kernel's buffer.
2738  *
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.
2743  *
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
2747  */
2748 long vread(char *buf, char *addr, unsigned long count)
2749 {
2750         struct vmap_area *va;
2751         struct vm_struct *vm;
2752         char *vaddr, *buf_start = buf;
2753         unsigned long buflen = count;
2754         unsigned long n;
2755
2756         /* Don't allow overflow */
2757         if ((unsigned long) addr + count < count)
2758                 count = -(unsigned long) addr;
2759
2760         spin_lock(&vmap_area_lock);
2761         list_for_each_entry(va, &vmap_area_list, list) {
2762                 if (!count)
2763                         break;
2764
2765                 if (!(va->flags & VM_VM_AREA))
2766                         continue;
2767
2768                 vm = va->vm;
2769                 vaddr = (char *) vm->addr;
2770                 if (addr >= vaddr + get_vm_area_size(vm))
2771                         continue;
2772                 while (addr < vaddr) {
2773                         if (count == 0)
2774                                 goto finished;
2775                         *buf = '\0';
2776                         buf++;
2777                         addr++;
2778                         count--;
2779                 }
2780                 n = vaddr + get_vm_area_size(vm) - addr;
2781                 if (n > count)
2782                         n = count;
2783                 if (!(vm->flags & VM_IOREMAP))
2784                         aligned_vread(buf, addr, n);
2785                 else /* IOREMAP area is treated as memory hole */
2786                         memset(buf, 0, n);
2787                 buf += n;
2788                 addr += n;
2789                 count -= n;
2790         }
2791 finished:
2792         spin_unlock(&vmap_area_lock);
2793
2794         if (buf == buf_start)
2795                 return 0;
2796         /* zero-fill memory holes */
2797         if (buf != buf_start + buflen)
2798                 memset(buf, 0, buflen - (buf - buf_start));
2799
2800         return buflen;
2801 }
2802
2803 /**
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.
2808  *
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.
2814  *
2815  * If [addr...addr+count) doesn't includes any intersects with alive
2816  * vm_struct area, returns 0. @buf should be kernel's buffer.
2817  *
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.
2822  *
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
2826  */
2827 long vwrite(char *buf, char *addr, unsigned long count)
2828 {
2829         struct vmap_area *va;
2830         struct vm_struct *vm;
2831         char *vaddr;
2832         unsigned long n, buflen;
2833         int copied = 0;
2834
2835         /* Don't allow overflow */
2836         if ((unsigned long) addr + count < count)
2837                 count = -(unsigned long) addr;
2838         buflen = count;
2839
2840         spin_lock(&vmap_area_lock);
2841         list_for_each_entry(va, &vmap_area_list, list) {
2842                 if (!count)
2843                         break;
2844
2845                 if (!(va->flags & VM_VM_AREA))
2846                         continue;
2847
2848                 vm = va->vm;
2849                 vaddr = (char *) vm->addr;
2850                 if (addr >= vaddr + get_vm_area_size(vm))
2851                         continue;
2852                 while (addr < vaddr) {
2853                         if (count == 0)
2854                                 goto finished;
2855                         buf++;
2856                         addr++;
2857                         count--;
2858                 }
2859                 n = vaddr + get_vm_area_size(vm) - addr;
2860                 if (n > count)
2861                         n = count;
2862                 if (!(vm->flags & VM_IOREMAP)) {
2863                         aligned_vwrite(buf, addr, n);
2864                         copied++;
2865                 }
2866                 buf += n;
2867                 addr += n;
2868                 count -= n;
2869         }
2870 finished:
2871         spin_unlock(&vmap_area_lock);
2872         if (!copied)
2873                 return 0;
2874         return buflen;
2875 }
2876
2877 /**
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
2883  *
2884  * Returns:     0 for success, -Exxx on failure
2885  *
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
2889  * met.
2890  *
2891  * Similar to remap_pfn_range() (see mm/memory.c)
2892  */
2893 int remap_vmalloc_range_partial(struct vm_area_struct *vma, unsigned long uaddr,
2894                                 void *kaddr, unsigned long size)
2895 {
2896         struct vm_struct *area;
2897
2898         size = PAGE_ALIGN(size);
2899
2900         if (!PAGE_ALIGNED(uaddr) || !PAGE_ALIGNED(kaddr))
2901                 return -EINVAL;
2902
2903         area = find_vm_area(kaddr);
2904         if (!area)
2905                 return -EINVAL;
2906
2907         if (!(area->flags & VM_USERMAP))
2908                 return -EINVAL;
2909
2910         if (kaddr + size > area->addr + get_vm_area_size(area))
2911                 return -EINVAL;
2912
2913         do {
2914                 struct page *page = vmalloc_to_page(kaddr);
2915                 int ret;
2916
2917                 ret = vm_insert_page(vma, uaddr, page);
2918                 if (ret)
2919                         return ret;
2920
2921                 uaddr += PAGE_SIZE;
2922                 kaddr += PAGE_SIZE;
2923                 size -= PAGE_SIZE;
2924         } while (size > 0);
2925
2926         vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
2927
2928         return 0;
2929 }
2930 EXPORT_SYMBOL(remap_vmalloc_range_partial);
2931
2932 /**
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
2937  *
2938  * Returns:     0 for success, -Exxx on failure
2939  *
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.
2943  *
2944  * Similar to remap_pfn_range() (see mm/memory.c)
2945  */
2946 int remap_vmalloc_range(struct vm_area_struct *vma, void *addr,
2947                                                 unsigned long pgoff)
2948 {
2949         return remap_vmalloc_range_partial(vma, vma->vm_start,
2950                                            addr + (pgoff << PAGE_SHIFT),
2951                                            vma->vm_end - vma->vm_start);
2952 }
2953 EXPORT_SYMBOL(remap_vmalloc_range);
2954
2955 /*
2956  * Implement a stub for vmalloc_sync_all() if the architecture chose not to
2957  * have one.
2958  */
2959 void __weak vmalloc_sync_all(void)
2960 {
2961 }
2962
2963
2964 static int f(pte_t *pte, pgtable_t table, unsigned long addr, void *data)
2965 {
2966         pte_t ***p = data;
2967
2968         if (p) {
2969                 *(*p) = pte;
2970                 (*p)++;
2971         }
2972         return 0;
2973 }
2974
2975 /**
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
2979  *
2980  * Returns:     NULL on failure, vm_struct on success
2981  *
2982  * This function reserves a range of kernel address space, and
2983  * allocates pagetables to map that range.  No actual mappings
2984  * are created.
2985  *
2986  * If @ptes is non-NULL, pointers to the PTEs (in init_mm)
2987  * allocated for the VM area are returned.
2988  */
2989 struct vm_struct *alloc_vm_area(size_t size, pte_t **ptes)
2990 {
2991         struct vm_struct *area;
2992
2993         area = get_vm_area_caller(size, VM_IOREMAP,
2994                                 __builtin_return_address(0));
2995         if (area == NULL)
2996                 return NULL;
2997
2998         /*
2999          * This ensures that page tables are constructed for this region
3000          * of kernel virtual address space and mapped into init_mm.
3001          */
3002         if (apply_to_page_range(&init_mm, (unsigned long)area->addr,
3003                                 size, f, ptes ? &ptes : NULL)) {
3004                 free_vm_area(area);
3005                 return NULL;
3006         }
3007
3008         return area;
3009 }
3010 EXPORT_SYMBOL_GPL(alloc_vm_area);
3011
3012 void free_vm_area(struct vm_struct *area)
3013 {
3014         struct vm_struct *ret;
3015         ret = remove_vm_area(area->addr);
3016         BUG_ON(ret != area);
3017         kfree(area);
3018 }
3019 EXPORT_SYMBOL_GPL(free_vm_area);
3020
3021 #ifdef CONFIG_SMP
3022 static struct vmap_area *node_to_va(struct rb_node *n)
3023 {
3024         return rb_entry_safe(n, struct vmap_area, rb_node);
3025 }
3026
3027 /**
3028  * pvm_find_va_enclose_addr - find the vmap_area @addr belongs to
3029  * @addr: target address
3030  *
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.
3035  */
3036 static struct vmap_area *
3037 pvm_find_va_enclose_addr(unsigned long addr)
3038 {
3039         struct vmap_area *va, *tmp;
3040         struct rb_node *n;
3041
3042         n = free_vmap_area_root.rb_node;
3043         va = NULL;
3044
3045         while (n) {
3046                 tmp = rb_entry(n, struct vmap_area, rb_node);
3047                 if (tmp->va_start <= addr) {
3048                         va = tmp;
3049                         if (tmp->va_end >= addr)
3050                                 break;
3051
3052                         n = n->rb_right;
3053                 } else {
3054                         n = n->rb_left;
3055                 }
3056         }
3057
3058         return va;
3059 }
3060
3061 /**
3062  * pvm_determine_end_from_reverse - find the highest aligned address
3063  * of free block below VMALLOC_END
3064  * @va:
3065  *   in - the VA we start the search(reverse order);
3066  *   out - the VA with the highest aligned end address.
3067  *
3068  * Returns: determined end address within vmap_area
3069  */
3070 static unsigned long
3071 pvm_determine_end_from_reverse(struct vmap_area **va, unsigned long align)
3072 {
3073         unsigned long vmalloc_end = VMALLOC_END & ~(align - 1);
3074         unsigned long addr;
3075
3076         if (likely(*va)) {
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)
3081                                 return addr;
3082                 }
3083         }
3084
3085         return 0;
3086 }
3087
3088 /**
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
3094  *
3095  * Returns: kmalloc'd vm_struct pointer array pointing to allocated
3096  *          vm_structs on success, %NULL on failure
3097  *
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.
3104  *
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.
3111  */
3112 struct vm_struct **pcpu_get_vm_areas(const unsigned long *offsets,
3113                                      const size_t *sizes, int nr_vms,
3114                                      size_t align)
3115 {
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;
3123         enum fit_type type;
3124
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];
3130
3131                 /* is everything aligned properly? */
3132                 BUG_ON(!IS_ALIGNED(offsets[area], align));
3133                 BUG_ON(!IS_ALIGNED(sizes[area], align));
3134
3135                 /* detect the area with the highest address */
3136                 if (start > offsets[last_area])
3137                         last_area = area;
3138
3139                 for (area2 = area + 1; area2 < nr_vms; area2++) {
3140                         unsigned long start2 = offsets[area2];
3141                         unsigned long end2 = start2 + sizes[area2];
3142
3143                         BUG_ON(start2 < end && start < end2);
3144                 }
3145         }
3146         last_end = offsets[last_area] + sizes[last_area];
3147
3148         if (vmalloc_end - vmalloc_start < last_end) {
3149                 WARN_ON(true);
3150                 return NULL;
3151         }
3152
3153         vms = kcalloc(nr_vms, sizeof(vms[0]), GFP_KERNEL);
3154         vas = kcalloc(nr_vms, sizeof(vas[0]), GFP_KERNEL);
3155         if (!vas || !vms)
3156                 goto err_free2;
3157
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])
3162                         goto err_free;
3163         }
3164 retry:
3165         spin_lock(&vmap_area_lock);
3166
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];
3171
3172         va = pvm_find_va_enclose_addr(vmalloc_end);
3173         base = pvm_determine_end_from_reverse(&va, align) - end;
3174
3175         while (true) {
3176                 /*
3177                  * base might have underflowed, add last_end before
3178                  * comparing.
3179                  */
3180                 if (base + last_end < vmalloc_start + last_end)
3181                         goto overflow;
3182
3183                 /*
3184                  * Fitting base has not been found.
3185                  */
3186                 if (va == NULL)
3187                         goto overflow;
3188
3189                 /*
3190                  * If this VA does not fit, move base downwards and recheck.
3191                  */
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;
3195                         term_area = area;
3196                         continue;
3197                 }
3198
3199                 /*
3200                  * This area fits, move on to the previous one.  If
3201                  * the previous one is the terminal one, we're done.
3202                  */
3203                 area = (area + nr_vms - 1) % nr_vms;
3204                 if (area == term_area)
3205                         break;
3206
3207                 start = offsets[area];
3208                 end = start + sizes[area];
3209                 va = pvm_find_va_enclose_addr(base + end);
3210         }
3211
3212         /* we've found a fitting base, insert all va's */
3213         for (area = 0; area < nr_vms; area++) {
3214                 int ret;
3215
3216                 start = base + offsets[area];
3217                 size = sizes[area];
3218
3219                 va = pvm_find_va_enclose_addr(start);
3220                 if (WARN_ON_ONCE(va == NULL))
3221                         /* It is a BUG(), but trigger recovery instead. */
3222                         goto recovery;
3223
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. */
3227                         goto recovery;
3228
3229                 ret = adjust_va_to_fit_type(va, start, size, type);
3230                 if (unlikely(ret))
3231                         goto recovery;
3232
3233                 /* Allocated area. */
3234                 va = vas[area];
3235                 va->va_start = start;
3236                 va->va_end = start + size;
3237
3238                 insert_vmap_area(va, &vmap_area_root, &vmap_area_list);
3239         }
3240
3241         spin_unlock(&vmap_area_lock);
3242
3243         /* insert all vm's */
3244         for (area = 0; area < nr_vms; area++)
3245                 setup_vmalloc_vm(vms[area], vas[area], VM_ALLOC,
3246                                  pcpu_get_vm_areas);
3247
3248         kfree(vas);
3249         return vms;
3250
3251 recovery:
3252         /* Remove previously inserted areas. */
3253         while (area--) {
3254                 __free_vmap_area(vas[area]);
3255                 vas[area] = NULL;
3256         }
3257
3258 overflow:
3259         spin_unlock(&vmap_area_lock);
3260         if (!purged) {
3261                 purge_vmap_area_lazy();
3262                 purged = true;
3263
3264                 /* Before "retry", check if we recover. */
3265                 for (area = 0; area < nr_vms; area++) {
3266                         if (vas[area])
3267                                 continue;
3268
3269                         vas[area] = kmem_cache_zalloc(
3270                                 vmap_area_cachep, GFP_KERNEL);
3271                         if (!vas[area])
3272                                 goto err_free;
3273                 }
3274
3275                 goto retry;
3276         }
3277
3278 err_free:
3279         for (area = 0; area < nr_vms; area++) {
3280                 if (vas[area])
3281                         kmem_cache_free(vmap_area_cachep, vas[area]);
3282
3283                 kfree(vms[area]);
3284         }
3285 err_free2:
3286         kfree(vas);
3287         kfree(vms);
3288         return NULL;
3289 }
3290
3291 /**
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
3295  *
3296  * Free vm_structs and the array allocated by pcpu_get_vm_areas().
3297  */
3298 void pcpu_free_vm_areas(struct vm_struct **vms, int nr_vms)
3299 {
3300         int i;
3301
3302         for (i = 0; i < nr_vms; i++)
3303                 free_vm_area(vms[i]);
3304         kfree(vms);
3305 }
3306 #endif  /* CONFIG_SMP */
3307
3308 #ifdef CONFIG_PROC_FS
3309 static void *s_start(struct seq_file *m, loff_t *pos)
3310         __acquires(&vmap_area_lock)
3311 {
3312         spin_lock(&vmap_area_lock);
3313         return seq_list_start(&vmap_area_list, *pos);
3314 }
3315
3316 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
3317 {
3318         return seq_list_next(p, &vmap_area_list, pos);
3319 }
3320
3321 static void s_stop(struct seq_file *m, void *p)
3322         __releases(&vmap_area_lock)
3323 {
3324         spin_unlock(&vmap_area_lock);
3325 }
3326
3327 static void show_numa_info(struct seq_file *m, struct vm_struct *v)
3328 {
3329         if (IS_ENABLED(CONFIG_NUMA)) {
3330                 unsigned int nr, *counters = m->private;
3331
3332                 if (!counters)
3333                         return;
3334
3335                 if (v->flags & VM_UNINITIALIZED)
3336                         return;
3337                 /* Pair with smp_wmb() in clear_vm_uninitialized_flag() */
3338                 smp_rmb();
3339
3340                 memset(counters, 0, nr_node_ids * sizeof(unsigned int));
3341
3342                 for (nr = 0; nr < v->nr_pages; nr++)
3343                         counters[page_to_nid(v->pages[nr])]++;
3344
3345                 for_each_node_state(nr, N_HIGH_MEMORY)
3346                         if (counters[nr])
3347                                 seq_printf(m, " N%u=%u", nr, counters[nr]);
3348         }
3349 }
3350
3351 static int s_show(struct seq_file *m, void *p)
3352 {
3353         struct vmap_area *va;
3354         struct vm_struct *v;
3355
3356         va = list_entry(p, struct vmap_area, list);
3357
3358         /*
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.
3361          */
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");
3367
3368                 return 0;
3369         }
3370
3371         v = va->vm;
3372
3373         seq_printf(m, "0x%pK-0x%pK %7ld",
3374                 v->addr, v->addr + v->size, v->size);
3375
3376         if (v->caller)
3377                 seq_printf(m, " %pS", v->caller);
3378
3379         if (v->nr_pages)
3380                 seq_printf(m, " pages=%d", v->nr_pages);
3381
3382         if (v->phys_addr)
3383                 seq_printf(m, " phys=%pa", &v->phys_addr);
3384
3385         if (v->flags & VM_IOREMAP)
3386                 seq_puts(m, " ioremap");
3387
3388         if (v->flags & VM_ALLOC)
3389                 seq_puts(m, " vmalloc");
3390
3391         if (v->flags & VM_MAP)
3392                 seq_puts(m, " vmap");
3393
3394         if (v->flags & VM_USERMAP)
3395                 seq_puts(m, " user");
3396
3397         if (is_vmalloc_addr(v->pages))
3398                 seq_puts(m, " vpages");
3399
3400         show_numa_info(m, v);
3401         seq_putc(m, '\n');
3402         return 0;
3403 }
3404
3405 static const struct seq_operations vmalloc_op = {
3406         .start = s_start,
3407         .next = s_next,
3408         .stop = s_stop,
3409         .show = s_show,
3410 };
3411
3412 static int __init proc_vmalloc_init(void)
3413 {
3414         if (IS_ENABLED(CONFIG_NUMA))
3415                 proc_create_seq_private("vmallocinfo", 0400, NULL,
3416                                 &vmalloc_op,
3417                                 nr_node_ids * sizeof(unsigned int), NULL);
3418         else
3419                 proc_create_seq("vmallocinfo", 0400, NULL, &vmalloc_op);
3420         return 0;
3421 }
3422 module_init(proc_vmalloc_init);
3423
3424 #endif