- Update Xen patches to 2.6.32 final and c/s 958.
[linux-flexiantxendom0-3.2.10.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.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/debugobjects.h>
22 #include <linux/kallsyms.h>
23 #include <linux/list.h>
24 #include <linux/rbtree.h>
25 #include <linux/radix-tree.h>
26 #include <linux/rcupdate.h>
27 #include <linux/pfn.h>
28 #include <linux/kmemleak.h>
29 #include <asm/atomic.h>
30 #include <asm/uaccess.h>
31 #include <asm/tlbflush.h>
32 #include <asm/shmparam.h>
33
34
35 /*** Page table manipulation functions ***/
36
37 static void vunmap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end)
38 {
39         pte_t *pte;
40
41         pte = pte_offset_kernel(pmd, addr);
42         do {
43                 pte_t ptent = ptep_get_and_clear(&init_mm, addr, pte);
44                 WARN_ON(!pte_none(ptent) && !pte_present(ptent));
45         } while (pte++, addr += PAGE_SIZE, addr != end);
46 }
47
48 static void vunmap_pmd_range(pud_t *pud, unsigned long addr, unsigned long end)
49 {
50         pmd_t *pmd;
51         unsigned long next;
52
53         pmd = pmd_offset(pud, addr);
54         do {
55                 next = pmd_addr_end(addr, end);
56                 if (pmd_none_or_clear_bad(pmd))
57                         continue;
58                 vunmap_pte_range(pmd, addr, next);
59         } while (pmd++, addr = next, addr != end);
60 }
61
62 static void vunmap_pud_range(pgd_t *pgd, unsigned long addr, unsigned long end)
63 {
64         pud_t *pud;
65         unsigned long next;
66
67         pud = pud_offset(pgd, addr);
68         do {
69                 next = pud_addr_end(addr, end);
70                 if (pud_none_or_clear_bad(pud))
71                         continue;
72                 vunmap_pmd_range(pud, addr, next);
73         } while (pud++, addr = next, addr != end);
74 }
75
76 static void vunmap_page_range(unsigned long addr, unsigned long end)
77 {
78         pgd_t *pgd;
79         unsigned long next;
80
81         BUG_ON(addr >= end);
82         pgd = pgd_offset_k(addr);
83         do {
84                 next = pgd_addr_end(addr, end);
85                 if (pgd_none_or_clear_bad(pgd))
86                         continue;
87                 vunmap_pud_range(pgd, addr, next);
88         } while (pgd++, addr = next, addr != end);
89 }
90
91 static int vmap_pte_range(pmd_t *pmd, unsigned long addr,
92                 unsigned long end, pgprot_t prot, struct page **pages, int *nr)
93 {
94         pte_t *pte;
95
96         /*
97          * nr is a running index into the array which helps higher level
98          * callers keep track of where we're up to.
99          */
100
101         pte = pte_alloc_kernel(pmd, addr);
102         if (!pte)
103                 return -ENOMEM;
104         do {
105                 struct page *page = pages[*nr];
106
107                 if (WARN_ON(!pte_none(*pte)))
108                         return -EBUSY;
109                 if (WARN_ON(!page))
110                         return -ENOMEM;
111                 set_pte_at(&init_mm, addr, pte, mk_pte(page, prot));
112                 (*nr)++;
113         } while (pte++, addr += PAGE_SIZE, addr != end);
114         return 0;
115 }
116
117 static int vmap_pmd_range(pud_t *pud, unsigned long addr,
118                 unsigned long end, pgprot_t prot, struct page **pages, int *nr)
119 {
120         pmd_t *pmd;
121         unsigned long next;
122
123         pmd = pmd_alloc(&init_mm, pud, addr);
124         if (!pmd)
125                 return -ENOMEM;
126         do {
127                 next = pmd_addr_end(addr, end);
128                 if (vmap_pte_range(pmd, addr, next, prot, pages, nr))
129                         return -ENOMEM;
130         } while (pmd++, addr = next, addr != end);
131         return 0;
132 }
133
134 static int vmap_pud_range(pgd_t *pgd, unsigned long addr,
135                 unsigned long end, pgprot_t prot, struct page **pages, int *nr)
136 {
137         pud_t *pud;
138         unsigned long next;
139
140         pud = pud_alloc(&init_mm, pgd, addr);
141         if (!pud)
142                 return -ENOMEM;
143         do {
144                 next = pud_addr_end(addr, end);
145                 if (vmap_pmd_range(pud, addr, next, prot, pages, nr))
146                         return -ENOMEM;
147         } while (pud++, addr = next, addr != end);
148         return 0;
149 }
150
151 /*
152  * Set up page tables in kva (addr, end). The ptes shall have prot "prot", and
153  * will have pfns corresponding to the "pages" array.
154  *
155  * Ie. pte at addr+N*PAGE_SIZE shall point to pfn corresponding to pages[N]
156  */
157 static int vmap_page_range_noflush(unsigned long start, unsigned long end,
158                                    pgprot_t prot, struct page **pages)
159 {
160         pgd_t *pgd;
161         unsigned long next;
162         unsigned long addr = start;
163         int err = 0;
164         int nr = 0;
165
166         BUG_ON(addr >= end);
167         pgd = pgd_offset_k(addr);
168         do {
169                 next = pgd_addr_end(addr, end);
170                 err = vmap_pud_range(pgd, addr, next, prot, pages, &nr);
171                 if (err)
172                         return err;
173         } while (pgd++, addr = next, addr != end);
174
175         return nr;
176 }
177
178 static int vmap_page_range(unsigned long start, unsigned long end,
179                            pgprot_t prot, struct page **pages)
180 {
181         int ret;
182
183         ret = vmap_page_range_noflush(start, end, prot, pages);
184         flush_cache_vmap(start, end);
185         return ret;
186 }
187
188 int is_vmalloc_or_module_addr(const void *x)
189 {
190         /*
191          * ARM, x86-64 and sparc64 put modules in a special place,
192          * and fall back on vmalloc() if that fails. Others
193          * just put it in the vmalloc space.
194          */
195 #if defined(CONFIG_MODULES) && defined(MODULES_VADDR)
196         unsigned long addr = (unsigned long)x;
197         if (addr >= MODULES_VADDR && addr < MODULES_END)
198                 return 1;
199 #endif
200         return is_vmalloc_addr(x);
201 }
202
203 /*
204  * Walk a vmap address to the struct page it maps.
205  */
206 struct page *vmalloc_to_page(const void *vmalloc_addr)
207 {
208         unsigned long addr = (unsigned long) vmalloc_addr;
209         struct page *page = NULL;
210         pgd_t *pgd = pgd_offset_k(addr);
211
212         /*
213          * XXX we might need to change this if we add VIRTUAL_BUG_ON for
214          * architectures that do not vmalloc module space
215          */
216         VIRTUAL_BUG_ON(!is_vmalloc_or_module_addr(vmalloc_addr));
217
218         if (!pgd_none(*pgd)) {
219                 pud_t *pud = pud_offset(pgd, addr);
220                 if (!pud_none(*pud)) {
221                         pmd_t *pmd = pmd_offset(pud, addr);
222                         if (!pmd_none(*pmd)) {
223                                 pte_t *ptep, pte;
224
225                                 ptep = pte_offset_map(pmd, addr);
226                                 pte = *ptep;
227                                 if (pte_present(pte))
228                                         page = pte_page(pte);
229                                 pte_unmap(ptep);
230                         }
231                 }
232         }
233         return page;
234 }
235 EXPORT_SYMBOL(vmalloc_to_page);
236
237 /*
238  * Map a vmalloc()-space virtual address to the physical page frame number.
239  */
240 unsigned long vmalloc_to_pfn(const void *vmalloc_addr)
241 {
242         return page_to_pfn(vmalloc_to_page(vmalloc_addr));
243 }
244 EXPORT_SYMBOL(vmalloc_to_pfn);
245
246
247 /*** Global kva allocator ***/
248
249 #define VM_LAZY_FREE    0x01
250 #define VM_LAZY_FREEING 0x02
251 #define VM_VM_AREA      0x04
252
253 struct vmap_area {
254         unsigned long va_start;
255         unsigned long va_end;
256         unsigned long flags;
257         struct rb_node rb_node;         /* address sorted rbtree */
258         struct list_head list;          /* address sorted list */
259         struct list_head purge_list;    /* "lazy purge" list */
260         void *private;
261         struct rcu_head rcu_head;
262 };
263
264 static DEFINE_SPINLOCK(vmap_area_lock);
265 static struct rb_root vmap_area_root = RB_ROOT;
266 static LIST_HEAD(vmap_area_list);
267 static unsigned long vmap_area_pcpu_hole;
268
269 static struct vmap_area *__find_vmap_area(unsigned long addr)
270 {
271         struct rb_node *n = vmap_area_root.rb_node;
272
273         while (n) {
274                 struct vmap_area *va;
275
276                 va = rb_entry(n, struct vmap_area, rb_node);
277                 if (addr < va->va_start)
278                         n = n->rb_left;
279                 else if (addr > va->va_start)
280                         n = n->rb_right;
281                 else
282                         return va;
283         }
284
285         return NULL;
286 }
287
288 static void __insert_vmap_area(struct vmap_area *va)
289 {
290         struct rb_node **p = &vmap_area_root.rb_node;
291         struct rb_node *parent = NULL;
292         struct rb_node *tmp;
293
294         while (*p) {
295                 struct vmap_area *tmp;
296
297                 parent = *p;
298                 tmp = rb_entry(parent, struct vmap_area, rb_node);
299                 if (va->va_start < tmp->va_end)
300                         p = &(*p)->rb_left;
301                 else if (va->va_end > tmp->va_start)
302                         p = &(*p)->rb_right;
303                 else
304                         BUG();
305         }
306
307         rb_link_node(&va->rb_node, parent, p);
308         rb_insert_color(&va->rb_node, &vmap_area_root);
309
310         /* address-sort this list so it is usable like the vmlist */
311         tmp = rb_prev(&va->rb_node);
312         if (tmp) {
313                 struct vmap_area *prev;
314                 prev = rb_entry(tmp, struct vmap_area, rb_node);
315                 list_add_rcu(&va->list, &prev->list);
316         } else
317                 list_add_rcu(&va->list, &vmap_area_list);
318 }
319
320 static void purge_vmap_area_lazy(void);
321
322 /*
323  * Allocate a region of KVA of the specified size and alignment, within the
324  * vstart and vend.
325  */
326 static struct vmap_area *alloc_vmap_area(unsigned long size,
327                                 unsigned long align,
328                                 unsigned long vstart, unsigned long vend,
329                                 int node, gfp_t gfp_mask)
330 {
331         struct vmap_area *va;
332         struct rb_node *n;
333         unsigned long addr;
334         int purged = 0;
335
336         BUG_ON(!size);
337         BUG_ON(size & ~PAGE_MASK);
338
339         va = kmalloc_node(sizeof(struct vmap_area),
340                         gfp_mask & GFP_RECLAIM_MASK, node);
341         if (unlikely(!va))
342                 return ERR_PTR(-ENOMEM);
343
344 retry:
345         addr = ALIGN(vstart, align);
346
347         spin_lock(&vmap_area_lock);
348         if (addr + size - 1 < addr)
349                 goto overflow;
350
351         /* XXX: could have a last_hole cache */
352         n = vmap_area_root.rb_node;
353         if (n) {
354                 struct vmap_area *first = NULL;
355
356                 do {
357                         struct vmap_area *tmp;
358                         tmp = rb_entry(n, struct vmap_area, rb_node);
359                         if (tmp->va_end >= addr) {
360                                 if (!first && tmp->va_start < addr + size)
361                                         first = tmp;
362                                 n = n->rb_left;
363                         } else {
364                                 first = tmp;
365                                 n = n->rb_right;
366                         }
367                 } while (n);
368
369                 if (!first)
370                         goto found;
371
372                 if (first->va_end < addr) {
373                         n = rb_next(&first->rb_node);
374                         if (n)
375                                 first = rb_entry(n, struct vmap_area, rb_node);
376                         else
377                                 goto found;
378                 }
379
380                 while (addr + size > first->va_start && addr + size <= vend) {
381                         addr = ALIGN(first->va_end + PAGE_SIZE, align);
382                         if (addr + size - 1 < addr)
383                                 goto overflow;
384
385                         n = rb_next(&first->rb_node);
386                         if (n)
387                                 first = rb_entry(n, struct vmap_area, rb_node);
388                         else
389                                 goto found;
390                 }
391         }
392 found:
393         if (addr + size > vend) {
394 overflow:
395                 spin_unlock(&vmap_area_lock);
396                 if (!purged) {
397                         purge_vmap_area_lazy();
398                         purged = 1;
399                         goto retry;
400                 }
401                 if (printk_ratelimit())
402                         printk(KERN_WARNING
403                                 "vmap allocation for size %lu failed: "
404                                 "use vmalloc=<size> to increase size.\n", size);
405                 kfree(va);
406                 return ERR_PTR(-EBUSY);
407         }
408
409         BUG_ON(addr & (align-1));
410
411         va->va_start = addr;
412         va->va_end = addr + size;
413         va->flags = 0;
414         __insert_vmap_area(va);
415         spin_unlock(&vmap_area_lock);
416
417         return va;
418 }
419
420 static void rcu_free_va(struct rcu_head *head)
421 {
422         struct vmap_area *va = container_of(head, struct vmap_area, rcu_head);
423
424         kfree(va);
425 }
426
427 static void __free_vmap_area(struct vmap_area *va)
428 {
429         BUG_ON(RB_EMPTY_NODE(&va->rb_node));
430         rb_erase(&va->rb_node, &vmap_area_root);
431         RB_CLEAR_NODE(&va->rb_node);
432         list_del_rcu(&va->list);
433
434         /*
435          * Track the highest possible candidate for pcpu area
436          * allocation.  Areas outside of vmalloc area can be returned
437          * here too, consider only end addresses which fall inside
438          * vmalloc area proper.
439          */
440         if (va->va_end > VMALLOC_START && va->va_end <= VMALLOC_END)
441                 vmap_area_pcpu_hole = max(vmap_area_pcpu_hole, va->va_end);
442
443         call_rcu(&va->rcu_head, rcu_free_va);
444 }
445
446 /*
447  * Free a region of KVA allocated by alloc_vmap_area
448  */
449 static void free_vmap_area(struct vmap_area *va)
450 {
451         spin_lock(&vmap_area_lock);
452         __free_vmap_area(va);
453         spin_unlock(&vmap_area_lock);
454 }
455
456 /*
457  * Clear the pagetable entries of a given vmap_area
458  */
459 static void unmap_vmap_area(struct vmap_area *va)
460 {
461         vunmap_page_range(va->va_start, va->va_end);
462 }
463
464 static void vmap_debug_free_range(unsigned long start, unsigned long end)
465 {
466         /*
467          * Unmap page tables and force a TLB flush immediately if
468          * CONFIG_DEBUG_PAGEALLOC is set. This catches use after free
469          * bugs similarly to those in linear kernel virtual address
470          * space after a page has been freed.
471          *
472          * All the lazy freeing logic is still retained, in order to
473          * minimise intrusiveness of this debugging feature.
474          *
475          * This is going to be *slow* (linear kernel virtual address
476          * debugging doesn't do a broadcast TLB flush so it is a lot
477          * faster).
478          */
479 #ifdef CONFIG_DEBUG_PAGEALLOC
480         vunmap_page_range(start, end);
481         flush_tlb_kernel_range(start, end);
482 #elif defined(CONFIG_XEN) && defined(CONFIG_X86)
483         vunmap_page_range(start, end);
484 #endif
485 }
486
487 /*
488  * lazy_max_pages is the maximum amount of virtual address space we gather up
489  * before attempting to purge with a TLB flush.
490  *
491  * There is a tradeoff here: a larger number will cover more kernel page tables
492  * and take slightly longer to purge, but it will linearly reduce the number of
493  * global TLB flushes that must be performed. It would seem natural to scale
494  * this number up linearly with the number of CPUs (because vmapping activity
495  * could also scale linearly with the number of CPUs), however it is likely
496  * that in practice, workloads might be constrained in other ways that mean
497  * vmap activity will not scale linearly with CPUs. Also, I want to be
498  * conservative and not introduce a big latency on huge systems, so go with
499  * a less aggressive log scale. It will still be an improvement over the old
500  * code, and it will be simple to change the scale factor if we find that it
501  * becomes a problem on bigger systems.
502  */
503 static unsigned long lazy_max_pages(void)
504 {
505         unsigned int log;
506
507         log = fls(num_online_cpus());
508
509         return log * (32UL * 1024 * 1024 / PAGE_SIZE);
510 }
511
512 static atomic_t vmap_lazy_nr = ATOMIC_INIT(0);
513
514 /*
515  * Purges all lazily-freed vmap areas.
516  *
517  * If sync is 0 then don't purge if there is already a purge in progress.
518  * If force_flush is 1, then flush kernel TLBs between *start and *end even
519  * if we found no lazy vmap areas to unmap (callers can use this to optimise
520  * their own TLB flushing).
521  * Returns with *start = min(*start, lowest purged address)
522  *              *end = max(*end, highest purged address)
523  */
524 static void __purge_vmap_area_lazy(unsigned long *start, unsigned long *end,
525                                         int sync, int force_flush)
526 {
527         static DEFINE_SPINLOCK(purge_lock);
528         LIST_HEAD(valist);
529         struct vmap_area *va;
530         struct vmap_area *n_va;
531         int nr = 0;
532
533         /*
534          * If sync is 0 but force_flush is 1, we'll go sync anyway but callers
535          * should not expect such behaviour. This just simplifies locking for
536          * the case that isn't actually used at the moment anyway.
537          */
538         if (!sync && !force_flush) {
539                 if (!spin_trylock(&purge_lock))
540                         return;
541         } else
542                 spin_lock(&purge_lock);
543
544         rcu_read_lock();
545         list_for_each_entry_rcu(va, &vmap_area_list, list) {
546                 if (va->flags & VM_LAZY_FREE) {
547                         if (va->va_start < *start)
548                                 *start = va->va_start;
549                         if (va->va_end > *end)
550                                 *end = va->va_end;
551                         nr += (va->va_end - va->va_start) >> PAGE_SHIFT;
552                         unmap_vmap_area(va);
553                         list_add_tail(&va->purge_list, &valist);
554                         va->flags |= VM_LAZY_FREEING;
555                         va->flags &= ~VM_LAZY_FREE;
556                 }
557         }
558         rcu_read_unlock();
559
560         if (nr) {
561                 BUG_ON(nr > atomic_read(&vmap_lazy_nr));
562                 atomic_sub(nr, &vmap_lazy_nr);
563         }
564
565         if (nr || force_flush)
566                 flush_tlb_kernel_range(*start, *end);
567
568         if (nr) {
569                 spin_lock(&vmap_area_lock);
570                 list_for_each_entry_safe(va, n_va, &valist, purge_list)
571                         __free_vmap_area(va);
572                 spin_unlock(&vmap_area_lock);
573         }
574         spin_unlock(&purge_lock);
575 }
576
577 /*
578  * Kick off a purge of the outstanding lazy areas. Don't bother if somebody
579  * is already purging.
580  */
581 static void try_purge_vmap_area_lazy(void)
582 {
583         unsigned long start = ULONG_MAX, end = 0;
584
585         __purge_vmap_area_lazy(&start, &end, 0, 0);
586 }
587
588 /*
589  * Kick off a purge of the outstanding lazy areas.
590  */
591 static void purge_vmap_area_lazy(void)
592 {
593         unsigned long start = ULONG_MAX, end = 0;
594
595         __purge_vmap_area_lazy(&start, &end, 1, 0);
596 }
597
598 /*
599  * Free and unmap a vmap area, caller ensuring flush_cache_vunmap had been
600  * called for the correct range previously.
601  */
602 static void free_unmap_vmap_area_noflush(struct vmap_area *va)
603 {
604         va->flags |= VM_LAZY_FREE;
605         atomic_add((va->va_end - va->va_start) >> PAGE_SHIFT, &vmap_lazy_nr);
606         if (unlikely(atomic_read(&vmap_lazy_nr) > lazy_max_pages()))
607                 try_purge_vmap_area_lazy();
608 }
609
610 /*
611  * Free and unmap a vmap area
612  */
613 static void free_unmap_vmap_area(struct vmap_area *va)
614 {
615         flush_cache_vunmap(va->va_start, va->va_end);
616         free_unmap_vmap_area_noflush(va);
617 }
618
619 static struct vmap_area *find_vmap_area(unsigned long addr)
620 {
621         struct vmap_area *va;
622
623         spin_lock(&vmap_area_lock);
624         va = __find_vmap_area(addr);
625         spin_unlock(&vmap_area_lock);
626
627         return va;
628 }
629
630 static void free_unmap_vmap_area_addr(unsigned long addr)
631 {
632         struct vmap_area *va;
633
634         va = find_vmap_area(addr);
635         BUG_ON(!va);
636         free_unmap_vmap_area(va);
637 }
638
639
640 /*** Per cpu kva allocator ***/
641
642 /*
643  * vmap space is limited especially on 32 bit architectures. Ensure there is
644  * room for at least 16 percpu vmap blocks per CPU.
645  */
646 /*
647  * If we had a constant VMALLOC_START and VMALLOC_END, we'd like to be able
648  * to #define VMALLOC_SPACE             (VMALLOC_END-VMALLOC_START). Guess
649  * instead (we just need a rough idea)
650  */
651 #if BITS_PER_LONG == 32
652 #define VMALLOC_SPACE           (128UL*1024*1024)
653 #else
654 #define VMALLOC_SPACE           (128UL*1024*1024*1024)
655 #endif
656
657 #define VMALLOC_PAGES           (VMALLOC_SPACE / PAGE_SIZE)
658 #define VMAP_MAX_ALLOC          BITS_PER_LONG   /* 256K with 4K pages */
659 #define VMAP_BBMAP_BITS_MAX     1024    /* 4MB with 4K pages */
660 #define VMAP_BBMAP_BITS_MIN     (VMAP_MAX_ALLOC*2)
661 #define VMAP_MIN(x, y)          ((x) < (y) ? (x) : (y)) /* can't use min() */
662 #define VMAP_MAX(x, y)          ((x) > (y) ? (x) : (y)) /* can't use max() */
663 #define VMAP_BBMAP_BITS         VMAP_MIN(VMAP_BBMAP_BITS_MAX,           \
664                                         VMAP_MAX(VMAP_BBMAP_BITS_MIN,   \
665                                                 VMALLOC_PAGES / NR_CPUS / 16))
666
667 #define VMAP_BLOCK_SIZE         (VMAP_BBMAP_BITS * PAGE_SIZE)
668
669 static bool vmap_initialized __read_mostly = false;
670
671 struct vmap_block_queue {
672         spinlock_t lock;
673         struct list_head free;
674         struct list_head dirty;
675         unsigned int nr_dirty;
676 };
677
678 struct vmap_block {
679         spinlock_t lock;
680         struct vmap_area *va;
681         struct vmap_block_queue *vbq;
682         unsigned long free, dirty;
683         DECLARE_BITMAP(alloc_map, VMAP_BBMAP_BITS);
684         DECLARE_BITMAP(dirty_map, VMAP_BBMAP_BITS);
685         union {
686                 struct list_head free_list;
687                 struct rcu_head rcu_head;
688         };
689 };
690
691 /* Queue of free and dirty vmap blocks, for allocation and flushing purposes */
692 static DEFINE_PER_CPU(struct vmap_block_queue, vmap_block_queue);
693
694 /*
695  * Radix tree of vmap blocks, indexed by address, to quickly find a vmap block
696  * in the free path. Could get rid of this if we change the API to return a
697  * "cookie" from alloc, to be passed to free. But no big deal yet.
698  */
699 static DEFINE_SPINLOCK(vmap_block_tree_lock);
700 static RADIX_TREE(vmap_block_tree, GFP_ATOMIC);
701
702 /*
703  * We should probably have a fallback mechanism to allocate virtual memory
704  * out of partially filled vmap blocks. However vmap block sizing should be
705  * fairly reasonable according to the vmalloc size, so it shouldn't be a
706  * big problem.
707  */
708
709 static unsigned long addr_to_vb_idx(unsigned long addr)
710 {
711         addr -= VMALLOC_START & ~(VMAP_BLOCK_SIZE-1);
712         addr /= VMAP_BLOCK_SIZE;
713         return addr;
714 }
715
716 static struct vmap_block *new_vmap_block(gfp_t gfp_mask)
717 {
718         struct vmap_block_queue *vbq;
719         struct vmap_block *vb;
720         struct vmap_area *va;
721         unsigned long vb_idx;
722         int node, err;
723
724         node = numa_node_id();
725
726         vb = kmalloc_node(sizeof(struct vmap_block),
727                         gfp_mask & GFP_RECLAIM_MASK, node);
728         if (unlikely(!vb))
729                 return ERR_PTR(-ENOMEM);
730
731         va = alloc_vmap_area(VMAP_BLOCK_SIZE, VMAP_BLOCK_SIZE,
732                                         VMALLOC_START, VMALLOC_END,
733                                         node, gfp_mask);
734         if (unlikely(IS_ERR(va))) {
735                 kfree(vb);
736                 return ERR_PTR(PTR_ERR(va));
737         }
738
739         err = radix_tree_preload(gfp_mask);
740         if (unlikely(err)) {
741                 kfree(vb);
742                 free_vmap_area(va);
743                 return ERR_PTR(err);
744         }
745
746         spin_lock_init(&vb->lock);
747         vb->va = va;
748         vb->free = VMAP_BBMAP_BITS;
749         vb->dirty = 0;
750         bitmap_zero(vb->alloc_map, VMAP_BBMAP_BITS);
751         bitmap_zero(vb->dirty_map, VMAP_BBMAP_BITS);
752         INIT_LIST_HEAD(&vb->free_list);
753
754         vb_idx = addr_to_vb_idx(va->va_start);
755         spin_lock(&vmap_block_tree_lock);
756         err = radix_tree_insert(&vmap_block_tree, vb_idx, vb);
757         spin_unlock(&vmap_block_tree_lock);
758         BUG_ON(err);
759         radix_tree_preload_end();
760
761         vbq = &get_cpu_var(vmap_block_queue);
762         vb->vbq = vbq;
763         spin_lock(&vbq->lock);
764         list_add(&vb->free_list, &vbq->free);
765         spin_unlock(&vbq->lock);
766         put_cpu_var(vmap_cpu_blocks);
767
768         return vb;
769 }
770
771 static void rcu_free_vb(struct rcu_head *head)
772 {
773         struct vmap_block *vb = container_of(head, struct vmap_block, rcu_head);
774
775         kfree(vb);
776 }
777
778 static void free_vmap_block(struct vmap_block *vb)
779 {
780         struct vmap_block *tmp;
781         unsigned long vb_idx;
782
783         BUG_ON(!list_empty(&vb->free_list));
784
785         vb_idx = addr_to_vb_idx(vb->va->va_start);
786         spin_lock(&vmap_block_tree_lock);
787         tmp = radix_tree_delete(&vmap_block_tree, vb_idx);
788         spin_unlock(&vmap_block_tree_lock);
789         BUG_ON(tmp != vb);
790
791         free_unmap_vmap_area_noflush(vb->va);
792         call_rcu(&vb->rcu_head, rcu_free_vb);
793 }
794
795 static void *vb_alloc(unsigned long size, gfp_t gfp_mask)
796 {
797         struct vmap_block_queue *vbq;
798         struct vmap_block *vb;
799         unsigned long addr = 0;
800         unsigned int order;
801
802         BUG_ON(size & ~PAGE_MASK);
803         BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
804         order = get_order(size);
805
806 again:
807         rcu_read_lock();
808         vbq = &get_cpu_var(vmap_block_queue);
809         list_for_each_entry_rcu(vb, &vbq->free, free_list) {
810                 int i;
811
812                 spin_lock(&vb->lock);
813                 i = bitmap_find_free_region(vb->alloc_map,
814                                                 VMAP_BBMAP_BITS, order);
815
816                 if (i >= 0) {
817                         addr = vb->va->va_start + (i << PAGE_SHIFT);
818                         BUG_ON(addr_to_vb_idx(addr) !=
819                                         addr_to_vb_idx(vb->va->va_start));
820                         vb->free -= 1UL << order;
821                         if (vb->free == 0) {
822                                 spin_lock(&vbq->lock);
823                                 list_del_init(&vb->free_list);
824                                 spin_unlock(&vbq->lock);
825                         }
826                         spin_unlock(&vb->lock);
827                         break;
828                 }
829                 spin_unlock(&vb->lock);
830         }
831         put_cpu_var(vmap_cpu_blocks);
832         rcu_read_unlock();
833
834         if (!addr) {
835                 vb = new_vmap_block(gfp_mask);
836                 if (IS_ERR(vb))
837                         return vb;
838                 goto again;
839         }
840
841         return (void *)addr;
842 }
843
844 static void vb_free(const void *addr, unsigned long size)
845 {
846         unsigned long offset;
847         unsigned long vb_idx;
848         unsigned int order;
849         struct vmap_block *vb;
850
851         BUG_ON(size & ~PAGE_MASK);
852         BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
853
854         flush_cache_vunmap((unsigned long)addr, (unsigned long)addr + size);
855
856         order = get_order(size);
857
858         offset = (unsigned long)addr & (VMAP_BLOCK_SIZE - 1);
859
860         vb_idx = addr_to_vb_idx((unsigned long)addr);
861         rcu_read_lock();
862         vb = radix_tree_lookup(&vmap_block_tree, vb_idx);
863         rcu_read_unlock();
864         BUG_ON(!vb);
865
866         spin_lock(&vb->lock);
867         bitmap_allocate_region(vb->dirty_map, offset >> PAGE_SHIFT, order);
868
869         vb->dirty += 1UL << order;
870         if (vb->dirty == VMAP_BBMAP_BITS) {
871                 BUG_ON(vb->free || !list_empty(&vb->free_list));
872                 spin_unlock(&vb->lock);
873                 free_vmap_block(vb);
874         } else
875                 spin_unlock(&vb->lock);
876 }
877
878 /**
879  * vm_unmap_aliases - unmap outstanding lazy aliases in the vmap layer
880  *
881  * The vmap/vmalloc layer lazily flushes kernel virtual mappings primarily
882  * to amortize TLB flushing overheads. What this means is that any page you
883  * have now, may, in a former life, have been mapped into kernel virtual
884  * address by the vmap layer and so there might be some CPUs with TLB entries
885  * still referencing that page (additional to the regular 1:1 kernel mapping).
886  *
887  * vm_unmap_aliases flushes all such lazy mappings. After it returns, we can
888  * be sure that none of the pages we have control over will have any aliases
889  * from the vmap layer.
890  */
891 void vm_unmap_aliases(void)
892 {
893         unsigned long start = ULONG_MAX, end = 0;
894         int cpu;
895         int flush = 0;
896
897         if (unlikely(!vmap_initialized))
898                 return;
899
900         for_each_possible_cpu(cpu) {
901                 struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu);
902                 struct vmap_block *vb;
903
904                 rcu_read_lock();
905                 list_for_each_entry_rcu(vb, &vbq->free, free_list) {
906                         int i;
907
908                         spin_lock(&vb->lock);
909                         i = find_first_bit(vb->dirty_map, VMAP_BBMAP_BITS);
910                         while (i < VMAP_BBMAP_BITS) {
911                                 unsigned long s, e;
912                                 int j;
913                                 j = find_next_zero_bit(vb->dirty_map,
914                                         VMAP_BBMAP_BITS, i);
915
916                                 s = vb->va->va_start + (i << PAGE_SHIFT);
917                                 e = vb->va->va_start + (j << PAGE_SHIFT);
918                                 vunmap_page_range(s, e);
919                                 flush = 1;
920
921                                 if (s < start)
922                                         start = s;
923                                 if (e > end)
924                                         end = e;
925
926                                 i = j;
927                                 i = find_next_bit(vb->dirty_map,
928                                                         VMAP_BBMAP_BITS, i);
929                         }
930                         spin_unlock(&vb->lock);
931                 }
932                 rcu_read_unlock();
933         }
934
935         __purge_vmap_area_lazy(&start, &end, 1, flush);
936 }
937 EXPORT_SYMBOL_GPL(vm_unmap_aliases);
938
939 /**
940  * vm_unmap_ram - unmap linear kernel address space set up by vm_map_ram
941  * @mem: the pointer returned by vm_map_ram
942  * @count: the count passed to that vm_map_ram call (cannot unmap partial)
943  */
944 void vm_unmap_ram(const void *mem, unsigned int count)
945 {
946         unsigned long size = count << PAGE_SHIFT;
947         unsigned long addr = (unsigned long)mem;
948
949         BUG_ON(!addr);
950         BUG_ON(addr < VMALLOC_START);
951         BUG_ON(addr > VMALLOC_END);
952         BUG_ON(addr & (PAGE_SIZE-1));
953
954         debug_check_no_locks_freed(mem, size);
955         vmap_debug_free_range(addr, addr+size);
956
957         if (likely(count <= VMAP_MAX_ALLOC))
958                 vb_free(mem, size);
959         else
960                 free_unmap_vmap_area_addr(addr);
961 }
962 EXPORT_SYMBOL(vm_unmap_ram);
963
964 /**
965  * vm_map_ram - map pages linearly into kernel virtual address (vmalloc space)
966  * @pages: an array of pointers to the pages to be mapped
967  * @count: number of pages
968  * @node: prefer to allocate data structures on this node
969  * @prot: memory protection to use. PAGE_KERNEL for regular RAM
970  *
971  * Returns: a pointer to the address that has been mapped, or %NULL on failure
972  */
973 void *vm_map_ram(struct page **pages, unsigned int count, int node, pgprot_t prot)
974 {
975         unsigned long size = count << PAGE_SHIFT;
976         unsigned long addr;
977         void *mem;
978
979         if (likely(count <= VMAP_MAX_ALLOC)) {
980                 mem = vb_alloc(size, GFP_KERNEL);
981                 if (IS_ERR(mem))
982                         return NULL;
983                 addr = (unsigned long)mem;
984         } else {
985                 struct vmap_area *va;
986                 va = alloc_vmap_area(size, PAGE_SIZE,
987                                 VMALLOC_START, VMALLOC_END, node, GFP_KERNEL);
988                 if (IS_ERR(va))
989                         return NULL;
990
991                 addr = va->va_start;
992                 mem = (void *)addr;
993         }
994         if (vmap_page_range(addr, addr + size, prot, pages) < 0) {
995                 vm_unmap_ram(mem, count);
996                 return NULL;
997         }
998         return mem;
999 }
1000 EXPORT_SYMBOL(vm_map_ram);
1001
1002 /**
1003  * vm_area_register_early - register vmap area early during boot
1004  * @vm: vm_struct to register
1005  * @align: requested alignment
1006  *
1007  * This function is used to register kernel vm area before
1008  * vmalloc_init() is called.  @vm->size and @vm->flags should contain
1009  * proper values on entry and other fields should be zero.  On return,
1010  * vm->addr contains the allocated address.
1011  *
1012  * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING.
1013  */
1014 void __init vm_area_register_early(struct vm_struct *vm, size_t align)
1015 {
1016         static size_t vm_init_off __initdata;
1017         unsigned long addr;
1018
1019         addr = ALIGN(VMALLOC_START + vm_init_off, align);
1020         vm_init_off = PFN_ALIGN(addr + vm->size) - VMALLOC_START;
1021
1022         vm->addr = (void *)addr;
1023
1024         vm->next = vmlist;
1025         vmlist = vm;
1026 }
1027
1028 void __init vmalloc_init(void)
1029 {
1030         struct vmap_area *va;
1031         struct vm_struct *tmp;
1032         int i;
1033
1034         for_each_possible_cpu(i) {
1035                 struct vmap_block_queue *vbq;
1036
1037                 vbq = &per_cpu(vmap_block_queue, i);
1038                 spin_lock_init(&vbq->lock);
1039                 INIT_LIST_HEAD(&vbq->free);
1040                 INIT_LIST_HEAD(&vbq->dirty);
1041                 vbq->nr_dirty = 0;
1042         }
1043
1044         /* Import existing vmlist entries. */
1045         for (tmp = vmlist; tmp; tmp = tmp->next) {
1046                 va = kzalloc(sizeof(struct vmap_area), GFP_NOWAIT);
1047                 va->flags = tmp->flags | VM_VM_AREA;
1048                 va->va_start = (unsigned long)tmp->addr;
1049                 va->va_end = va->va_start + tmp->size;
1050                 __insert_vmap_area(va);
1051         }
1052
1053         vmap_area_pcpu_hole = VMALLOC_END;
1054
1055         vmap_initialized = true;
1056 }
1057
1058 /**
1059  * map_kernel_range_noflush - map kernel VM area with the specified pages
1060  * @addr: start of the VM area to map
1061  * @size: size of the VM area to map
1062  * @prot: page protection flags to use
1063  * @pages: pages to map
1064  *
1065  * Map PFN_UP(@size) pages at @addr.  The VM area @addr and @size
1066  * specify should have been allocated using get_vm_area() and its
1067  * friends.
1068  *
1069  * NOTE:
1070  * This function does NOT do any cache flushing.  The caller is
1071  * responsible for calling flush_cache_vmap() on to-be-mapped areas
1072  * before calling this function.
1073  *
1074  * RETURNS:
1075  * The number of pages mapped on success, -errno on failure.
1076  */
1077 int map_kernel_range_noflush(unsigned long addr, unsigned long size,
1078                              pgprot_t prot, struct page **pages)
1079 {
1080         return vmap_page_range_noflush(addr, addr + size, prot, pages);
1081 }
1082
1083 /**
1084  * unmap_kernel_range_noflush - unmap kernel VM area
1085  * @addr: start of the VM area to unmap
1086  * @size: size of the VM area to unmap
1087  *
1088  * Unmap PFN_UP(@size) pages at @addr.  The VM area @addr and @size
1089  * specify should have been allocated using get_vm_area() and its
1090  * friends.
1091  *
1092  * NOTE:
1093  * This function does NOT do any cache flushing.  The caller is
1094  * responsible for calling flush_cache_vunmap() on to-be-mapped areas
1095  * before calling this function and flush_tlb_kernel_range() after.
1096  */
1097 void unmap_kernel_range_noflush(unsigned long addr, unsigned long size)
1098 {
1099         vunmap_page_range(addr, addr + size);
1100 }
1101
1102 /**
1103  * unmap_kernel_range - unmap kernel VM area and flush cache and TLB
1104  * @addr: start of the VM area to unmap
1105  * @size: size of the VM area to unmap
1106  *
1107  * Similar to unmap_kernel_range_noflush() but flushes vcache before
1108  * the unmapping and tlb after.
1109  */
1110 void unmap_kernel_range(unsigned long addr, unsigned long size)
1111 {
1112         unsigned long end = addr + size;
1113
1114         flush_cache_vunmap(addr, end);
1115         vunmap_page_range(addr, end);
1116         flush_tlb_kernel_range(addr, end);
1117 }
1118
1119 int map_vm_area(struct vm_struct *area, pgprot_t prot, struct page ***pages)
1120 {
1121         unsigned long addr = (unsigned long)area->addr;
1122         unsigned long end = addr + area->size - PAGE_SIZE;
1123         int err;
1124
1125         err = vmap_page_range(addr, end, prot, *pages);
1126         if (err > 0) {
1127                 *pages += err;
1128                 err = 0;
1129         }
1130
1131         return err;
1132 }
1133 EXPORT_SYMBOL_GPL(map_vm_area);
1134
1135 /*** Old vmalloc interfaces ***/
1136 DEFINE_RWLOCK(vmlist_lock);
1137 struct vm_struct *vmlist;
1138
1139 static void insert_vmalloc_vm(struct vm_struct *vm, struct vmap_area *va,
1140                               unsigned long flags, void *caller)
1141 {
1142         struct vm_struct *tmp, **p;
1143
1144         vm->flags = flags;
1145         vm->addr = (void *)va->va_start;
1146         vm->size = va->va_end - va->va_start;
1147         vm->caller = caller;
1148         va->private = vm;
1149         va->flags |= VM_VM_AREA;
1150
1151         write_lock(&vmlist_lock);
1152         for (p = &vmlist; (tmp = *p) != NULL; p = &tmp->next) {
1153                 if (tmp->addr >= vm->addr)
1154                         break;
1155         }
1156         vm->next = *p;
1157         *p = vm;
1158         write_unlock(&vmlist_lock);
1159 }
1160
1161 static struct vm_struct *__get_vm_area_node(unsigned long size,
1162                 unsigned long align, unsigned long flags, unsigned long start,
1163                 unsigned long end, int node, gfp_t gfp_mask, void *caller)
1164 {
1165         static struct vmap_area *va;
1166         struct vm_struct *area;
1167
1168         BUG_ON(in_interrupt());
1169         if (flags & VM_IOREMAP) {
1170                 int bit = fls(size);
1171
1172                 if (bit > IOREMAP_MAX_ORDER)
1173                         bit = IOREMAP_MAX_ORDER;
1174                 else if (bit < PAGE_SHIFT)
1175                         bit = PAGE_SHIFT;
1176
1177                 align = 1ul << bit;
1178         }
1179
1180         size = PAGE_ALIGN(size);
1181         if (unlikely(!size))
1182                 return NULL;
1183
1184         area = kzalloc_node(sizeof(*area), gfp_mask & GFP_RECLAIM_MASK, node);
1185         if (unlikely(!area))
1186                 return NULL;
1187
1188         /*
1189          * We always allocate a guard page.
1190          */
1191         size += PAGE_SIZE;
1192
1193         va = alloc_vmap_area(size, align, start, end, node, gfp_mask);
1194         if (IS_ERR(va)) {
1195                 kfree(area);
1196                 return NULL;
1197         }
1198
1199         insert_vmalloc_vm(area, va, flags, caller);
1200         return area;
1201 }
1202
1203 struct vm_struct *__get_vm_area(unsigned long size, unsigned long flags,
1204                                 unsigned long start, unsigned long end)
1205 {
1206         return __get_vm_area_node(size, 1, flags, start, end, -1, GFP_KERNEL,
1207                                                 __builtin_return_address(0));
1208 }
1209 EXPORT_SYMBOL_GPL(__get_vm_area);
1210
1211 struct vm_struct *__get_vm_area_caller(unsigned long size, unsigned long flags,
1212                                        unsigned long start, unsigned long end,
1213                                        void *caller)
1214 {
1215         return __get_vm_area_node(size, 1, flags, start, end, -1, GFP_KERNEL,
1216                                   caller);
1217 }
1218
1219 /**
1220  *      get_vm_area  -  reserve a contiguous kernel virtual area
1221  *      @size:          size of the area
1222  *      @flags:         %VM_IOREMAP for I/O mappings or VM_ALLOC
1223  *
1224  *      Search an area of @size in the kernel virtual mapping area,
1225  *      and reserved it for out purposes.  Returns the area descriptor
1226  *      on success or %NULL on failure.
1227  */
1228 struct vm_struct *get_vm_area(unsigned long size, unsigned long flags)
1229 {
1230         return __get_vm_area_node(size, 1, flags, VMALLOC_START, VMALLOC_END,
1231                                 -1, GFP_KERNEL, __builtin_return_address(0));
1232 }
1233
1234 struct vm_struct *get_vm_area_caller(unsigned long size, unsigned long flags,
1235                                 void *caller)
1236 {
1237         return __get_vm_area_node(size, 1, flags, VMALLOC_START, VMALLOC_END,
1238                                                 -1, GFP_KERNEL, caller);
1239 }
1240
1241 struct vm_struct *get_vm_area_node(unsigned long size, unsigned long flags,
1242                                    int node, gfp_t gfp_mask)
1243 {
1244         return __get_vm_area_node(size, 1, flags, VMALLOC_START, VMALLOC_END,
1245                                   node, gfp_mask, __builtin_return_address(0));
1246 }
1247
1248 static struct vm_struct *find_vm_area(const void *addr)
1249 {
1250         struct vmap_area *va;
1251
1252         va = find_vmap_area((unsigned long)addr);
1253         if (va && va->flags & VM_VM_AREA)
1254                 return va->private;
1255
1256         return NULL;
1257 }
1258
1259 /**
1260  *      remove_vm_area  -  find and remove a continuous kernel virtual area
1261  *      @addr:          base address
1262  *
1263  *      Search for the kernel VM area starting at @addr, and remove it.
1264  *      This function returns the found VM area, but using it is NOT safe
1265  *      on SMP machines, except for its size or flags.
1266  */
1267 struct vm_struct *remove_vm_area(const void *addr)
1268 {
1269         struct vmap_area *va;
1270
1271         va = find_vmap_area((unsigned long)addr);
1272         if (va && va->flags & VM_VM_AREA) {
1273                 struct vm_struct *vm = va->private;
1274                 struct vm_struct *tmp, **p;
1275                 /*
1276                  * remove from list and disallow access to this vm_struct
1277                  * before unmap. (address range confliction is maintained by
1278                  * vmap.)
1279                  */
1280                 write_lock(&vmlist_lock);
1281                 for (p = &vmlist; (tmp = *p) != vm; p = &tmp->next)
1282                         ;
1283                 *p = tmp->next;
1284                 write_unlock(&vmlist_lock);
1285
1286                 vmap_debug_free_range(va->va_start, va->va_end);
1287                 free_unmap_vmap_area(va);
1288                 vm->size -= PAGE_SIZE;
1289
1290                 return vm;
1291         }
1292         return NULL;
1293 }
1294
1295 static void __vunmap(const void *addr, int deallocate_pages)
1296 {
1297         struct vm_struct *area;
1298
1299         if (!addr)
1300                 return;
1301
1302         if ((PAGE_SIZE-1) & (unsigned long)addr) {
1303                 WARN(1, KERN_ERR "Trying to vfree() bad address (%p)\n", addr);
1304                 return;
1305         }
1306
1307         area = remove_vm_area(addr);
1308         if (unlikely(!area)) {
1309                 WARN(1, KERN_ERR "Trying to vfree() nonexistent vm area (%p)\n",
1310                                 addr);
1311                 return;
1312         }
1313
1314         debug_check_no_locks_freed(addr, area->size);
1315         debug_check_no_obj_freed(addr, area->size);
1316
1317         if (deallocate_pages) {
1318                 int i;
1319
1320                 for (i = 0; i < area->nr_pages; i++) {
1321                         struct page *page = area->pages[i];
1322
1323                         BUG_ON(!page);
1324                         __free_page(page);
1325                 }
1326
1327                 if (area->flags & VM_VPAGES)
1328                         vfree(area->pages);
1329                 else
1330                         kfree(area->pages);
1331         }
1332
1333         kfree(area);
1334         return;
1335 }
1336
1337 /**
1338  *      vfree  -  release memory allocated by vmalloc()
1339  *      @addr:          memory base address
1340  *
1341  *      Free the virtually continuous memory area starting at @addr, as
1342  *      obtained from vmalloc(), vmalloc_32() or __vmalloc(). If @addr is
1343  *      NULL, no operation is performed.
1344  *
1345  *      Must not be called in interrupt context.
1346  */
1347 void vfree(const void *addr)
1348 {
1349         BUG_ON(in_interrupt());
1350
1351         kmemleak_free(addr);
1352
1353         __vunmap(addr, 1);
1354 }
1355 EXPORT_SYMBOL(vfree);
1356
1357 /**
1358  *      vunmap  -  release virtual mapping obtained by vmap()
1359  *      @addr:          memory base address
1360  *
1361  *      Free the virtually contiguous memory area starting at @addr,
1362  *      which was created from the page array passed to vmap().
1363  *
1364  *      Must not be called in interrupt context.
1365  */
1366 void vunmap(const void *addr)
1367 {
1368         BUG_ON(in_interrupt());
1369         might_sleep();
1370         __vunmap(addr, 0);
1371 }
1372 EXPORT_SYMBOL(vunmap);
1373
1374 /**
1375  *      vmap  -  map an array of pages into virtually contiguous space
1376  *      @pages:         array of page pointers
1377  *      @count:         number of pages to map
1378  *      @flags:         vm_area->flags
1379  *      @prot:          page protection for the mapping
1380  *
1381  *      Maps @count pages from @pages into contiguous kernel virtual
1382  *      space.
1383  */
1384 void *vmap(struct page **pages, unsigned int count,
1385                 unsigned long flags, pgprot_t prot)
1386 {
1387         struct vm_struct *area;
1388
1389         might_sleep();
1390
1391         if (count > totalram_pages)
1392                 return NULL;
1393
1394         area = get_vm_area_caller((count << PAGE_SHIFT), flags,
1395                                         __builtin_return_address(0));
1396         if (!area)
1397                 return NULL;
1398
1399         if (map_vm_area(area, prot, &pages)) {
1400                 vunmap(area->addr);
1401                 return NULL;
1402         }
1403
1404         return area->addr;
1405 }
1406 EXPORT_SYMBOL(vmap);
1407
1408 static void *__vmalloc_node(unsigned long size, unsigned long align,
1409                             gfp_t gfp_mask, pgprot_t prot,
1410                             int node, void *caller);
1411 static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask,
1412                                  pgprot_t prot, int node, void *caller)
1413 {
1414         struct page **pages;
1415         unsigned int nr_pages, array_size, i;
1416         gfp_t nested_gfp = (gfp_mask & GFP_RECLAIM_MASK) | __GFP_ZERO;
1417 #ifdef CONFIG_XEN
1418         gfp_t dma_mask = gfp_mask & (__GFP_DMA | __GFP_DMA32);
1419
1420         BUILD_BUG_ON((__GFP_DMA | __GFP_DMA32) != (__GFP_DMA + __GFP_DMA32));
1421         if (dma_mask == (__GFP_DMA | __GFP_DMA32))
1422                 gfp_mask &= ~(__GFP_DMA | __GFP_DMA32);
1423 #endif
1424
1425         nr_pages = (area->size - PAGE_SIZE) >> PAGE_SHIFT;
1426         array_size = (nr_pages * sizeof(struct page *));
1427
1428         area->nr_pages = nr_pages;
1429         /* Please note that the recursion is strictly bounded. */
1430         if (array_size > PAGE_SIZE) {
1431                 pages = __vmalloc_node(array_size, 1,
1432                                        nested_gfp | __GFP_HIGHMEM,
1433                                        PAGE_KERNEL, node, caller);
1434                 area->flags |= VM_VPAGES;
1435         } else {
1436                 pages = kmalloc_node(array_size, nested_gfp, node);
1437         }
1438         area->pages = pages;
1439         area->caller = caller;
1440         if (!area->pages) {
1441                 remove_vm_area(area->addr);
1442                 kfree(area);
1443                 return NULL;
1444         }
1445
1446         for (i = 0; i < area->nr_pages; i++) {
1447                 struct page *page;
1448
1449                 if (node < 0)
1450                         page = alloc_page(gfp_mask);
1451                 else
1452                         page = alloc_pages_node(node, gfp_mask, 0);
1453
1454                 if (unlikely(!page)) {
1455                         /* Successfully allocated i pages, free them in __vunmap() */
1456                         area->nr_pages = i;
1457                         goto fail;
1458                 }
1459                 area->pages[i] = page;
1460 #ifdef CONFIG_XEN
1461                 if (dma_mask) {
1462                         if (xen_limit_pages_to_max_mfn(page, 0, 32)) {
1463                                 area->nr_pages = i + 1;
1464                                 goto fail;
1465                         }
1466                         if (gfp_mask & __GFP_ZERO)
1467                                 clear_highpage(page);
1468                 }
1469 #endif
1470         }
1471
1472         if (map_vm_area(area, prot, &pages))
1473                 goto fail;
1474         return area->addr;
1475
1476 fail:
1477         vfree(area->addr);
1478         return NULL;
1479 }
1480
1481 void *__vmalloc_area(struct vm_struct *area, gfp_t gfp_mask, pgprot_t prot)
1482 {
1483         void *addr = __vmalloc_area_node(area, gfp_mask, prot, -1,
1484                                          __builtin_return_address(0));
1485
1486         /*
1487          * A ref_count = 3 is needed because the vm_struct and vmap_area
1488          * structures allocated in the __get_vm_area_node() function contain
1489          * references to the virtual address of the vmalloc'ed block.
1490          */
1491         kmemleak_alloc(addr, area->size - PAGE_SIZE, 3, gfp_mask);
1492
1493         return addr;
1494 }
1495
1496 /**
1497  *      __vmalloc_node  -  allocate virtually contiguous memory
1498  *      @size:          allocation size
1499  *      @align:         desired alignment
1500  *      @gfp_mask:      flags for the page level allocator
1501  *      @prot:          protection mask for the allocated pages
1502  *      @node:          node to use for allocation or -1
1503  *      @caller:        caller's return address
1504  *
1505  *      Allocate enough pages to cover @size from the page level
1506  *      allocator with @gfp_mask flags.  Map them into contiguous
1507  *      kernel virtual space, using a pagetable protection of @prot.
1508  */
1509 static void *__vmalloc_node(unsigned long size, unsigned long align,
1510                             gfp_t gfp_mask, pgprot_t prot,
1511                             int node, void *caller)
1512 {
1513         struct vm_struct *area;
1514         void *addr;
1515         unsigned long real_size = size;
1516
1517         size = PAGE_ALIGN(size);
1518         if (!size || (size >> PAGE_SHIFT) > totalram_pages)
1519                 return NULL;
1520
1521         area = __get_vm_area_node(size, align, VM_ALLOC, VMALLOC_START,
1522                                   VMALLOC_END, node, gfp_mask, caller);
1523
1524         if (!area)
1525                 return NULL;
1526
1527         addr = __vmalloc_area_node(area, gfp_mask, prot, node, caller);
1528
1529         /*
1530          * A ref_count = 3 is needed because the vm_struct and vmap_area
1531          * structures allocated in the __get_vm_area_node() function contain
1532          * references to the virtual address of the vmalloc'ed block.
1533          */
1534         kmemleak_alloc(addr, real_size, 3, gfp_mask);
1535
1536         return addr;
1537 }
1538
1539 void *__vmalloc(unsigned long size, gfp_t gfp_mask, pgprot_t prot)
1540 {
1541         return __vmalloc_node(size, 1, gfp_mask, prot, -1,
1542                                 __builtin_return_address(0));
1543 }
1544 EXPORT_SYMBOL(__vmalloc);
1545
1546 /**
1547  *      vmalloc  -  allocate virtually contiguous memory
1548  *      @size:          allocation size
1549  *      Allocate enough pages to cover @size from the page level
1550  *      allocator and map them into contiguous kernel virtual space.
1551  *
1552  *      For tight control over page level allocator and protection flags
1553  *      use __vmalloc() instead.
1554  */
1555 void *vmalloc(unsigned long size)
1556 {
1557         return __vmalloc_node(size, 1, GFP_KERNEL | __GFP_HIGHMEM, PAGE_KERNEL,
1558                                         -1, __builtin_return_address(0));
1559 }
1560 EXPORT_SYMBOL(vmalloc);
1561
1562 /**
1563  * vmalloc_user - allocate zeroed virtually contiguous memory for userspace
1564  * @size: allocation size
1565  *
1566  * The resulting memory area is zeroed so it can be mapped to userspace
1567  * without leaking data.
1568  */
1569 void *vmalloc_user(unsigned long size)
1570 {
1571         struct vm_struct *area;
1572         void *ret;
1573
1574         ret = __vmalloc_node(size, SHMLBA,
1575                              GFP_KERNEL | __GFP_HIGHMEM | __GFP_ZERO,
1576                              PAGE_KERNEL, -1, __builtin_return_address(0));
1577         if (ret) {
1578                 area = find_vm_area(ret);
1579                 area->flags |= VM_USERMAP;
1580         }
1581         return ret;
1582 }
1583 EXPORT_SYMBOL(vmalloc_user);
1584
1585 /**
1586  *      vmalloc_node  -  allocate memory on a specific node
1587  *      @size:          allocation size
1588  *      @node:          numa node
1589  *
1590  *      Allocate enough pages to cover @size from the page level
1591  *      allocator and map them into contiguous kernel virtual space.
1592  *
1593  *      For tight control over page level allocator and protection flags
1594  *      use __vmalloc() instead.
1595  */
1596 void *vmalloc_node(unsigned long size, int node)
1597 {
1598         return __vmalloc_node(size, 1, GFP_KERNEL | __GFP_HIGHMEM, PAGE_KERNEL,
1599                                         node, __builtin_return_address(0));
1600 }
1601 EXPORT_SYMBOL(vmalloc_node);
1602
1603 #ifndef PAGE_KERNEL_EXEC
1604 # define PAGE_KERNEL_EXEC PAGE_KERNEL
1605 #endif
1606
1607 /**
1608  *      vmalloc_exec  -  allocate virtually contiguous, executable memory
1609  *      @size:          allocation size
1610  *
1611  *      Kernel-internal function to allocate enough pages to cover @size
1612  *      the page level allocator and map them into contiguous and
1613  *      executable kernel virtual space.
1614  *
1615  *      For tight control over page level allocator and protection flags
1616  *      use __vmalloc() instead.
1617  */
1618
1619 void *vmalloc_exec(unsigned long size)
1620 {
1621         return __vmalloc_node(size, 1, GFP_KERNEL | __GFP_HIGHMEM, PAGE_KERNEL_EXEC,
1622                               -1, __builtin_return_address(0));
1623 }
1624
1625 #if defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA32)
1626 #define GFP_VMALLOC32 GFP_DMA32 | GFP_KERNEL
1627 #elif defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA)
1628 #define GFP_VMALLOC32 GFP_DMA | GFP_KERNEL
1629 #elif defined(CONFIG_XEN)
1630 #define GFP_VMALLOC32 __GFP_DMA | __GFP_DMA32 | GFP_KERNEL
1631 #else
1632 #define GFP_VMALLOC32 GFP_KERNEL
1633 #endif
1634
1635 /**
1636  *      vmalloc_32  -  allocate virtually contiguous memory (32bit addressable)
1637  *      @size:          allocation size
1638  *
1639  *      Allocate enough 32bit PA addressable pages to cover @size from the
1640  *      page level allocator and map them into contiguous kernel virtual space.
1641  */
1642 void *vmalloc_32(unsigned long size)
1643 {
1644         return __vmalloc_node(size, 1, GFP_VMALLOC32, PAGE_KERNEL,
1645                               -1, __builtin_return_address(0));
1646 }
1647 EXPORT_SYMBOL(vmalloc_32);
1648
1649 /**
1650  * vmalloc_32_user - allocate zeroed virtually contiguous 32bit memory
1651  *      @size:          allocation size
1652  *
1653  * The resulting memory area is 32bit addressable and zeroed so it can be
1654  * mapped to userspace without leaking data.
1655  */
1656 void *vmalloc_32_user(unsigned long size)
1657 {
1658         struct vm_struct *area;
1659         void *ret;
1660
1661         ret = __vmalloc_node(size, 1, GFP_VMALLOC32 | __GFP_ZERO, PAGE_KERNEL,
1662                              -1, __builtin_return_address(0));
1663         if (ret) {
1664                 area = find_vm_area(ret);
1665                 area->flags |= VM_USERMAP;
1666         }
1667         return ret;
1668 }
1669 EXPORT_SYMBOL(vmalloc_32_user);
1670
1671 /*
1672  * small helper routine , copy contents to buf from addr.
1673  * If the page is not present, fill zero.
1674  */
1675
1676 static int aligned_vread(char *buf, char *addr, unsigned long count)
1677 {
1678         struct page *p;
1679         int copied = 0;
1680
1681         while (count) {
1682                 unsigned long offset, length;
1683
1684                 offset = (unsigned long)addr & ~PAGE_MASK;
1685                 length = PAGE_SIZE - offset;
1686                 if (length > count)
1687                         length = count;
1688                 p = vmalloc_to_page(addr);
1689                 /*
1690                  * To do safe access to this _mapped_ area, we need
1691                  * lock. But adding lock here means that we need to add
1692                  * overhead of vmalloc()/vfree() calles for this _debug_
1693                  * interface, rarely used. Instead of that, we'll use
1694                  * kmap() and get small overhead in this access function.
1695                  */
1696                 if (p) {
1697                         /*
1698                          * we can expect USER0 is not used (see vread/vwrite's
1699                          * function description)
1700                          */
1701                         void *map = kmap_atomic(p, KM_USER0);
1702                         memcpy(buf, map + offset, length);
1703                         kunmap_atomic(map, KM_USER0);
1704                 } else
1705                         memset(buf, 0, length);
1706
1707                 addr += length;
1708                 buf += length;
1709                 copied += length;
1710                 count -= length;
1711         }
1712         return copied;
1713 }
1714
1715 static int aligned_vwrite(char *buf, char *addr, unsigned long count)
1716 {
1717         struct page *p;
1718         int copied = 0;
1719
1720         while (count) {
1721                 unsigned long offset, length;
1722
1723                 offset = (unsigned long)addr & ~PAGE_MASK;
1724                 length = PAGE_SIZE - offset;
1725                 if (length > count)
1726                         length = count;
1727                 p = vmalloc_to_page(addr);
1728                 /*
1729                  * To do safe access to this _mapped_ area, we need
1730                  * lock. But adding lock here means that we need to add
1731                  * overhead of vmalloc()/vfree() calles for this _debug_
1732                  * interface, rarely used. Instead of that, we'll use
1733                  * kmap() and get small overhead in this access function.
1734                  */
1735                 if (p) {
1736                         /*
1737                          * we can expect USER0 is not used (see vread/vwrite's
1738                          * function description)
1739                          */
1740                         void *map = kmap_atomic(p, KM_USER0);
1741                         memcpy(map + offset, buf, length);
1742                         kunmap_atomic(map, KM_USER0);
1743                 }
1744                 addr += length;
1745                 buf += length;
1746                 copied += length;
1747                 count -= length;
1748         }
1749         return copied;
1750 }
1751
1752 /**
1753  *      vread() -  read vmalloc area in a safe way.
1754  *      @buf:           buffer for reading data
1755  *      @addr:          vm address.
1756  *      @count:         number of bytes to be read.
1757  *
1758  *      Returns # of bytes which addr and buf should be increased.
1759  *      (same number to @count). Returns 0 if [addr...addr+count) doesn't
1760  *      includes any intersect with alive vmalloc area.
1761  *
1762  *      This function checks that addr is a valid vmalloc'ed area, and
1763  *      copy data from that area to a given buffer. If the given memory range
1764  *      of [addr...addr+count) includes some valid address, data is copied to
1765  *      proper area of @buf. If there are memory holes, they'll be zero-filled.
1766  *      IOREMAP area is treated as memory hole and no copy is done.
1767  *
1768  *      If [addr...addr+count) doesn't includes any intersects with alive
1769  *      vm_struct area, returns 0.
1770  *      @buf should be kernel's buffer. Because this function uses KM_USER0,
1771  *      the caller should guarantee KM_USER0 is not used.
1772  *
1773  *      Note: In usual ops, vread() is never necessary because the caller
1774  *      should know vmalloc() area is valid and can use memcpy().
1775  *      This is for routines which have to access vmalloc area without
1776  *      any informaion, as /dev/kmem.
1777  *
1778  */
1779
1780 long vread(char *buf, char *addr, unsigned long count)
1781 {
1782         struct vm_struct *tmp;
1783         char *vaddr, *buf_start = buf;
1784         unsigned long buflen = count;
1785         unsigned long n;
1786
1787         /* Don't allow overflow */
1788         if ((unsigned long) addr + count < count)
1789                 count = -(unsigned long) addr;
1790
1791         read_lock(&vmlist_lock);
1792         for (tmp = vmlist; count && tmp; tmp = tmp->next) {
1793                 vaddr = (char *) tmp->addr;
1794                 if (addr >= vaddr + tmp->size - PAGE_SIZE)
1795                         continue;
1796                 while (addr < vaddr) {
1797                         if (count == 0)
1798                                 goto finished;
1799                         *buf = '\0';
1800                         buf++;
1801                         addr++;
1802                         count--;
1803                 }
1804                 n = vaddr + tmp->size - PAGE_SIZE - addr;
1805                 if (n > count)
1806                         n = count;
1807                 if (!(tmp->flags & VM_IOREMAP))
1808                         aligned_vread(buf, addr, n);
1809                 else /* IOREMAP area is treated as memory hole */
1810                         memset(buf, 0, n);
1811                 buf += n;
1812                 addr += n;
1813                 count -= n;
1814         }
1815 finished:
1816         read_unlock(&vmlist_lock);
1817
1818         if (buf == buf_start)
1819                 return 0;
1820         /* zero-fill memory holes */
1821         if (buf != buf_start + buflen)
1822                 memset(buf, 0, buflen - (buf - buf_start));
1823
1824         return buflen;
1825 }
1826
1827 /**
1828  *      vwrite() -  write vmalloc area in a safe way.
1829  *      @buf:           buffer for source data
1830  *      @addr:          vm address.
1831  *      @count:         number of bytes to be read.
1832  *
1833  *      Returns # of bytes which addr and buf should be incresed.
1834  *      (same number to @count).
1835  *      If [addr...addr+count) doesn't includes any intersect with valid
1836  *      vmalloc area, returns 0.
1837  *
1838  *      This function checks that addr is a valid vmalloc'ed area, and
1839  *      copy data from a buffer to the given addr. If specified range of
1840  *      [addr...addr+count) includes some valid address, data is copied from
1841  *      proper area of @buf. If there are memory holes, no copy to hole.
1842  *      IOREMAP area is treated as memory hole and no copy is done.
1843  *
1844  *      If [addr...addr+count) doesn't includes any intersects with alive
1845  *      vm_struct area, returns 0.
1846  *      @buf should be kernel's buffer. Because this function uses KM_USER0,
1847  *      the caller should guarantee KM_USER0 is not used.
1848  *
1849  *      Note: In usual ops, vwrite() is never necessary because the caller
1850  *      should know vmalloc() area is valid and can use memcpy().
1851  *      This is for routines which have to access vmalloc area without
1852  *      any informaion, as /dev/kmem.
1853  *
1854  *      The caller should guarantee KM_USER1 is not used.
1855  */
1856
1857 long vwrite(char *buf, char *addr, unsigned long count)
1858 {
1859         struct vm_struct *tmp;
1860         char *vaddr;
1861         unsigned long n, buflen;
1862         int copied = 0;
1863
1864         /* Don't allow overflow */
1865         if ((unsigned long) addr + count < count)
1866                 count = -(unsigned long) addr;
1867         buflen = count;
1868
1869         read_lock(&vmlist_lock);
1870         for (tmp = vmlist; count && tmp; tmp = tmp->next) {
1871                 vaddr = (char *) tmp->addr;
1872                 if (addr >= vaddr + tmp->size - PAGE_SIZE)
1873                         continue;
1874                 while (addr < vaddr) {
1875                         if (count == 0)
1876                                 goto finished;
1877                         buf++;
1878                         addr++;
1879                         count--;
1880                 }
1881                 n = vaddr + tmp->size - PAGE_SIZE - addr;
1882                 if (n > count)
1883                         n = count;
1884                 if (!(tmp->flags & VM_IOREMAP)) {
1885                         aligned_vwrite(buf, addr, n);
1886                         copied++;
1887                 }
1888                 buf += n;
1889                 addr += n;
1890                 count -= n;
1891         }
1892 finished:
1893         read_unlock(&vmlist_lock);
1894         if (!copied)
1895                 return 0;
1896         return buflen;
1897 }
1898
1899 /**
1900  *      remap_vmalloc_range  -  map vmalloc pages to userspace
1901  *      @vma:           vma to cover (map full range of vma)
1902  *      @addr:          vmalloc memory
1903  *      @pgoff:         number of pages into addr before first page to map
1904  *
1905  *      Returns:        0 for success, -Exxx on failure
1906  *
1907  *      This function checks that addr is a valid vmalloc'ed area, and
1908  *      that it is big enough to cover the vma. Will return failure if
1909  *      that criteria isn't met.
1910  *
1911  *      Similar to remap_pfn_range() (see mm/memory.c)
1912  */
1913 int remap_vmalloc_range(struct vm_area_struct *vma, void *addr,
1914                                                 unsigned long pgoff)
1915 {
1916         struct vm_struct *area;
1917         unsigned long uaddr = vma->vm_start;
1918         unsigned long usize = vma->vm_end - vma->vm_start;
1919
1920         if ((PAGE_SIZE-1) & (unsigned long)addr)
1921                 return -EINVAL;
1922
1923         area = find_vm_area(addr);
1924         if (!area)
1925                 return -EINVAL;
1926
1927         if (!(area->flags & VM_USERMAP))
1928                 return -EINVAL;
1929
1930         if (usize + (pgoff << PAGE_SHIFT) > area->size - PAGE_SIZE)
1931                 return -EINVAL;
1932
1933         addr += pgoff << PAGE_SHIFT;
1934         do {
1935                 struct page *page = vmalloc_to_page(addr);
1936                 int ret;
1937
1938                 ret = vm_insert_page(vma, uaddr, page);
1939                 if (ret)
1940                         return ret;
1941
1942                 uaddr += PAGE_SIZE;
1943                 addr += PAGE_SIZE;
1944                 usize -= PAGE_SIZE;
1945         } while (usize > 0);
1946
1947         /* Prevent "things" like memory migration? VM_flags need a cleanup... */
1948         vma->vm_flags |= VM_RESERVED;
1949
1950         return 0;
1951 }
1952 EXPORT_SYMBOL(remap_vmalloc_range);
1953
1954 /*
1955  * Implement a stub for vmalloc_sync_all() if the architecture chose not to
1956  * have one.
1957  */
1958 void  __attribute__((weak)) vmalloc_sync_all(void)
1959 {
1960 }
1961
1962
1963 static int f(pte_t *pte, pgtable_t table, unsigned long addr, void *data)
1964 {
1965         /* apply_to_page_range() does all the hard work. */
1966         return 0;
1967 }
1968
1969 /**
1970  *      alloc_vm_area - allocate a range of kernel address space
1971  *      @size:          size of the area
1972  *
1973  *      Returns:        NULL on failure, vm_struct on success
1974  *
1975  *      This function reserves a range of kernel address space, and
1976  *      allocates pagetables to map that range.  No actual mappings
1977  *      are created.  If the kernel address space is not shared
1978  *      between processes, it syncs the pagetable across all
1979  *      processes.
1980  */
1981 struct vm_struct *alloc_vm_area(size_t size)
1982 {
1983         struct vm_struct *area;
1984
1985         area = get_vm_area_caller(size, VM_IOREMAP,
1986                                 __builtin_return_address(0));
1987         if (area == NULL)
1988                 return NULL;
1989
1990         /*
1991          * This ensures that page tables are constructed for this region
1992          * of kernel virtual address space and mapped into init_mm.
1993          */
1994         if (apply_to_page_range(&init_mm, (unsigned long)area->addr,
1995                                 area->size, f, NULL)) {
1996                 free_vm_area(area);
1997                 return NULL;
1998         }
1999
2000         /* Make sure the pagetables are constructed in process kernel
2001            mappings */
2002         vmalloc_sync_all();
2003
2004         return area;
2005 }
2006 EXPORT_SYMBOL_GPL(alloc_vm_area);
2007
2008 void free_vm_area(struct vm_struct *area)
2009 {
2010         struct vm_struct *ret;
2011         ret = remove_vm_area(area->addr);
2012         BUG_ON(ret != area);
2013         kfree(area);
2014 }
2015 EXPORT_SYMBOL_GPL(free_vm_area);
2016
2017 static struct vmap_area *node_to_va(struct rb_node *n)
2018 {
2019         return n ? rb_entry(n, struct vmap_area, rb_node) : NULL;
2020 }
2021
2022 /**
2023  * pvm_find_next_prev - find the next and prev vmap_area surrounding @end
2024  * @end: target address
2025  * @pnext: out arg for the next vmap_area
2026  * @pprev: out arg for the previous vmap_area
2027  *
2028  * Returns: %true if either or both of next and prev are found,
2029  *          %false if no vmap_area exists
2030  *
2031  * Find vmap_areas end addresses of which enclose @end.  ie. if not
2032  * NULL, *pnext->va_end > @end and *pprev->va_end <= @end.
2033  */
2034 static bool pvm_find_next_prev(unsigned long end,
2035                                struct vmap_area **pnext,
2036                                struct vmap_area **pprev)
2037 {
2038         struct rb_node *n = vmap_area_root.rb_node;
2039         struct vmap_area *va = NULL;
2040
2041         while (n) {
2042                 va = rb_entry(n, struct vmap_area, rb_node);
2043                 if (end < va->va_end)
2044                         n = n->rb_left;
2045                 else if (end > va->va_end)
2046                         n = n->rb_right;
2047                 else
2048                         break;
2049         }
2050
2051         if (!va)
2052                 return false;
2053
2054         if (va->va_end > end) {
2055                 *pnext = va;
2056                 *pprev = node_to_va(rb_prev(&(*pnext)->rb_node));
2057         } else {
2058                 *pprev = va;
2059                 *pnext = node_to_va(rb_next(&(*pprev)->rb_node));
2060         }
2061         return true;
2062 }
2063
2064 /**
2065  * pvm_determine_end - find the highest aligned address between two vmap_areas
2066  * @pnext: in/out arg for the next vmap_area
2067  * @pprev: in/out arg for the previous vmap_area
2068  * @align: alignment
2069  *
2070  * Returns: determined end address
2071  *
2072  * Find the highest aligned address between *@pnext and *@pprev below
2073  * VMALLOC_END.  *@pnext and *@pprev are adjusted so that the aligned
2074  * down address is between the end addresses of the two vmap_areas.
2075  *
2076  * Please note that the address returned by this function may fall
2077  * inside *@pnext vmap_area.  The caller is responsible for checking
2078  * that.
2079  */
2080 static unsigned long pvm_determine_end(struct vmap_area **pnext,
2081                                        struct vmap_area **pprev,
2082                                        unsigned long align)
2083 {
2084         const unsigned long vmalloc_end = VMALLOC_END & ~(align - 1);
2085         unsigned long addr;
2086
2087         if (*pnext)
2088                 addr = min((*pnext)->va_start & ~(align - 1), vmalloc_end);
2089         else
2090                 addr = vmalloc_end;
2091
2092         while (*pprev && (*pprev)->va_end > addr) {
2093                 *pnext = *pprev;
2094                 *pprev = node_to_va(rb_prev(&(*pnext)->rb_node));
2095         }
2096
2097         return addr;
2098 }
2099
2100 /**
2101  * pcpu_get_vm_areas - allocate vmalloc areas for percpu allocator
2102  * @offsets: array containing offset of each area
2103  * @sizes: array containing size of each area
2104  * @nr_vms: the number of areas to allocate
2105  * @align: alignment, all entries in @offsets and @sizes must be aligned to this
2106  * @gfp_mask: allocation mask
2107  *
2108  * Returns: kmalloc'd vm_struct pointer array pointing to allocated
2109  *          vm_structs on success, %NULL on failure
2110  *
2111  * Percpu allocator wants to use congruent vm areas so that it can
2112  * maintain the offsets among percpu areas.  This function allocates
2113  * congruent vmalloc areas for it.  These areas tend to be scattered
2114  * pretty far, distance between two areas easily going up to
2115  * gigabytes.  To avoid interacting with regular vmallocs, these areas
2116  * are allocated from top.
2117  *
2118  * Despite its complicated look, this allocator is rather simple.  It
2119  * does everything top-down and scans areas from the end looking for
2120  * matching slot.  While scanning, if any of the areas overlaps with
2121  * existing vmap_area, the base address is pulled down to fit the
2122  * area.  Scanning is repeated till all the areas fit and then all
2123  * necessary data structres are inserted and the result is returned.
2124  */
2125 struct vm_struct **pcpu_get_vm_areas(const unsigned long *offsets,
2126                                      const size_t *sizes, int nr_vms,
2127                                      size_t align, gfp_t gfp_mask)
2128 {
2129         const unsigned long vmalloc_start = ALIGN(VMALLOC_START, align);
2130         const unsigned long vmalloc_end = VMALLOC_END & ~(align - 1);
2131         struct vmap_area **vas, *prev, *next;
2132         struct vm_struct **vms;
2133         int area, area2, last_area, term_area;
2134         unsigned long base, start, end, last_end;
2135         bool purged = false;
2136
2137         gfp_mask &= GFP_RECLAIM_MASK;
2138
2139         /* verify parameters and allocate data structures */
2140         BUG_ON(align & ~PAGE_MASK || !is_power_of_2(align));
2141         for (last_area = 0, area = 0; area < nr_vms; area++) {
2142                 start = offsets[area];
2143                 end = start + sizes[area];
2144
2145                 /* is everything aligned properly? */
2146                 BUG_ON(!IS_ALIGNED(offsets[area], align));
2147                 BUG_ON(!IS_ALIGNED(sizes[area], align));
2148
2149                 /* detect the area with the highest address */
2150                 if (start > offsets[last_area])
2151                         last_area = area;
2152
2153                 for (area2 = 0; area2 < nr_vms; area2++) {
2154                         unsigned long start2 = offsets[area2];
2155                         unsigned long end2 = start2 + sizes[area2];
2156
2157                         if (area2 == area)
2158                                 continue;
2159
2160                         BUG_ON(start2 >= start && start2 < end);
2161                         BUG_ON(end2 <= end && end2 > start);
2162                 }
2163         }
2164         last_end = offsets[last_area] + sizes[last_area];
2165
2166         if (vmalloc_end - vmalloc_start < last_end) {
2167                 WARN_ON(true);
2168                 return NULL;
2169         }
2170
2171         vms = kzalloc(sizeof(vms[0]) * nr_vms, gfp_mask);
2172         vas = kzalloc(sizeof(vas[0]) * nr_vms, gfp_mask);
2173         if (!vas || !vms)
2174                 goto err_free;
2175
2176         for (area = 0; area < nr_vms; area++) {
2177                 vas[area] = kzalloc(sizeof(struct vmap_area), gfp_mask);
2178                 vms[area] = kzalloc(sizeof(struct vm_struct), gfp_mask);
2179                 if (!vas[area] || !vms[area])
2180                         goto err_free;
2181         }
2182 retry:
2183         spin_lock(&vmap_area_lock);
2184
2185         /* start scanning - we scan from the top, begin with the last area */
2186         area = term_area = last_area;
2187         start = offsets[area];
2188         end = start + sizes[area];
2189
2190         if (!pvm_find_next_prev(vmap_area_pcpu_hole, &next, &prev)) {
2191                 base = vmalloc_end - last_end;
2192                 goto found;
2193         }
2194         base = pvm_determine_end(&next, &prev, align) - end;
2195
2196         while (true) {
2197                 BUG_ON(next && next->va_end <= base + end);
2198                 BUG_ON(prev && prev->va_end > base + end);
2199
2200                 /*
2201                  * base might have underflowed, add last_end before
2202                  * comparing.
2203                  */
2204                 if (base + last_end < vmalloc_start + last_end) {
2205                         spin_unlock(&vmap_area_lock);
2206                         if (!purged) {
2207                                 purge_vmap_area_lazy();
2208                                 purged = true;
2209                                 goto retry;
2210                         }
2211                         goto err_free;
2212                 }
2213
2214                 /*
2215                  * If next overlaps, move base downwards so that it's
2216                  * right below next and then recheck.
2217                  */
2218                 if (next && next->va_start < base + end) {
2219                         base = pvm_determine_end(&next, &prev, align) - end;
2220                         term_area = area;
2221                         continue;
2222                 }
2223
2224                 /*
2225                  * If prev overlaps, shift down next and prev and move
2226                  * base so that it's right below new next and then
2227                  * recheck.
2228                  */
2229                 if (prev && prev->va_end > base + start)  {
2230                         next = prev;
2231                         prev = node_to_va(rb_prev(&next->rb_node));
2232                         base = pvm_determine_end(&next, &prev, align) - end;
2233                         term_area = area;
2234                         continue;
2235                 }
2236
2237                 /*
2238                  * This area fits, move on to the previous one.  If
2239                  * the previous one is the terminal one, we're done.
2240                  */
2241                 area = (area + nr_vms - 1) % nr_vms;
2242                 if (area == term_area)
2243                         break;
2244                 start = offsets[area];
2245                 end = start + sizes[area];
2246                 pvm_find_next_prev(base + end, &next, &prev);
2247         }
2248 found:
2249         /* we've found a fitting base, insert all va's */
2250         for (area = 0; area < nr_vms; area++) {
2251                 struct vmap_area *va = vas[area];
2252
2253                 va->va_start = base + offsets[area];
2254                 va->va_end = va->va_start + sizes[area];
2255                 __insert_vmap_area(va);
2256         }
2257
2258         vmap_area_pcpu_hole = base + offsets[last_area];
2259
2260         spin_unlock(&vmap_area_lock);
2261
2262         /* insert all vm's */
2263         for (area = 0; area < nr_vms; area++)
2264                 insert_vmalloc_vm(vms[area], vas[area], VM_ALLOC,
2265                                   pcpu_get_vm_areas);
2266
2267         kfree(vas);
2268         return vms;
2269
2270 err_free:
2271         for (area = 0; area < nr_vms; area++) {
2272                 if (vas)
2273                         kfree(vas[area]);
2274                 if (vms)
2275                         kfree(vms[area]);
2276         }
2277         kfree(vas);
2278         kfree(vms);
2279         return NULL;
2280 }
2281
2282 /**
2283  * pcpu_free_vm_areas - free vmalloc areas for percpu allocator
2284  * @vms: vm_struct pointer array returned by pcpu_get_vm_areas()
2285  * @nr_vms: the number of allocated areas
2286  *
2287  * Free vm_structs and the array allocated by pcpu_get_vm_areas().
2288  */
2289 void pcpu_free_vm_areas(struct vm_struct **vms, int nr_vms)
2290 {
2291         int i;
2292
2293         for (i = 0; i < nr_vms; i++)
2294                 free_vm_area(vms[i]);
2295         kfree(vms);
2296 }
2297
2298 #ifdef CONFIG_PROC_FS
2299 static void *s_start(struct seq_file *m, loff_t *pos)
2300 {
2301         loff_t n = *pos;
2302         struct vm_struct *v;
2303
2304         read_lock(&vmlist_lock);
2305         v = vmlist;
2306         while (n > 0 && v) {
2307                 n--;
2308                 v = v->next;
2309         }
2310         if (!n)
2311                 return v;
2312
2313         return NULL;
2314
2315 }
2316
2317 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
2318 {
2319         struct vm_struct *v = p;
2320
2321         ++*pos;
2322         return v->next;
2323 }
2324
2325 static void s_stop(struct seq_file *m, void *p)
2326 {
2327         read_unlock(&vmlist_lock);
2328 }
2329
2330 static void show_numa_info(struct seq_file *m, struct vm_struct *v)
2331 {
2332         if (NUMA_BUILD) {
2333                 unsigned int nr, *counters = m->private;
2334
2335                 if (!counters)
2336                         return;
2337
2338                 memset(counters, 0, nr_node_ids * sizeof(unsigned int));
2339
2340                 for (nr = 0; nr < v->nr_pages; nr++)
2341                         counters[page_to_nid(v->pages[nr])]++;
2342
2343                 for_each_node_state(nr, N_HIGH_MEMORY)
2344                         if (counters[nr])
2345                                 seq_printf(m, " N%u=%u", nr, counters[nr]);
2346         }
2347 }
2348
2349 static int s_show(struct seq_file *m, void *p)
2350 {
2351         struct vm_struct *v = p;
2352
2353         seq_printf(m, "0x%p-0x%p %7ld",
2354                 v->addr, v->addr + v->size, v->size);
2355
2356         if (v->caller) {
2357                 char buff[KSYM_SYMBOL_LEN];
2358
2359                 seq_putc(m, ' ');
2360                 sprint_symbol(buff, (unsigned long)v->caller);
2361                 seq_puts(m, buff);
2362         }
2363
2364         if (v->nr_pages)
2365                 seq_printf(m, " pages=%d", v->nr_pages);
2366
2367         if (v->phys_addr)
2368                 seq_printf(m, " phys=%lx", v->phys_addr);
2369
2370         if (v->flags & VM_IOREMAP)
2371                 seq_printf(m, " ioremap");
2372
2373         if (v->flags & VM_ALLOC)
2374                 seq_printf(m, " vmalloc");
2375
2376         if (v->flags & VM_MAP)
2377                 seq_printf(m, " vmap");
2378
2379         if (v->flags & VM_USERMAP)
2380                 seq_printf(m, " user");
2381
2382         if (v->flags & VM_VPAGES)
2383                 seq_printf(m, " vpages");
2384
2385         show_numa_info(m, v);
2386         seq_putc(m, '\n');
2387         return 0;
2388 }
2389
2390 static const struct seq_operations vmalloc_op = {
2391         .start = s_start,
2392         .next = s_next,
2393         .stop = s_stop,
2394         .show = s_show,
2395 };
2396
2397 static int vmalloc_open(struct inode *inode, struct file *file)
2398 {
2399         unsigned int *ptr = NULL;
2400         int ret;
2401
2402         if (NUMA_BUILD)
2403                 ptr = kmalloc(nr_node_ids * sizeof(unsigned int), GFP_KERNEL);
2404         ret = seq_open(file, &vmalloc_op);
2405         if (!ret) {
2406                 struct seq_file *m = file->private_data;
2407                 m->private = ptr;
2408         } else
2409                 kfree(ptr);
2410         return ret;
2411 }
2412
2413 static const struct file_operations proc_vmalloc_operations = {
2414         .open           = vmalloc_open,
2415         .read           = seq_read,
2416         .llseek         = seq_lseek,
2417         .release        = seq_release_private,
2418 };
2419
2420 static int __init proc_vmalloc_init(void)
2421 {
2422         proc_create("vmallocinfo", S_IRUSR, NULL, &proc_vmalloc_operations);
2423         return 0;
2424 }
2425 module_init(proc_vmalloc_init);
2426 #endif
2427