]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - mm/vmalloc.c
mm/vmalloc: simplify augment_tree_propagate_check()
[mirror_ubuntu-jammy-kernel.git] / mm / vmalloc.c
CommitLineData
457c8996 1// SPDX-License-Identifier: GPL-2.0-only
1da177e4
LT
2/*
3 * linux/mm/vmalloc.c
4 *
5 * Copyright (C) 1993 Linus Torvalds
6 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
7 * SMP-safe vmalloc/vfree/ioremap, Tigran Aivazian <tigran@veritas.com>, May 2000
8 * Major rework to support vmap/vunmap, Christoph Hellwig, SGI, August 2002
930fc45a 9 * Numa awareness, Christoph Lameter, SGI, June 2005
1da177e4
LT
10 */
11
db64fe02 12#include <linux/vmalloc.h>
1da177e4
LT
13#include <linux/mm.h>
14#include <linux/module.h>
15#include <linux/highmem.h>
c3edc401 16#include <linux/sched/signal.h>
1da177e4
LT
17#include <linux/slab.h>
18#include <linux/spinlock.h>
19#include <linux/interrupt.h>
5f6a6a9c 20#include <linux/proc_fs.h>
a10aa579 21#include <linux/seq_file.h>
868b104d 22#include <linux/set_memory.h>
3ac7fe5a 23#include <linux/debugobjects.h>
23016969 24#include <linux/kallsyms.h>
db64fe02 25#include <linux/list.h>
4da56b99 26#include <linux/notifier.h>
db64fe02 27#include <linux/rbtree.h>
0f14599c 28#include <linux/xarray.h>
db64fe02 29#include <linux/rcupdate.h>
f0aa6617 30#include <linux/pfn.h>
89219d37 31#include <linux/kmemleak.h>
60063497 32#include <linux/atomic.h>
3b32123d 33#include <linux/compiler.h>
32fcfd40 34#include <linux/llist.h>
0f616be1 35#include <linux/bitops.h>
68ad4a33 36#include <linux/rbtree_augmented.h>
bdebd6a2 37#include <linux/overflow.h>
3b32123d 38
7c0f6ba6 39#include <linux/uaccess.h>
1da177e4 40#include <asm/tlbflush.h>
2dca6999 41#include <asm/shmparam.h>
1da177e4 42
dd56b046 43#include "internal.h"
2a681cfa 44#include "pgalloc-track.h"
dd56b046 45
186525bd
IM
46bool is_vmalloc_addr(const void *x)
47{
48 unsigned long addr = (unsigned long)x;
49
50 return addr >= VMALLOC_START && addr < VMALLOC_END;
51}
52EXPORT_SYMBOL(is_vmalloc_addr);
53
32fcfd40
AV
54struct vfree_deferred {
55 struct llist_head list;
56 struct work_struct wq;
57};
58static DEFINE_PER_CPU(struct vfree_deferred, vfree_deferred);
59
60static void __vunmap(const void *, int);
61
62static void free_work(struct work_struct *w)
63{
64 struct vfree_deferred *p = container_of(w, struct vfree_deferred, wq);
894e58c1
BP
65 struct llist_node *t, *llnode;
66
67 llist_for_each_safe(llnode, t, llist_del_all(&p->list))
68 __vunmap((void *)llnode, 1);
32fcfd40
AV
69}
70
db64fe02 71/*** Page table manipulation functions ***/
b221385b 72
2ba3e694
JR
73static void vunmap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
74 pgtbl_mod_mask *mask)
1da177e4
LT
75{
76 pte_t *pte;
77
78 pte = pte_offset_kernel(pmd, addr);
79 do {
80 pte_t ptent = ptep_get_and_clear(&init_mm, addr, pte);
81 WARN_ON(!pte_none(ptent) && !pte_present(ptent));
82 } while (pte++, addr += PAGE_SIZE, addr != end);
2ba3e694 83 *mask |= PGTBL_PTE_MODIFIED;
1da177e4
LT
84}
85
2ba3e694
JR
86static void vunmap_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,
87 pgtbl_mod_mask *mask)
1da177e4
LT
88{
89 pmd_t *pmd;
90 unsigned long next;
2ba3e694 91 int cleared;
1da177e4
LT
92
93 pmd = pmd_offset(pud, addr);
94 do {
95 next = pmd_addr_end(addr, end);
2ba3e694
JR
96
97 cleared = pmd_clear_huge(pmd);
98 if (cleared || pmd_bad(*pmd))
99 *mask |= PGTBL_PMD_MODIFIED;
100
101 if (cleared)
b9820d8f 102 continue;
1da177e4
LT
103 if (pmd_none_or_clear_bad(pmd))
104 continue;
2ba3e694 105 vunmap_pte_range(pmd, addr, next, mask);
1da177e4
LT
106 } while (pmd++, addr = next, addr != end);
107}
108
2ba3e694
JR
109static void vunmap_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end,
110 pgtbl_mod_mask *mask)
1da177e4
LT
111{
112 pud_t *pud;
113 unsigned long next;
2ba3e694 114 int cleared;
1da177e4 115
c2febafc 116 pud = pud_offset(p4d, addr);
1da177e4
LT
117 do {
118 next = pud_addr_end(addr, end);
2ba3e694
JR
119
120 cleared = pud_clear_huge(pud);
121 if (cleared || pud_bad(*pud))
122 *mask |= PGTBL_PUD_MODIFIED;
123
124 if (cleared)
b9820d8f 125 continue;
1da177e4
LT
126 if (pud_none_or_clear_bad(pud))
127 continue;
2ba3e694 128 vunmap_pmd_range(pud, addr, next, mask);
1da177e4
LT
129 } while (pud++, addr = next, addr != end);
130}
131
2ba3e694
JR
132static void vunmap_p4d_range(pgd_t *pgd, unsigned long addr, unsigned long end,
133 pgtbl_mod_mask *mask)
c2febafc
KS
134{
135 p4d_t *p4d;
136 unsigned long next;
2ba3e694 137 int cleared;
c2febafc
KS
138
139 p4d = p4d_offset(pgd, addr);
140 do {
141 next = p4d_addr_end(addr, end);
2ba3e694
JR
142
143 cleared = p4d_clear_huge(p4d);
144 if (cleared || p4d_bad(*p4d))
145 *mask |= PGTBL_P4D_MODIFIED;
146
147 if (cleared)
c2febafc
KS
148 continue;
149 if (p4d_none_or_clear_bad(p4d))
150 continue;
2ba3e694 151 vunmap_pud_range(p4d, addr, next, mask);
c2febafc
KS
152 } while (p4d++, addr = next, addr != end);
153}
154
b521c43f
CH
155/**
156 * unmap_kernel_range_noflush - unmap kernel VM area
2ba3e694 157 * @start: start of the VM area to unmap
b521c43f
CH
158 * @size: size of the VM area to unmap
159 *
160 * Unmap PFN_UP(@size) pages at @addr. The VM area @addr and @size specify
161 * should have been allocated using get_vm_area() and its friends.
162 *
163 * NOTE:
164 * This function does NOT do any cache flushing. The caller is responsible
165 * for calling flush_cache_vunmap() on to-be-mapped areas before calling this
166 * function and flush_tlb_kernel_range() after.
167 */
2ba3e694 168void unmap_kernel_range_noflush(unsigned long start, unsigned long size)
1da177e4 169{
2ba3e694 170 unsigned long end = start + size;
1da177e4 171 unsigned long next;
b521c43f 172 pgd_t *pgd;
2ba3e694
JR
173 unsigned long addr = start;
174 pgtbl_mod_mask mask = 0;
1da177e4
LT
175
176 BUG_ON(addr >= end);
2ba3e694 177 start = addr;
1da177e4 178 pgd = pgd_offset_k(addr);
1da177e4
LT
179 do {
180 next = pgd_addr_end(addr, end);
2ba3e694
JR
181 if (pgd_bad(*pgd))
182 mask |= PGTBL_PGD_MODIFIED;
1da177e4
LT
183 if (pgd_none_or_clear_bad(pgd))
184 continue;
2ba3e694 185 vunmap_p4d_range(pgd, addr, next, &mask);
1da177e4 186 } while (pgd++, addr = next, addr != end);
2ba3e694
JR
187
188 if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
189 arch_sync_kernel_mappings(start, end);
1da177e4
LT
190}
191
192static int vmap_pte_range(pmd_t *pmd, unsigned long addr,
2ba3e694
JR
193 unsigned long end, pgprot_t prot, struct page **pages, int *nr,
194 pgtbl_mod_mask *mask)
1da177e4
LT
195{
196 pte_t *pte;
197
db64fe02
NP
198 /*
199 * nr is a running index into the array which helps higher level
200 * callers keep track of where we're up to.
201 */
202
2ba3e694 203 pte = pte_alloc_kernel_track(pmd, addr, mask);
1da177e4
LT
204 if (!pte)
205 return -ENOMEM;
206 do {
db64fe02
NP
207 struct page *page = pages[*nr];
208
209 if (WARN_ON(!pte_none(*pte)))
210 return -EBUSY;
211 if (WARN_ON(!page))
1da177e4
LT
212 return -ENOMEM;
213 set_pte_at(&init_mm, addr, pte, mk_pte(page, prot));
db64fe02 214 (*nr)++;
1da177e4 215 } while (pte++, addr += PAGE_SIZE, addr != end);
2ba3e694 216 *mask |= PGTBL_PTE_MODIFIED;
1da177e4
LT
217 return 0;
218}
219
db64fe02 220static int vmap_pmd_range(pud_t *pud, unsigned long addr,
2ba3e694
JR
221 unsigned long end, pgprot_t prot, struct page **pages, int *nr,
222 pgtbl_mod_mask *mask)
1da177e4
LT
223{
224 pmd_t *pmd;
225 unsigned long next;
226
2ba3e694 227 pmd = pmd_alloc_track(&init_mm, pud, addr, mask);
1da177e4
LT
228 if (!pmd)
229 return -ENOMEM;
230 do {
231 next = pmd_addr_end(addr, end);
2ba3e694 232 if (vmap_pte_range(pmd, addr, next, prot, pages, nr, mask))
1da177e4
LT
233 return -ENOMEM;
234 } while (pmd++, addr = next, addr != end);
235 return 0;
236}
237
c2febafc 238static int vmap_pud_range(p4d_t *p4d, unsigned long addr,
2ba3e694
JR
239 unsigned long end, pgprot_t prot, struct page **pages, int *nr,
240 pgtbl_mod_mask *mask)
1da177e4
LT
241{
242 pud_t *pud;
243 unsigned long next;
244
2ba3e694 245 pud = pud_alloc_track(&init_mm, p4d, addr, mask);
1da177e4
LT
246 if (!pud)
247 return -ENOMEM;
248 do {
249 next = pud_addr_end(addr, end);
2ba3e694 250 if (vmap_pmd_range(pud, addr, next, prot, pages, nr, mask))
1da177e4
LT
251 return -ENOMEM;
252 } while (pud++, addr = next, addr != end);
253 return 0;
254}
255
c2febafc 256static int vmap_p4d_range(pgd_t *pgd, unsigned long addr,
2ba3e694
JR
257 unsigned long end, pgprot_t prot, struct page **pages, int *nr,
258 pgtbl_mod_mask *mask)
c2febafc
KS
259{
260 p4d_t *p4d;
261 unsigned long next;
262
2ba3e694 263 p4d = p4d_alloc_track(&init_mm, pgd, addr, mask);
c2febafc
KS
264 if (!p4d)
265 return -ENOMEM;
266 do {
267 next = p4d_addr_end(addr, end);
2ba3e694 268 if (vmap_pud_range(p4d, addr, next, prot, pages, nr, mask))
c2febafc
KS
269 return -ENOMEM;
270 } while (p4d++, addr = next, addr != end);
271 return 0;
272}
273
b521c43f
CH
274/**
275 * map_kernel_range_noflush - map kernel VM area with the specified pages
276 * @addr: start of the VM area to map
277 * @size: size of the VM area to map
278 * @prot: page protection flags to use
279 * @pages: pages to map
db64fe02 280 *
b521c43f
CH
281 * Map PFN_UP(@size) pages at @addr. The VM area @addr and @size specify should
282 * have been allocated using get_vm_area() and its friends.
283 *
284 * NOTE:
285 * This function does NOT do any cache flushing. The caller is responsible for
286 * calling flush_cache_vmap() on to-be-mapped areas before calling this
287 * function.
288 *
289 * RETURNS:
60bb4465 290 * 0 on success, -errno on failure.
db64fe02 291 */
b521c43f
CH
292int map_kernel_range_noflush(unsigned long addr, unsigned long size,
293 pgprot_t prot, struct page **pages)
1da177e4 294{
2ba3e694 295 unsigned long start = addr;
b521c43f 296 unsigned long end = addr + size;
1da177e4 297 unsigned long next;
b521c43f 298 pgd_t *pgd;
db64fe02
NP
299 int err = 0;
300 int nr = 0;
2ba3e694 301 pgtbl_mod_mask mask = 0;
1da177e4
LT
302
303 BUG_ON(addr >= end);
304 pgd = pgd_offset_k(addr);
1da177e4
LT
305 do {
306 next = pgd_addr_end(addr, end);
2ba3e694
JR
307 if (pgd_bad(*pgd))
308 mask |= PGTBL_PGD_MODIFIED;
309 err = vmap_p4d_range(pgd, addr, next, prot, pages, &nr, &mask);
1da177e4 310 if (err)
bf88c8c8 311 return err;
1da177e4 312 } while (pgd++, addr = next, addr != end);
db64fe02 313
2ba3e694
JR
314 if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
315 arch_sync_kernel_mappings(start, end);
316
60bb4465 317 return 0;
1da177e4
LT
318}
319
ed1f324c
CH
320int map_kernel_range(unsigned long start, unsigned long size, pgprot_t prot,
321 struct page **pages)
8fc48985
TH
322{
323 int ret;
324
a29adb62
CH
325 ret = map_kernel_range_noflush(start, size, prot, pages);
326 flush_cache_vmap(start, start + size);
8fc48985
TH
327 return ret;
328}
329
81ac3ad9 330int is_vmalloc_or_module_addr(const void *x)
73bdf0a6
LT
331{
332 /*
ab4f2ee1 333 * ARM, x86-64 and sparc64 put modules in a special place,
73bdf0a6
LT
334 * and fall back on vmalloc() if that fails. Others
335 * just put it in the vmalloc space.
336 */
337#if defined(CONFIG_MODULES) && defined(MODULES_VADDR)
338 unsigned long addr = (unsigned long)x;
339 if (addr >= MODULES_VADDR && addr < MODULES_END)
340 return 1;
341#endif
342 return is_vmalloc_addr(x);
343}
344
48667e7a 345/*
add688fb 346 * Walk a vmap address to the struct page it maps.
48667e7a 347 */
add688fb 348struct page *vmalloc_to_page(const void *vmalloc_addr)
48667e7a
CL
349{
350 unsigned long addr = (unsigned long) vmalloc_addr;
add688fb 351 struct page *page = NULL;
48667e7a 352 pgd_t *pgd = pgd_offset_k(addr);
c2febafc
KS
353 p4d_t *p4d;
354 pud_t *pud;
355 pmd_t *pmd;
356 pte_t *ptep, pte;
48667e7a 357
7aa413de
IM
358 /*
359 * XXX we might need to change this if we add VIRTUAL_BUG_ON for
360 * architectures that do not vmalloc module space
361 */
73bdf0a6 362 VIRTUAL_BUG_ON(!is_vmalloc_or_module_addr(vmalloc_addr));
59ea7463 363
c2febafc
KS
364 if (pgd_none(*pgd))
365 return NULL;
366 p4d = p4d_offset(pgd, addr);
367 if (p4d_none(*p4d))
368 return NULL;
369 pud = pud_offset(p4d, addr);
029c54b0
AB
370
371 /*
372 * Don't dereference bad PUD or PMD (below) entries. This will also
373 * identify huge mappings, which we may encounter on architectures
374 * that define CONFIG_HAVE_ARCH_HUGE_VMAP=y. Such regions will be
375 * identified as vmalloc addresses by is_vmalloc_addr(), but are
376 * not [unambiguously] associated with a struct page, so there is
377 * no correct value to return for them.
378 */
379 WARN_ON_ONCE(pud_bad(*pud));
380 if (pud_none(*pud) || pud_bad(*pud))
c2febafc
KS
381 return NULL;
382 pmd = pmd_offset(pud, addr);
029c54b0
AB
383 WARN_ON_ONCE(pmd_bad(*pmd));
384 if (pmd_none(*pmd) || pmd_bad(*pmd))
c2febafc
KS
385 return NULL;
386
387 ptep = pte_offset_map(pmd, addr);
388 pte = *ptep;
389 if (pte_present(pte))
390 page = pte_page(pte);
391 pte_unmap(ptep);
add688fb 392 return page;
48667e7a 393}
add688fb 394EXPORT_SYMBOL(vmalloc_to_page);
48667e7a
CL
395
396/*
add688fb 397 * Map a vmalloc()-space virtual address to the physical page frame number.
48667e7a 398 */
add688fb 399unsigned long vmalloc_to_pfn(const void *vmalloc_addr)
48667e7a 400{
add688fb 401 return page_to_pfn(vmalloc_to_page(vmalloc_addr));
48667e7a 402}
add688fb 403EXPORT_SYMBOL(vmalloc_to_pfn);
48667e7a 404
db64fe02
NP
405
406/*** Global kva allocator ***/
407
bb850f4d 408#define DEBUG_AUGMENT_PROPAGATE_CHECK 0
a6cf4e0f 409#define DEBUG_AUGMENT_LOWEST_MATCH_CHECK 0
bb850f4d 410
db64fe02 411
db64fe02 412static DEFINE_SPINLOCK(vmap_area_lock);
e36176be 413static DEFINE_SPINLOCK(free_vmap_area_lock);
f1c4069e
JK
414/* Export for kexec only */
415LIST_HEAD(vmap_area_list);
80c4bd7a 416static LLIST_HEAD(vmap_purge_list);
89699605 417static struct rb_root vmap_area_root = RB_ROOT;
68ad4a33 418static bool vmap_initialized __read_mostly;
89699605 419
68ad4a33
URS
420/*
421 * This kmem_cache is used for vmap_area objects. Instead of
422 * allocating from slab we reuse an object from this cache to
423 * make things faster. Especially in "no edge" splitting of
424 * free block.
425 */
426static struct kmem_cache *vmap_area_cachep;
427
428/*
429 * This linked list is used in pair with free_vmap_area_root.
430 * It gives O(1) access to prev/next to perform fast coalescing.
431 */
432static LIST_HEAD(free_vmap_area_list);
433
434/*
435 * This augment red-black tree represents the free vmap space.
436 * All vmap_area objects in this tree are sorted by va->va_start
437 * address. It is used for allocation and merging when a vmap
438 * object is released.
439 *
440 * Each vmap_area node contains a maximum available free block
441 * of its sub-tree, right or left. Therefore it is possible to
442 * find a lowest match of free area.
443 */
444static struct rb_root free_vmap_area_root = RB_ROOT;
445
82dd23e8
URS
446/*
447 * Preload a CPU with one object for "no edge" split case. The
448 * aim is to get rid of allocations from the atomic context, thus
449 * to use more permissive allocation masks.
450 */
451static DEFINE_PER_CPU(struct vmap_area *, ne_fit_preload_node);
452
68ad4a33
URS
453static __always_inline unsigned long
454va_size(struct vmap_area *va)
455{
456 return (va->va_end - va->va_start);
457}
458
459static __always_inline unsigned long
460get_subtree_max_size(struct rb_node *node)
461{
462 struct vmap_area *va;
463
464 va = rb_entry_safe(node, struct vmap_area, rb_node);
465 return va ? va->subtree_max_size : 0;
466}
89699605 467
68ad4a33
URS
468/*
469 * Gets called when remove the node and rotate.
470 */
471static __always_inline unsigned long
472compute_subtree_max_size(struct vmap_area *va)
473{
474 return max3(va_size(va),
475 get_subtree_max_size(va->rb_node.rb_left),
476 get_subtree_max_size(va->rb_node.rb_right));
477}
478
315cc066
ML
479RB_DECLARE_CALLBACKS_MAX(static, free_vmap_area_rb_augment_cb,
480 struct vmap_area, rb_node, unsigned long, subtree_max_size, va_size)
68ad4a33
URS
481
482static void purge_vmap_area_lazy(void);
483static BLOCKING_NOTIFIER_HEAD(vmap_notify_list);
484static unsigned long lazy_max_pages(void);
db64fe02 485
97105f0a
RG
486static atomic_long_t nr_vmalloc_pages;
487
488unsigned long vmalloc_nr_pages(void)
489{
490 return atomic_long_read(&nr_vmalloc_pages);
491}
492
db64fe02 493static struct vmap_area *__find_vmap_area(unsigned long addr)
1da177e4 494{
db64fe02
NP
495 struct rb_node *n = vmap_area_root.rb_node;
496
497 while (n) {
498 struct vmap_area *va;
499
500 va = rb_entry(n, struct vmap_area, rb_node);
501 if (addr < va->va_start)
502 n = n->rb_left;
cef2ac3f 503 else if (addr >= va->va_end)
db64fe02
NP
504 n = n->rb_right;
505 else
506 return va;
507 }
508
509 return NULL;
510}
511
68ad4a33
URS
512/*
513 * This function returns back addresses of parent node
514 * and its left or right link for further processing.
515 */
516static __always_inline struct rb_node **
517find_va_links(struct vmap_area *va,
518 struct rb_root *root, struct rb_node *from,
519 struct rb_node **parent)
520{
521 struct vmap_area *tmp_va;
522 struct rb_node **link;
523
524 if (root) {
525 link = &root->rb_node;
526 if (unlikely(!*link)) {
527 *parent = NULL;
528 return link;
529 }
530 } else {
531 link = &from;
532 }
db64fe02 533
68ad4a33
URS
534 /*
535 * Go to the bottom of the tree. When we hit the last point
536 * we end up with parent rb_node and correct direction, i name
537 * it link, where the new va->rb_node will be attached to.
538 */
539 do {
540 tmp_va = rb_entry(*link, struct vmap_area, rb_node);
db64fe02 541
68ad4a33
URS
542 /*
543 * During the traversal we also do some sanity check.
544 * Trigger the BUG() if there are sides(left/right)
545 * or full overlaps.
546 */
547 if (va->va_start < tmp_va->va_end &&
548 va->va_end <= tmp_va->va_start)
549 link = &(*link)->rb_left;
550 else if (va->va_end > tmp_va->va_start &&
551 va->va_start >= tmp_va->va_end)
552 link = &(*link)->rb_right;
db64fe02
NP
553 else
554 BUG();
68ad4a33
URS
555 } while (*link);
556
557 *parent = &tmp_va->rb_node;
558 return link;
559}
560
561static __always_inline struct list_head *
562get_va_next_sibling(struct rb_node *parent, struct rb_node **link)
563{
564 struct list_head *list;
565
566 if (unlikely(!parent))
567 /*
568 * The red-black tree where we try to find VA neighbors
569 * before merging or inserting is empty, i.e. it means
570 * there is no free vmap space. Normally it does not
571 * happen but we handle this case anyway.
572 */
573 return NULL;
574
575 list = &rb_entry(parent, struct vmap_area, rb_node)->list;
576 return (&parent->rb_right == link ? list->next : list);
577}
578
579static __always_inline void
580link_va(struct vmap_area *va, struct rb_root *root,
581 struct rb_node *parent, struct rb_node **link, struct list_head *head)
582{
583 /*
584 * VA is still not in the list, but we can
585 * identify its future previous list_head node.
586 */
587 if (likely(parent)) {
588 head = &rb_entry(parent, struct vmap_area, rb_node)->list;
589 if (&parent->rb_right != link)
590 head = head->prev;
db64fe02
NP
591 }
592
68ad4a33
URS
593 /* Insert to the rb-tree */
594 rb_link_node(&va->rb_node, parent, link);
595 if (root == &free_vmap_area_root) {
596 /*
597 * Some explanation here. Just perform simple insertion
598 * to the tree. We do not set va->subtree_max_size to
599 * its current size before calling rb_insert_augmented().
600 * It is because of we populate the tree from the bottom
601 * to parent levels when the node _is_ in the tree.
602 *
603 * Therefore we set subtree_max_size to zero after insertion,
604 * to let __augment_tree_propagate_from() puts everything to
605 * the correct order later on.
606 */
607 rb_insert_augmented(&va->rb_node,
608 root, &free_vmap_area_rb_augment_cb);
609 va->subtree_max_size = 0;
610 } else {
611 rb_insert_color(&va->rb_node, root);
612 }
db64fe02 613
68ad4a33
URS
614 /* Address-sort this list */
615 list_add(&va->list, head);
db64fe02
NP
616}
617
68ad4a33
URS
618static __always_inline void
619unlink_va(struct vmap_area *va, struct rb_root *root)
620{
460e42d1
URS
621 if (WARN_ON(RB_EMPTY_NODE(&va->rb_node)))
622 return;
db64fe02 623
460e42d1
URS
624 if (root == &free_vmap_area_root)
625 rb_erase_augmented(&va->rb_node,
626 root, &free_vmap_area_rb_augment_cb);
627 else
628 rb_erase(&va->rb_node, root);
629
630 list_del(&va->list);
631 RB_CLEAR_NODE(&va->rb_node);
68ad4a33
URS
632}
633
bb850f4d
URS
634#if DEBUG_AUGMENT_PROPAGATE_CHECK
635static void
da27c9ed 636augment_tree_propagate_check(void)
bb850f4d
URS
637{
638 struct vmap_area *va;
da27c9ed 639 unsigned long computed_size;
bb850f4d 640
da27c9ed
URS
641 list_for_each_entry(va, &free_vmap_area_list, list) {
642 computed_size = compute_subtree_max_size(va);
643 if (computed_size != va->subtree_max_size)
644 pr_emerg("tree is corrupted: %lu, %lu\n",
645 va_size(va), va->subtree_max_size);
bb850f4d 646 }
bb850f4d
URS
647}
648#endif
649
68ad4a33
URS
650/*
651 * This function populates subtree_max_size from bottom to upper
652 * levels starting from VA point. The propagation must be done
653 * when VA size is modified by changing its va_start/va_end. Or
654 * in case of newly inserting of VA to the tree.
655 *
656 * It means that __augment_tree_propagate_from() must be called:
657 * - After VA has been inserted to the tree(free path);
658 * - After VA has been shrunk(allocation path);
659 * - After VA has been increased(merging path).
660 *
661 * Please note that, it does not mean that upper parent nodes
662 * and their subtree_max_size are recalculated all the time up
663 * to the root node.
664 *
665 * 4--8
666 * /\
667 * / \
668 * / \
669 * 2--2 8--8
670 *
671 * For example if we modify the node 4, shrinking it to 2, then
672 * no any modification is required. If we shrink the node 2 to 1
673 * its subtree_max_size is updated only, and set to 1. If we shrink
674 * the node 8 to 6, then its subtree_max_size is set to 6 and parent
675 * node becomes 4--6.
676 */
677static __always_inline void
678augment_tree_propagate_from(struct vmap_area *va)
679{
680 struct rb_node *node = &va->rb_node;
681 unsigned long new_va_sub_max_size;
682
683 while (node) {
684 va = rb_entry(node, struct vmap_area, rb_node);
685 new_va_sub_max_size = compute_subtree_max_size(va);
686
687 /*
688 * If the newly calculated maximum available size of the
689 * subtree is equal to the current one, then it means that
690 * the tree is propagated correctly. So we have to stop at
691 * this point to save cycles.
692 */
693 if (va->subtree_max_size == new_va_sub_max_size)
694 break;
695
696 va->subtree_max_size = new_va_sub_max_size;
697 node = rb_parent(&va->rb_node);
698 }
bb850f4d
URS
699
700#if DEBUG_AUGMENT_PROPAGATE_CHECK
da27c9ed 701 augment_tree_propagate_check();
bb850f4d 702#endif
68ad4a33
URS
703}
704
705static void
706insert_vmap_area(struct vmap_area *va,
707 struct rb_root *root, struct list_head *head)
708{
709 struct rb_node **link;
710 struct rb_node *parent;
711
712 link = find_va_links(va, root, NULL, &parent);
713 link_va(va, root, parent, link, head);
714}
715
716static void
717insert_vmap_area_augment(struct vmap_area *va,
718 struct rb_node *from, struct rb_root *root,
719 struct list_head *head)
720{
721 struct rb_node **link;
722 struct rb_node *parent;
723
724 if (from)
725 link = find_va_links(va, NULL, from, &parent);
726 else
727 link = find_va_links(va, root, NULL, &parent);
728
729 link_va(va, root, parent, link, head);
730 augment_tree_propagate_from(va);
731}
732
733/*
734 * Merge de-allocated chunk of VA memory with previous
735 * and next free blocks. If coalesce is not done a new
736 * free area is inserted. If VA has been merged, it is
737 * freed.
738 */
3c5c3cfb 739static __always_inline struct vmap_area *
68ad4a33
URS
740merge_or_add_vmap_area(struct vmap_area *va,
741 struct rb_root *root, struct list_head *head)
742{
743 struct vmap_area *sibling;
744 struct list_head *next;
745 struct rb_node **link;
746 struct rb_node *parent;
747 bool merged = false;
748
749 /*
750 * Find a place in the tree where VA potentially will be
751 * inserted, unless it is merged with its sibling/siblings.
752 */
753 link = find_va_links(va, root, NULL, &parent);
754
755 /*
756 * Get next node of VA to check if merging can be done.
757 */
758 next = get_va_next_sibling(parent, link);
759 if (unlikely(next == NULL))
760 goto insert;
761
762 /*
763 * start end
764 * | |
765 * |<------VA------>|<-----Next----->|
766 * | |
767 * start end
768 */
769 if (next != head) {
770 sibling = list_entry(next, struct vmap_area, list);
771 if (sibling->va_start == va->va_end) {
772 sibling->va_start = va->va_start;
773
68ad4a33
URS
774 /* Free vmap_area object. */
775 kmem_cache_free(vmap_area_cachep, va);
776
777 /* Point to the new merged area. */
778 va = sibling;
779 merged = true;
780 }
781 }
782
783 /*
784 * start end
785 * | |
786 * |<-----Prev----->|<------VA------>|
787 * | |
788 * start end
789 */
790 if (next->prev != head) {
791 sibling = list_entry(next->prev, struct vmap_area, list);
792 if (sibling->va_end == va->va_start) {
5dd78640
URS
793 /*
794 * If both neighbors are coalesced, it is important
795 * to unlink the "next" node first, followed by merging
796 * with "previous" one. Otherwise the tree might not be
797 * fully populated if a sibling's augmented value is
798 * "normalized" because of rotation operations.
799 */
54f63d9d
URS
800 if (merged)
801 unlink_va(va, root);
68ad4a33 802
5dd78640
URS
803 sibling->va_end = va->va_end;
804
68ad4a33
URS
805 /* Free vmap_area object. */
806 kmem_cache_free(vmap_area_cachep, va);
3c5c3cfb
DA
807
808 /* Point to the new merged area. */
809 va = sibling;
810 merged = true;
68ad4a33
URS
811 }
812 }
813
814insert:
5dd78640 815 if (!merged)
68ad4a33 816 link_va(va, root, parent, link, head);
3c5c3cfb 817
5dd78640
URS
818 /*
819 * Last step is to check and update the tree.
820 */
821 augment_tree_propagate_from(va);
3c5c3cfb 822 return va;
68ad4a33
URS
823}
824
825static __always_inline bool
826is_within_this_va(struct vmap_area *va, unsigned long size,
827 unsigned long align, unsigned long vstart)
828{
829 unsigned long nva_start_addr;
830
831 if (va->va_start > vstart)
832 nva_start_addr = ALIGN(va->va_start, align);
833 else
834 nva_start_addr = ALIGN(vstart, align);
835
836 /* Can be overflowed due to big size or alignment. */
837 if (nva_start_addr + size < nva_start_addr ||
838 nva_start_addr < vstart)
839 return false;
840
841 return (nva_start_addr + size <= va->va_end);
842}
843
844/*
845 * Find the first free block(lowest start address) in the tree,
846 * that will accomplish the request corresponding to passing
847 * parameters.
848 */
849static __always_inline struct vmap_area *
850find_vmap_lowest_match(unsigned long size,
851 unsigned long align, unsigned long vstart)
852{
853 struct vmap_area *va;
854 struct rb_node *node;
855 unsigned long length;
856
857 /* Start from the root. */
858 node = free_vmap_area_root.rb_node;
859
860 /* Adjust the search size for alignment overhead. */
861 length = size + align - 1;
862
863 while (node) {
864 va = rb_entry(node, struct vmap_area, rb_node);
865
866 if (get_subtree_max_size(node->rb_left) >= length &&
867 vstart < va->va_start) {
868 node = node->rb_left;
869 } else {
870 if (is_within_this_va(va, size, align, vstart))
871 return va;
872
873 /*
874 * Does not make sense to go deeper towards the right
875 * sub-tree if it does not have a free block that is
876 * equal or bigger to the requested search length.
877 */
878 if (get_subtree_max_size(node->rb_right) >= length) {
879 node = node->rb_right;
880 continue;
881 }
882
883 /*
3806b041 884 * OK. We roll back and find the first right sub-tree,
68ad4a33
URS
885 * that will satisfy the search criteria. It can happen
886 * only once due to "vstart" restriction.
887 */
888 while ((node = rb_parent(node))) {
889 va = rb_entry(node, struct vmap_area, rb_node);
890 if (is_within_this_va(va, size, align, vstart))
891 return va;
892
893 if (get_subtree_max_size(node->rb_right) >= length &&
894 vstart <= va->va_start) {
895 node = node->rb_right;
896 break;
897 }
898 }
899 }
900 }
901
902 return NULL;
903}
904
a6cf4e0f
URS
905#if DEBUG_AUGMENT_LOWEST_MATCH_CHECK
906#include <linux/random.h>
907
908static struct vmap_area *
909find_vmap_lowest_linear_match(unsigned long size,
910 unsigned long align, unsigned long vstart)
911{
912 struct vmap_area *va;
913
914 list_for_each_entry(va, &free_vmap_area_list, list) {
915 if (!is_within_this_va(va, size, align, vstart))
916 continue;
917
918 return va;
919 }
920
921 return NULL;
922}
923
924static void
925find_vmap_lowest_match_check(unsigned long size)
926{
927 struct vmap_area *va_1, *va_2;
928 unsigned long vstart;
929 unsigned int rnd;
930
931 get_random_bytes(&rnd, sizeof(rnd));
932 vstart = VMALLOC_START + rnd;
933
934 va_1 = find_vmap_lowest_match(size, 1, vstart);
935 va_2 = find_vmap_lowest_linear_match(size, 1, vstart);
936
937 if (va_1 != va_2)
938 pr_emerg("not lowest: t: 0x%p, l: 0x%p, v: 0x%lx\n",
939 va_1, va_2, vstart);
940}
941#endif
942
68ad4a33
URS
943enum fit_type {
944 NOTHING_FIT = 0,
945 FL_FIT_TYPE = 1, /* full fit */
946 LE_FIT_TYPE = 2, /* left edge fit */
947 RE_FIT_TYPE = 3, /* right edge fit */
948 NE_FIT_TYPE = 4 /* no edge fit */
949};
950
951static __always_inline enum fit_type
952classify_va_fit_type(struct vmap_area *va,
953 unsigned long nva_start_addr, unsigned long size)
954{
955 enum fit_type type;
956
957 /* Check if it is within VA. */
958 if (nva_start_addr < va->va_start ||
959 nva_start_addr + size > va->va_end)
960 return NOTHING_FIT;
961
962 /* Now classify. */
963 if (va->va_start == nva_start_addr) {
964 if (va->va_end == nva_start_addr + size)
965 type = FL_FIT_TYPE;
966 else
967 type = LE_FIT_TYPE;
968 } else if (va->va_end == nva_start_addr + size) {
969 type = RE_FIT_TYPE;
970 } else {
971 type = NE_FIT_TYPE;
972 }
973
974 return type;
975}
976
977static __always_inline int
978adjust_va_to_fit_type(struct vmap_area *va,
979 unsigned long nva_start_addr, unsigned long size,
980 enum fit_type type)
981{
2c929233 982 struct vmap_area *lva = NULL;
68ad4a33
URS
983
984 if (type == FL_FIT_TYPE) {
985 /*
986 * No need to split VA, it fully fits.
987 *
988 * | |
989 * V NVA V
990 * |---------------|
991 */
992 unlink_va(va, &free_vmap_area_root);
993 kmem_cache_free(vmap_area_cachep, va);
994 } else if (type == LE_FIT_TYPE) {
995 /*
996 * Split left edge of fit VA.
997 *
998 * | |
999 * V NVA V R
1000 * |-------|-------|
1001 */
1002 va->va_start += size;
1003 } else if (type == RE_FIT_TYPE) {
1004 /*
1005 * Split right edge of fit VA.
1006 *
1007 * | |
1008 * L V NVA V
1009 * |-------|-------|
1010 */
1011 va->va_end = nva_start_addr;
1012 } else if (type == NE_FIT_TYPE) {
1013 /*
1014 * Split no edge of fit VA.
1015 *
1016 * | |
1017 * L V NVA V R
1018 * |---|-------|---|
1019 */
82dd23e8
URS
1020 lva = __this_cpu_xchg(ne_fit_preload_node, NULL);
1021 if (unlikely(!lva)) {
1022 /*
1023 * For percpu allocator we do not do any pre-allocation
1024 * and leave it as it is. The reason is it most likely
1025 * never ends up with NE_FIT_TYPE splitting. In case of
1026 * percpu allocations offsets and sizes are aligned to
1027 * fixed align request, i.e. RE_FIT_TYPE and FL_FIT_TYPE
1028 * are its main fitting cases.
1029 *
1030 * There are a few exceptions though, as an example it is
1031 * a first allocation (early boot up) when we have "one"
1032 * big free space that has to be split.
060650a2
URS
1033 *
1034 * Also we can hit this path in case of regular "vmap"
1035 * allocations, if "this" current CPU was not preloaded.
1036 * See the comment in alloc_vmap_area() why. If so, then
1037 * GFP_NOWAIT is used instead to get an extra object for
1038 * split purpose. That is rare and most time does not
1039 * occur.
1040 *
1041 * What happens if an allocation gets failed. Basically,
1042 * an "overflow" path is triggered to purge lazily freed
1043 * areas to free some memory, then, the "retry" path is
1044 * triggered to repeat one more time. See more details
1045 * in alloc_vmap_area() function.
82dd23e8
URS
1046 */
1047 lva = kmem_cache_alloc(vmap_area_cachep, GFP_NOWAIT);
1048 if (!lva)
1049 return -1;
1050 }
68ad4a33
URS
1051
1052 /*
1053 * Build the remainder.
1054 */
1055 lva->va_start = va->va_start;
1056 lva->va_end = nva_start_addr;
1057
1058 /*
1059 * Shrink this VA to remaining size.
1060 */
1061 va->va_start = nva_start_addr + size;
1062 } else {
1063 return -1;
1064 }
1065
1066 if (type != FL_FIT_TYPE) {
1067 augment_tree_propagate_from(va);
1068
2c929233 1069 if (lva) /* type == NE_FIT_TYPE */
68ad4a33
URS
1070 insert_vmap_area_augment(lva, &va->rb_node,
1071 &free_vmap_area_root, &free_vmap_area_list);
1072 }
1073
1074 return 0;
1075}
1076
1077/*
1078 * Returns a start address of the newly allocated area, if success.
1079 * Otherwise a vend is returned that indicates failure.
1080 */
1081static __always_inline unsigned long
1082__alloc_vmap_area(unsigned long size, unsigned long align,
cacca6ba 1083 unsigned long vstart, unsigned long vend)
68ad4a33
URS
1084{
1085 unsigned long nva_start_addr;
1086 struct vmap_area *va;
1087 enum fit_type type;
1088 int ret;
1089
1090 va = find_vmap_lowest_match(size, align, vstart);
1091 if (unlikely(!va))
1092 return vend;
1093
1094 if (va->va_start > vstart)
1095 nva_start_addr = ALIGN(va->va_start, align);
1096 else
1097 nva_start_addr = ALIGN(vstart, align);
1098
1099 /* Check the "vend" restriction. */
1100 if (nva_start_addr + size > vend)
1101 return vend;
1102
1103 /* Classify what we have found. */
1104 type = classify_va_fit_type(va, nva_start_addr, size);
1105 if (WARN_ON_ONCE(type == NOTHING_FIT))
1106 return vend;
1107
1108 /* Update the free vmap_area. */
1109 ret = adjust_va_to_fit_type(va, nva_start_addr, size, type);
1110 if (ret)
1111 return vend;
1112
a6cf4e0f
URS
1113#if DEBUG_AUGMENT_LOWEST_MATCH_CHECK
1114 find_vmap_lowest_match_check(size);
1115#endif
1116
68ad4a33
URS
1117 return nva_start_addr;
1118}
4da56b99 1119
d98c9e83
AR
1120/*
1121 * Free a region of KVA allocated by alloc_vmap_area
1122 */
1123static void free_vmap_area(struct vmap_area *va)
1124{
1125 /*
1126 * Remove from the busy tree/list.
1127 */
1128 spin_lock(&vmap_area_lock);
1129 unlink_va(va, &vmap_area_root);
1130 spin_unlock(&vmap_area_lock);
1131
1132 /*
1133 * Insert/Merge it back to the free tree/list.
1134 */
1135 spin_lock(&free_vmap_area_lock);
1136 merge_or_add_vmap_area(va, &free_vmap_area_root, &free_vmap_area_list);
1137 spin_unlock(&free_vmap_area_lock);
1138}
1139
db64fe02
NP
1140/*
1141 * Allocate a region of KVA of the specified size and alignment, within the
1142 * vstart and vend.
1143 */
1144static struct vmap_area *alloc_vmap_area(unsigned long size,
1145 unsigned long align,
1146 unsigned long vstart, unsigned long vend,
1147 int node, gfp_t gfp_mask)
1148{
82dd23e8 1149 struct vmap_area *va, *pva;
1da177e4 1150 unsigned long addr;
db64fe02 1151 int purged = 0;
d98c9e83 1152 int ret;
db64fe02 1153
7766970c 1154 BUG_ON(!size);
891c49ab 1155 BUG_ON(offset_in_page(size));
89699605 1156 BUG_ON(!is_power_of_2(align));
db64fe02 1157
68ad4a33
URS
1158 if (unlikely(!vmap_initialized))
1159 return ERR_PTR(-EBUSY);
1160
5803ed29 1161 might_sleep();
f07116d7 1162 gfp_mask = gfp_mask & GFP_RECLAIM_MASK;
4da56b99 1163
f07116d7 1164 va = kmem_cache_alloc_node(vmap_area_cachep, gfp_mask, node);
db64fe02
NP
1165 if (unlikely(!va))
1166 return ERR_PTR(-ENOMEM);
1167
7f88f88f
CM
1168 /*
1169 * Only scan the relevant parts containing pointers to other objects
1170 * to avoid false negatives.
1171 */
f07116d7 1172 kmemleak_scan_area(&va->rb_node, SIZE_MAX, gfp_mask);
7f88f88f 1173
db64fe02 1174retry:
82dd23e8 1175 /*
81f1ba58
URS
1176 * Preload this CPU with one extra vmap_area object. It is used
1177 * when fit type of free area is NE_FIT_TYPE. Please note, it
1178 * does not guarantee that an allocation occurs on a CPU that
1179 * is preloaded, instead we minimize the case when it is not.
1180 * It can happen because of cpu migration, because there is a
1181 * race until the below spinlock is taken.
82dd23e8
URS
1182 *
1183 * The preload is done in non-atomic context, thus it allows us
1184 * to use more permissive allocation masks to be more stable under
81f1ba58
URS
1185 * low memory condition and high memory pressure. In rare case,
1186 * if not preloaded, GFP_NOWAIT is used.
82dd23e8 1187 *
81f1ba58 1188 * Set "pva" to NULL here, because of "retry" path.
82dd23e8 1189 */
81f1ba58 1190 pva = NULL;
82dd23e8 1191
81f1ba58
URS
1192 if (!this_cpu_read(ne_fit_preload_node))
1193 /*
1194 * Even if it fails we do not really care about that.
1195 * Just proceed as it is. If needed "overflow" path
1196 * will refill the cache we allocate from.
1197 */
f07116d7 1198 pva = kmem_cache_alloc_node(vmap_area_cachep, gfp_mask, node);
82dd23e8 1199
e36176be 1200 spin_lock(&free_vmap_area_lock);
81f1ba58
URS
1201
1202 if (pva && __this_cpu_cmpxchg(ne_fit_preload_node, NULL, pva))
1203 kmem_cache_free(vmap_area_cachep, pva);
89699605 1204
afd07389 1205 /*
68ad4a33
URS
1206 * If an allocation fails, the "vend" address is
1207 * returned. Therefore trigger the overflow path.
afd07389 1208 */
cacca6ba 1209 addr = __alloc_vmap_area(size, align, vstart, vend);
e36176be
URS
1210 spin_unlock(&free_vmap_area_lock);
1211
68ad4a33 1212 if (unlikely(addr == vend))
89699605 1213 goto overflow;
db64fe02
NP
1214
1215 va->va_start = addr;
1216 va->va_end = addr + size;
688fcbfc 1217 va->vm = NULL;
68ad4a33 1218
d98c9e83 1219
e36176be
URS
1220 spin_lock(&vmap_area_lock);
1221 insert_vmap_area(va, &vmap_area_root, &vmap_area_list);
db64fe02
NP
1222 spin_unlock(&vmap_area_lock);
1223
61e16557 1224 BUG_ON(!IS_ALIGNED(va->va_start, align));
89699605
NP
1225 BUG_ON(va->va_start < vstart);
1226 BUG_ON(va->va_end > vend);
1227
d98c9e83
AR
1228 ret = kasan_populate_vmalloc(addr, size);
1229 if (ret) {
1230 free_vmap_area(va);
1231 return ERR_PTR(ret);
1232 }
1233
db64fe02 1234 return va;
89699605
NP
1235
1236overflow:
89699605
NP
1237 if (!purged) {
1238 purge_vmap_area_lazy();
1239 purged = 1;
1240 goto retry;
1241 }
4da56b99
CW
1242
1243 if (gfpflags_allow_blocking(gfp_mask)) {
1244 unsigned long freed = 0;
1245 blocking_notifier_call_chain(&vmap_notify_list, 0, &freed);
1246 if (freed > 0) {
1247 purged = 0;
1248 goto retry;
1249 }
1250 }
1251
03497d76 1252 if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit())
756a025f
JP
1253 pr_warn("vmap allocation for size %lu failed: use vmalloc=<size> to increase size\n",
1254 size);
68ad4a33
URS
1255
1256 kmem_cache_free(vmap_area_cachep, va);
89699605 1257 return ERR_PTR(-EBUSY);
db64fe02
NP
1258}
1259
4da56b99
CW
1260int register_vmap_purge_notifier(struct notifier_block *nb)
1261{
1262 return blocking_notifier_chain_register(&vmap_notify_list, nb);
1263}
1264EXPORT_SYMBOL_GPL(register_vmap_purge_notifier);
1265
1266int unregister_vmap_purge_notifier(struct notifier_block *nb)
1267{
1268 return blocking_notifier_chain_unregister(&vmap_notify_list, nb);
1269}
1270EXPORT_SYMBOL_GPL(unregister_vmap_purge_notifier);
1271
db64fe02
NP
1272/*
1273 * lazy_max_pages is the maximum amount of virtual address space we gather up
1274 * before attempting to purge with a TLB flush.
1275 *
1276 * There is a tradeoff here: a larger number will cover more kernel page tables
1277 * and take slightly longer to purge, but it will linearly reduce the number of
1278 * global TLB flushes that must be performed. It would seem natural to scale
1279 * this number up linearly with the number of CPUs (because vmapping activity
1280 * could also scale linearly with the number of CPUs), however it is likely
1281 * that in practice, workloads might be constrained in other ways that mean
1282 * vmap activity will not scale linearly with CPUs. Also, I want to be
1283 * conservative and not introduce a big latency on huge systems, so go with
1284 * a less aggressive log scale. It will still be an improvement over the old
1285 * code, and it will be simple to change the scale factor if we find that it
1286 * becomes a problem on bigger systems.
1287 */
1288static unsigned long lazy_max_pages(void)
1289{
1290 unsigned int log;
1291
1292 log = fls(num_online_cpus());
1293
1294 return log * (32UL * 1024 * 1024 / PAGE_SIZE);
1295}
1296
4d36e6f8 1297static atomic_long_t vmap_lazy_nr = ATOMIC_LONG_INIT(0);
db64fe02 1298
0574ecd1
CH
1299/*
1300 * Serialize vmap purging. There is no actual criticial section protected
1301 * by this look, but we want to avoid concurrent calls for performance
1302 * reasons and to make the pcpu_get_vm_areas more deterministic.
1303 */
f9e09977 1304static DEFINE_MUTEX(vmap_purge_lock);
0574ecd1 1305
02b709df
NP
1306/* for per-CPU blocks */
1307static void purge_fragmented_blocks_allcpus(void);
1308
3ee48b6a
CW
1309/*
1310 * called before a call to iounmap() if the caller wants vm_area_struct's
1311 * immediately freed.
1312 */
1313void set_iounmap_nonlazy(void)
1314{
4d36e6f8 1315 atomic_long_set(&vmap_lazy_nr, lazy_max_pages()+1);
3ee48b6a
CW
1316}
1317
db64fe02
NP
1318/*
1319 * Purges all lazily-freed vmap areas.
db64fe02 1320 */
0574ecd1 1321static bool __purge_vmap_area_lazy(unsigned long start, unsigned long end)
db64fe02 1322{
4d36e6f8 1323 unsigned long resched_threshold;
80c4bd7a 1324 struct llist_node *valist;
db64fe02 1325 struct vmap_area *va;
cbb76676 1326 struct vmap_area *n_va;
db64fe02 1327
0574ecd1 1328 lockdep_assert_held(&vmap_purge_lock);
02b709df 1329
80c4bd7a 1330 valist = llist_del_all(&vmap_purge_list);
68571be9
URS
1331 if (unlikely(valist == NULL))
1332 return false;
1333
1334 /*
1335 * TODO: to calculate a flush range without looping.
1336 * The list can be up to lazy_max_pages() elements.
1337 */
80c4bd7a 1338 llist_for_each_entry(va, valist, purge_list) {
0574ecd1
CH
1339 if (va->va_start < start)
1340 start = va->va_start;
1341 if (va->va_end > end)
1342 end = va->va_end;
db64fe02 1343 }
db64fe02 1344
0574ecd1 1345 flush_tlb_kernel_range(start, end);
4d36e6f8 1346 resched_threshold = lazy_max_pages() << 1;
db64fe02 1347
e36176be 1348 spin_lock(&free_vmap_area_lock);
763b218d 1349 llist_for_each_entry_safe(va, n_va, valist, purge_list) {
4d36e6f8 1350 unsigned long nr = (va->va_end - va->va_start) >> PAGE_SHIFT;
3c5c3cfb
DA
1351 unsigned long orig_start = va->va_start;
1352 unsigned long orig_end = va->va_end;
763b218d 1353
dd3b8353
URS
1354 /*
1355 * Finally insert or merge lazily-freed area. It is
1356 * detached and there is no need to "unlink" it from
1357 * anything.
1358 */
3c5c3cfb
DA
1359 va = merge_or_add_vmap_area(va, &free_vmap_area_root,
1360 &free_vmap_area_list);
1361
1362 if (is_vmalloc_or_module_addr((void *)orig_start))
1363 kasan_release_vmalloc(orig_start, orig_end,
1364 va->va_start, va->va_end);
dd3b8353 1365
4d36e6f8 1366 atomic_long_sub(nr, &vmap_lazy_nr);
68571be9 1367
4d36e6f8 1368 if (atomic_long_read(&vmap_lazy_nr) < resched_threshold)
e36176be 1369 cond_resched_lock(&free_vmap_area_lock);
763b218d 1370 }
e36176be 1371 spin_unlock(&free_vmap_area_lock);
0574ecd1 1372 return true;
db64fe02
NP
1373}
1374
496850e5
NP
1375/*
1376 * Kick off a purge of the outstanding lazy areas. Don't bother if somebody
1377 * is already purging.
1378 */
1379static void try_purge_vmap_area_lazy(void)
1380{
f9e09977 1381 if (mutex_trylock(&vmap_purge_lock)) {
0574ecd1 1382 __purge_vmap_area_lazy(ULONG_MAX, 0);
f9e09977 1383 mutex_unlock(&vmap_purge_lock);
0574ecd1 1384 }
496850e5
NP
1385}
1386
db64fe02
NP
1387/*
1388 * Kick off a purge of the outstanding lazy areas.
1389 */
1390static void purge_vmap_area_lazy(void)
1391{
f9e09977 1392 mutex_lock(&vmap_purge_lock);
0574ecd1
CH
1393 purge_fragmented_blocks_allcpus();
1394 __purge_vmap_area_lazy(ULONG_MAX, 0);
f9e09977 1395 mutex_unlock(&vmap_purge_lock);
db64fe02
NP
1396}
1397
1398/*
64141da5
JF
1399 * Free a vmap area, caller ensuring that the area has been unmapped
1400 * and flush_cache_vunmap had been called for the correct range
1401 * previously.
db64fe02 1402 */
64141da5 1403static void free_vmap_area_noflush(struct vmap_area *va)
db64fe02 1404{
4d36e6f8 1405 unsigned long nr_lazy;
80c4bd7a 1406
dd3b8353
URS
1407 spin_lock(&vmap_area_lock);
1408 unlink_va(va, &vmap_area_root);
1409 spin_unlock(&vmap_area_lock);
1410
4d36e6f8
URS
1411 nr_lazy = atomic_long_add_return((va->va_end - va->va_start) >>
1412 PAGE_SHIFT, &vmap_lazy_nr);
80c4bd7a
CW
1413
1414 /* After this point, we may free va at any time */
1415 llist_add(&va->purge_list, &vmap_purge_list);
1416
1417 if (unlikely(nr_lazy > lazy_max_pages()))
496850e5 1418 try_purge_vmap_area_lazy();
db64fe02
NP
1419}
1420
b29acbdc
NP
1421/*
1422 * Free and unmap a vmap area
1423 */
1424static void free_unmap_vmap_area(struct vmap_area *va)
1425{
1426 flush_cache_vunmap(va->va_start, va->va_end);
855e57a1 1427 unmap_kernel_range_noflush(va->va_start, va->va_end - va->va_start);
8e57f8ac 1428 if (debug_pagealloc_enabled_static())
82a2e924
CP
1429 flush_tlb_kernel_range(va->va_start, va->va_end);
1430
c8eef01e 1431 free_vmap_area_noflush(va);
b29acbdc
NP
1432}
1433
db64fe02
NP
1434static struct vmap_area *find_vmap_area(unsigned long addr)
1435{
1436 struct vmap_area *va;
1437
1438 spin_lock(&vmap_area_lock);
1439 va = __find_vmap_area(addr);
1440 spin_unlock(&vmap_area_lock);
1441
1442 return va;
1443}
1444
db64fe02
NP
1445/*** Per cpu kva allocator ***/
1446
1447/*
1448 * vmap space is limited especially on 32 bit architectures. Ensure there is
1449 * room for at least 16 percpu vmap blocks per CPU.
1450 */
1451/*
1452 * If we had a constant VMALLOC_START and VMALLOC_END, we'd like to be able
1453 * to #define VMALLOC_SPACE (VMALLOC_END-VMALLOC_START). Guess
1454 * instead (we just need a rough idea)
1455 */
1456#if BITS_PER_LONG == 32
1457#define VMALLOC_SPACE (128UL*1024*1024)
1458#else
1459#define VMALLOC_SPACE (128UL*1024*1024*1024)
1460#endif
1461
1462#define VMALLOC_PAGES (VMALLOC_SPACE / PAGE_SIZE)
1463#define VMAP_MAX_ALLOC BITS_PER_LONG /* 256K with 4K pages */
1464#define VMAP_BBMAP_BITS_MAX 1024 /* 4MB with 4K pages */
1465#define VMAP_BBMAP_BITS_MIN (VMAP_MAX_ALLOC*2)
1466#define VMAP_MIN(x, y) ((x) < (y) ? (x) : (y)) /* can't use min() */
1467#define VMAP_MAX(x, y) ((x) > (y) ? (x) : (y)) /* can't use max() */
f982f915
CL
1468#define VMAP_BBMAP_BITS \
1469 VMAP_MIN(VMAP_BBMAP_BITS_MAX, \
1470 VMAP_MAX(VMAP_BBMAP_BITS_MIN, \
1471 VMALLOC_PAGES / roundup_pow_of_two(NR_CPUS) / 16))
db64fe02
NP
1472
1473#define VMAP_BLOCK_SIZE (VMAP_BBMAP_BITS * PAGE_SIZE)
1474
1475struct vmap_block_queue {
1476 spinlock_t lock;
1477 struct list_head free;
db64fe02
NP
1478};
1479
1480struct vmap_block {
1481 spinlock_t lock;
1482 struct vmap_area *va;
db64fe02 1483 unsigned long free, dirty;
7d61bfe8 1484 unsigned long dirty_min, dirty_max; /*< dirty range */
de560423
NP
1485 struct list_head free_list;
1486 struct rcu_head rcu_head;
02b709df 1487 struct list_head purge;
db64fe02
NP
1488};
1489
1490/* Queue of free and dirty vmap blocks, for allocation and flushing purposes */
1491static DEFINE_PER_CPU(struct vmap_block_queue, vmap_block_queue);
1492
1493/*
0f14599c 1494 * XArray of vmap blocks, indexed by address, to quickly find a vmap block
db64fe02
NP
1495 * in the free path. Could get rid of this if we change the API to return a
1496 * "cookie" from alloc, to be passed to free. But no big deal yet.
1497 */
0f14599c 1498static DEFINE_XARRAY(vmap_blocks);
db64fe02
NP
1499
1500/*
1501 * We should probably have a fallback mechanism to allocate virtual memory
1502 * out of partially filled vmap blocks. However vmap block sizing should be
1503 * fairly reasonable according to the vmalloc size, so it shouldn't be a
1504 * big problem.
1505 */
1506
1507static unsigned long addr_to_vb_idx(unsigned long addr)
1508{
1509 addr -= VMALLOC_START & ~(VMAP_BLOCK_SIZE-1);
1510 addr /= VMAP_BLOCK_SIZE;
1511 return addr;
1512}
1513
cf725ce2
RP
1514static void *vmap_block_vaddr(unsigned long va_start, unsigned long pages_off)
1515{
1516 unsigned long addr;
1517
1518 addr = va_start + (pages_off << PAGE_SHIFT);
1519 BUG_ON(addr_to_vb_idx(addr) != addr_to_vb_idx(va_start));
1520 return (void *)addr;
1521}
1522
1523/**
1524 * new_vmap_block - allocates new vmap_block and occupies 2^order pages in this
1525 * block. Of course pages number can't exceed VMAP_BBMAP_BITS
1526 * @order: how many 2^order pages should be occupied in newly allocated block
1527 * @gfp_mask: flags for the page level allocator
1528 *
a862f68a 1529 * Return: virtual address in a newly allocated block or ERR_PTR(-errno)
cf725ce2
RP
1530 */
1531static void *new_vmap_block(unsigned int order, gfp_t gfp_mask)
db64fe02
NP
1532{
1533 struct vmap_block_queue *vbq;
1534 struct vmap_block *vb;
1535 struct vmap_area *va;
1536 unsigned long vb_idx;
1537 int node, err;
cf725ce2 1538 void *vaddr;
db64fe02
NP
1539
1540 node = numa_node_id();
1541
1542 vb = kmalloc_node(sizeof(struct vmap_block),
1543 gfp_mask & GFP_RECLAIM_MASK, node);
1544 if (unlikely(!vb))
1545 return ERR_PTR(-ENOMEM);
1546
1547 va = alloc_vmap_area(VMAP_BLOCK_SIZE, VMAP_BLOCK_SIZE,
1548 VMALLOC_START, VMALLOC_END,
1549 node, gfp_mask);
ddf9c6d4 1550 if (IS_ERR(va)) {
db64fe02 1551 kfree(vb);
e7d86340 1552 return ERR_CAST(va);
db64fe02
NP
1553 }
1554
cf725ce2 1555 vaddr = vmap_block_vaddr(va->va_start, 0);
db64fe02
NP
1556 spin_lock_init(&vb->lock);
1557 vb->va = va;
cf725ce2
RP
1558 /* At least something should be left free */
1559 BUG_ON(VMAP_BBMAP_BITS <= (1UL << order));
1560 vb->free = VMAP_BBMAP_BITS - (1UL << order);
db64fe02 1561 vb->dirty = 0;
7d61bfe8
RP
1562 vb->dirty_min = VMAP_BBMAP_BITS;
1563 vb->dirty_max = 0;
db64fe02 1564 INIT_LIST_HEAD(&vb->free_list);
db64fe02
NP
1565
1566 vb_idx = addr_to_vb_idx(va->va_start);
0f14599c
MWO
1567 err = xa_insert(&vmap_blocks, vb_idx, vb, gfp_mask);
1568 if (err) {
1569 kfree(vb);
1570 free_vmap_area(va);
1571 return ERR_PTR(err);
1572 }
db64fe02
NP
1573
1574 vbq = &get_cpu_var(vmap_block_queue);
db64fe02 1575 spin_lock(&vbq->lock);
68ac546f 1576 list_add_tail_rcu(&vb->free_list, &vbq->free);
db64fe02 1577 spin_unlock(&vbq->lock);
3f04ba85 1578 put_cpu_var(vmap_block_queue);
db64fe02 1579
cf725ce2 1580 return vaddr;
db64fe02
NP
1581}
1582
db64fe02
NP
1583static void free_vmap_block(struct vmap_block *vb)
1584{
1585 struct vmap_block *tmp;
db64fe02 1586
0f14599c 1587 tmp = xa_erase(&vmap_blocks, addr_to_vb_idx(vb->va->va_start));
db64fe02
NP
1588 BUG_ON(tmp != vb);
1589
64141da5 1590 free_vmap_area_noflush(vb->va);
22a3c7d1 1591 kfree_rcu(vb, rcu_head);
db64fe02
NP
1592}
1593
02b709df
NP
1594static void purge_fragmented_blocks(int cpu)
1595{
1596 LIST_HEAD(purge);
1597 struct vmap_block *vb;
1598 struct vmap_block *n_vb;
1599 struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu);
1600
1601 rcu_read_lock();
1602 list_for_each_entry_rcu(vb, &vbq->free, free_list) {
1603
1604 if (!(vb->free + vb->dirty == VMAP_BBMAP_BITS && vb->dirty != VMAP_BBMAP_BITS))
1605 continue;
1606
1607 spin_lock(&vb->lock);
1608 if (vb->free + vb->dirty == VMAP_BBMAP_BITS && vb->dirty != VMAP_BBMAP_BITS) {
1609 vb->free = 0; /* prevent further allocs after releasing lock */
1610 vb->dirty = VMAP_BBMAP_BITS; /* prevent purging it again */
7d61bfe8
RP
1611 vb->dirty_min = 0;
1612 vb->dirty_max = VMAP_BBMAP_BITS;
02b709df
NP
1613 spin_lock(&vbq->lock);
1614 list_del_rcu(&vb->free_list);
1615 spin_unlock(&vbq->lock);
1616 spin_unlock(&vb->lock);
1617 list_add_tail(&vb->purge, &purge);
1618 } else
1619 spin_unlock(&vb->lock);
1620 }
1621 rcu_read_unlock();
1622
1623 list_for_each_entry_safe(vb, n_vb, &purge, purge) {
1624 list_del(&vb->purge);
1625 free_vmap_block(vb);
1626 }
1627}
1628
02b709df
NP
1629static void purge_fragmented_blocks_allcpus(void)
1630{
1631 int cpu;
1632
1633 for_each_possible_cpu(cpu)
1634 purge_fragmented_blocks(cpu);
1635}
1636
db64fe02
NP
1637static void *vb_alloc(unsigned long size, gfp_t gfp_mask)
1638{
1639 struct vmap_block_queue *vbq;
1640 struct vmap_block *vb;
cf725ce2 1641 void *vaddr = NULL;
db64fe02
NP
1642 unsigned int order;
1643
891c49ab 1644 BUG_ON(offset_in_page(size));
db64fe02 1645 BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
aa91c4d8
JK
1646 if (WARN_ON(size == 0)) {
1647 /*
1648 * Allocating 0 bytes isn't what caller wants since
1649 * get_order(0) returns funny result. Just warn and terminate
1650 * early.
1651 */
1652 return NULL;
1653 }
db64fe02
NP
1654 order = get_order(size);
1655
db64fe02
NP
1656 rcu_read_lock();
1657 vbq = &get_cpu_var(vmap_block_queue);
1658 list_for_each_entry_rcu(vb, &vbq->free, free_list) {
cf725ce2 1659 unsigned long pages_off;
db64fe02
NP
1660
1661 spin_lock(&vb->lock);
cf725ce2
RP
1662 if (vb->free < (1UL << order)) {
1663 spin_unlock(&vb->lock);
1664 continue;
1665 }
02b709df 1666
cf725ce2
RP
1667 pages_off = VMAP_BBMAP_BITS - vb->free;
1668 vaddr = vmap_block_vaddr(vb->va->va_start, pages_off);
02b709df
NP
1669 vb->free -= 1UL << order;
1670 if (vb->free == 0) {
1671 spin_lock(&vbq->lock);
1672 list_del_rcu(&vb->free_list);
1673 spin_unlock(&vbq->lock);
1674 }
cf725ce2 1675
02b709df
NP
1676 spin_unlock(&vb->lock);
1677 break;
db64fe02 1678 }
02b709df 1679
3f04ba85 1680 put_cpu_var(vmap_block_queue);
db64fe02
NP
1681 rcu_read_unlock();
1682
cf725ce2
RP
1683 /* Allocate new block if nothing was found */
1684 if (!vaddr)
1685 vaddr = new_vmap_block(order, gfp_mask);
db64fe02 1686
cf725ce2 1687 return vaddr;
db64fe02
NP
1688}
1689
78a0e8c4 1690static void vb_free(unsigned long addr, unsigned long size)
db64fe02
NP
1691{
1692 unsigned long offset;
db64fe02
NP
1693 unsigned int order;
1694 struct vmap_block *vb;
1695
891c49ab 1696 BUG_ON(offset_in_page(size));
db64fe02 1697 BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
b29acbdc 1698
78a0e8c4 1699 flush_cache_vunmap(addr, addr + size);
b29acbdc 1700
db64fe02 1701 order = get_order(size);
78a0e8c4 1702 offset = (addr & (VMAP_BLOCK_SIZE - 1)) >> PAGE_SHIFT;
0f14599c 1703 vb = xa_load(&vmap_blocks, addr_to_vb_idx(addr));
db64fe02 1704
b521c43f 1705 unmap_kernel_range_noflush(addr, size);
64141da5 1706
8e57f8ac 1707 if (debug_pagealloc_enabled_static())
78a0e8c4 1708 flush_tlb_kernel_range(addr, addr + size);
82a2e924 1709
db64fe02 1710 spin_lock(&vb->lock);
7d61bfe8
RP
1711
1712 /* Expand dirty range */
1713 vb->dirty_min = min(vb->dirty_min, offset);
1714 vb->dirty_max = max(vb->dirty_max, offset + (1UL << order));
d086817d 1715
db64fe02
NP
1716 vb->dirty += 1UL << order;
1717 if (vb->dirty == VMAP_BBMAP_BITS) {
de560423 1718 BUG_ON(vb->free);
db64fe02
NP
1719 spin_unlock(&vb->lock);
1720 free_vmap_block(vb);
1721 } else
1722 spin_unlock(&vb->lock);
1723}
1724
868b104d 1725static void _vm_unmap_aliases(unsigned long start, unsigned long end, int flush)
db64fe02 1726{
db64fe02 1727 int cpu;
db64fe02 1728
9b463334
JF
1729 if (unlikely(!vmap_initialized))
1730 return;
1731
5803ed29
CH
1732 might_sleep();
1733
db64fe02
NP
1734 for_each_possible_cpu(cpu) {
1735 struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu);
1736 struct vmap_block *vb;
1737
1738 rcu_read_lock();
1739 list_for_each_entry_rcu(vb, &vbq->free, free_list) {
db64fe02 1740 spin_lock(&vb->lock);
7d61bfe8
RP
1741 if (vb->dirty) {
1742 unsigned long va_start = vb->va->va_start;
db64fe02 1743 unsigned long s, e;
b136be5e 1744
7d61bfe8
RP
1745 s = va_start + (vb->dirty_min << PAGE_SHIFT);
1746 e = va_start + (vb->dirty_max << PAGE_SHIFT);
db64fe02 1747
7d61bfe8
RP
1748 start = min(s, start);
1749 end = max(e, end);
db64fe02 1750
7d61bfe8 1751 flush = 1;
db64fe02
NP
1752 }
1753 spin_unlock(&vb->lock);
1754 }
1755 rcu_read_unlock();
1756 }
1757
f9e09977 1758 mutex_lock(&vmap_purge_lock);
0574ecd1
CH
1759 purge_fragmented_blocks_allcpus();
1760 if (!__purge_vmap_area_lazy(start, end) && flush)
1761 flush_tlb_kernel_range(start, end);
f9e09977 1762 mutex_unlock(&vmap_purge_lock);
db64fe02 1763}
868b104d
RE
1764
1765/**
1766 * vm_unmap_aliases - unmap outstanding lazy aliases in the vmap layer
1767 *
1768 * The vmap/vmalloc layer lazily flushes kernel virtual mappings primarily
1769 * to amortize TLB flushing overheads. What this means is that any page you
1770 * have now, may, in a former life, have been mapped into kernel virtual
1771 * address by the vmap layer and so there might be some CPUs with TLB entries
1772 * still referencing that page (additional to the regular 1:1 kernel mapping).
1773 *
1774 * vm_unmap_aliases flushes all such lazy mappings. After it returns, we can
1775 * be sure that none of the pages we have control over will have any aliases
1776 * from the vmap layer.
1777 */
1778void vm_unmap_aliases(void)
1779{
1780 unsigned long start = ULONG_MAX, end = 0;
1781 int flush = 0;
1782
1783 _vm_unmap_aliases(start, end, flush);
1784}
db64fe02
NP
1785EXPORT_SYMBOL_GPL(vm_unmap_aliases);
1786
1787/**
1788 * vm_unmap_ram - unmap linear kernel address space set up by vm_map_ram
1789 * @mem: the pointer returned by vm_map_ram
1790 * @count: the count passed to that vm_map_ram call (cannot unmap partial)
1791 */
1792void vm_unmap_ram(const void *mem, unsigned int count)
1793{
65ee03c4 1794 unsigned long size = (unsigned long)count << PAGE_SHIFT;
db64fe02 1795 unsigned long addr = (unsigned long)mem;
9c3acf60 1796 struct vmap_area *va;
db64fe02 1797
5803ed29 1798 might_sleep();
db64fe02
NP
1799 BUG_ON(!addr);
1800 BUG_ON(addr < VMALLOC_START);
1801 BUG_ON(addr > VMALLOC_END);
a1c0b1a0 1802 BUG_ON(!PAGE_ALIGNED(addr));
db64fe02 1803
d98c9e83
AR
1804 kasan_poison_vmalloc(mem, size);
1805
9c3acf60 1806 if (likely(count <= VMAP_MAX_ALLOC)) {
05e3ff95 1807 debug_check_no_locks_freed(mem, size);
78a0e8c4 1808 vb_free(addr, size);
9c3acf60
CH
1809 return;
1810 }
1811
1812 va = find_vmap_area(addr);
1813 BUG_ON(!va);
05e3ff95
CP
1814 debug_check_no_locks_freed((void *)va->va_start,
1815 (va->va_end - va->va_start));
9c3acf60 1816 free_unmap_vmap_area(va);
db64fe02
NP
1817}
1818EXPORT_SYMBOL(vm_unmap_ram);
1819
1820/**
1821 * vm_map_ram - map pages linearly into kernel virtual address (vmalloc space)
1822 * @pages: an array of pointers to the pages to be mapped
1823 * @count: number of pages
1824 * @node: prefer to allocate data structures on this node
e99c97ad 1825 *
36437638
GK
1826 * If you use this function for less than VMAP_MAX_ALLOC pages, it could be
1827 * faster than vmap so it's good. But if you mix long-life and short-life
1828 * objects with vm_map_ram(), it could consume lots of address space through
1829 * fragmentation (especially on a 32bit machine). You could see failures in
1830 * the end. Please use this function for short-lived objects.
1831 *
e99c97ad 1832 * Returns: a pointer to the address that has been mapped, or %NULL on failure
db64fe02 1833 */
d4efd79a 1834void *vm_map_ram(struct page **pages, unsigned int count, int node)
db64fe02 1835{
65ee03c4 1836 unsigned long size = (unsigned long)count << PAGE_SHIFT;
db64fe02
NP
1837 unsigned long addr;
1838 void *mem;
1839
1840 if (likely(count <= VMAP_MAX_ALLOC)) {
1841 mem = vb_alloc(size, GFP_KERNEL);
1842 if (IS_ERR(mem))
1843 return NULL;
1844 addr = (unsigned long)mem;
1845 } else {
1846 struct vmap_area *va;
1847 va = alloc_vmap_area(size, PAGE_SIZE,
1848 VMALLOC_START, VMALLOC_END, node, GFP_KERNEL);
1849 if (IS_ERR(va))
1850 return NULL;
1851
1852 addr = va->va_start;
1853 mem = (void *)addr;
1854 }
d98c9e83
AR
1855
1856 kasan_unpoison_vmalloc(mem, size);
1857
d4efd79a 1858 if (map_kernel_range(addr, size, PAGE_KERNEL, pages) < 0) {
db64fe02
NP
1859 vm_unmap_ram(mem, count);
1860 return NULL;
1861 }
1862 return mem;
1863}
1864EXPORT_SYMBOL(vm_map_ram);
1865
4341fa45 1866static struct vm_struct *vmlist __initdata;
92eac168 1867
be9b7335
NP
1868/**
1869 * vm_area_add_early - add vmap area early during boot
1870 * @vm: vm_struct to add
1871 *
1872 * This function is used to add fixed kernel vm area to vmlist before
1873 * vmalloc_init() is called. @vm->addr, @vm->size, and @vm->flags
1874 * should contain proper values and the other fields should be zero.
1875 *
1876 * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING.
1877 */
1878void __init vm_area_add_early(struct vm_struct *vm)
1879{
1880 struct vm_struct *tmp, **p;
1881
1882 BUG_ON(vmap_initialized);
1883 for (p = &vmlist; (tmp = *p) != NULL; p = &tmp->next) {
1884 if (tmp->addr >= vm->addr) {
1885 BUG_ON(tmp->addr < vm->addr + vm->size);
1886 break;
1887 } else
1888 BUG_ON(tmp->addr + tmp->size > vm->addr);
1889 }
1890 vm->next = *p;
1891 *p = vm;
1892}
1893
f0aa6617
TH
1894/**
1895 * vm_area_register_early - register vmap area early during boot
1896 * @vm: vm_struct to register
c0c0a293 1897 * @align: requested alignment
f0aa6617
TH
1898 *
1899 * This function is used to register kernel vm area before
1900 * vmalloc_init() is called. @vm->size and @vm->flags should contain
1901 * proper values on entry and other fields should be zero. On return,
1902 * vm->addr contains the allocated address.
1903 *
1904 * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING.
1905 */
c0c0a293 1906void __init vm_area_register_early(struct vm_struct *vm, size_t align)
f0aa6617
TH
1907{
1908 static size_t vm_init_off __initdata;
c0c0a293
TH
1909 unsigned long addr;
1910
1911 addr = ALIGN(VMALLOC_START + vm_init_off, align);
1912 vm_init_off = PFN_ALIGN(addr + vm->size) - VMALLOC_START;
f0aa6617 1913
c0c0a293 1914 vm->addr = (void *)addr;
f0aa6617 1915
be9b7335 1916 vm_area_add_early(vm);
f0aa6617
TH
1917}
1918
68ad4a33
URS
1919static void vmap_init_free_space(void)
1920{
1921 unsigned long vmap_start = 1;
1922 const unsigned long vmap_end = ULONG_MAX;
1923 struct vmap_area *busy, *free;
1924
1925 /*
1926 * B F B B B F
1927 * -|-----|.....|-----|-----|-----|.....|-
1928 * | The KVA space |
1929 * |<--------------------------------->|
1930 */
1931 list_for_each_entry(busy, &vmap_area_list, list) {
1932 if (busy->va_start - vmap_start > 0) {
1933 free = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
1934 if (!WARN_ON_ONCE(!free)) {
1935 free->va_start = vmap_start;
1936 free->va_end = busy->va_start;
1937
1938 insert_vmap_area_augment(free, NULL,
1939 &free_vmap_area_root,
1940 &free_vmap_area_list);
1941 }
1942 }
1943
1944 vmap_start = busy->va_end;
1945 }
1946
1947 if (vmap_end - vmap_start > 0) {
1948 free = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
1949 if (!WARN_ON_ONCE(!free)) {
1950 free->va_start = vmap_start;
1951 free->va_end = vmap_end;
1952
1953 insert_vmap_area_augment(free, NULL,
1954 &free_vmap_area_root,
1955 &free_vmap_area_list);
1956 }
1957 }
1958}
1959
db64fe02
NP
1960void __init vmalloc_init(void)
1961{
822c18f2
IK
1962 struct vmap_area *va;
1963 struct vm_struct *tmp;
db64fe02
NP
1964 int i;
1965
68ad4a33
URS
1966 /*
1967 * Create the cache for vmap_area objects.
1968 */
1969 vmap_area_cachep = KMEM_CACHE(vmap_area, SLAB_PANIC);
1970
db64fe02
NP
1971 for_each_possible_cpu(i) {
1972 struct vmap_block_queue *vbq;
32fcfd40 1973 struct vfree_deferred *p;
db64fe02
NP
1974
1975 vbq = &per_cpu(vmap_block_queue, i);
1976 spin_lock_init(&vbq->lock);
1977 INIT_LIST_HEAD(&vbq->free);
32fcfd40
AV
1978 p = &per_cpu(vfree_deferred, i);
1979 init_llist_head(&p->list);
1980 INIT_WORK(&p->wq, free_work);
db64fe02 1981 }
9b463334 1982
822c18f2
IK
1983 /* Import existing vmlist entries. */
1984 for (tmp = vmlist; tmp; tmp = tmp->next) {
68ad4a33
URS
1985 va = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
1986 if (WARN_ON_ONCE(!va))
1987 continue;
1988
822c18f2
IK
1989 va->va_start = (unsigned long)tmp->addr;
1990 va->va_end = va->va_start + tmp->size;
dbda591d 1991 va->vm = tmp;
68ad4a33 1992 insert_vmap_area(va, &vmap_area_root, &vmap_area_list);
822c18f2 1993 }
ca23e405 1994
68ad4a33
URS
1995 /*
1996 * Now we can initialize a free vmap space.
1997 */
1998 vmap_init_free_space();
9b463334 1999 vmap_initialized = true;
db64fe02
NP
2000}
2001
8fc48985
TH
2002/**
2003 * unmap_kernel_range - unmap kernel VM area and flush cache and TLB
2004 * @addr: start of the VM area to unmap
2005 * @size: size of the VM area to unmap
2006 *
2007 * Similar to unmap_kernel_range_noflush() but flushes vcache before
2008 * the unmapping and tlb after.
2009 */
db64fe02
NP
2010void unmap_kernel_range(unsigned long addr, unsigned long size)
2011{
2012 unsigned long end = addr + size;
f6fcba70
TH
2013
2014 flush_cache_vunmap(addr, end);
b521c43f 2015 unmap_kernel_range_noflush(addr, size);
db64fe02
NP
2016 flush_tlb_kernel_range(addr, end);
2017}
2018
e36176be
URS
2019static inline void setup_vmalloc_vm_locked(struct vm_struct *vm,
2020 struct vmap_area *va, unsigned long flags, const void *caller)
cf88c790 2021{
cf88c790
TH
2022 vm->flags = flags;
2023 vm->addr = (void *)va->va_start;
2024 vm->size = va->va_end - va->va_start;
2025 vm->caller = caller;
db1aecaf 2026 va->vm = vm;
e36176be
URS
2027}
2028
2029static void setup_vmalloc_vm(struct vm_struct *vm, struct vmap_area *va,
2030 unsigned long flags, const void *caller)
2031{
2032 spin_lock(&vmap_area_lock);
2033 setup_vmalloc_vm_locked(vm, va, flags, caller);
c69480ad 2034 spin_unlock(&vmap_area_lock);
f5252e00 2035}
cf88c790 2036
20fc02b4 2037static void clear_vm_uninitialized_flag(struct vm_struct *vm)
f5252e00 2038{
d4033afd 2039 /*
20fc02b4 2040 * Before removing VM_UNINITIALIZED,
d4033afd
JK
2041 * we should make sure that vm has proper values.
2042 * Pair with smp_rmb() in show_numa_info().
2043 */
2044 smp_wmb();
20fc02b4 2045 vm->flags &= ~VM_UNINITIALIZED;
cf88c790
TH
2046}
2047
db64fe02 2048static struct vm_struct *__get_vm_area_node(unsigned long size,
2dca6999 2049 unsigned long align, unsigned long flags, unsigned long start,
5e6cafc8 2050 unsigned long end, int node, gfp_t gfp_mask, const void *caller)
db64fe02 2051{
0006526d 2052 struct vmap_area *va;
db64fe02 2053 struct vm_struct *area;
d98c9e83 2054 unsigned long requested_size = size;
1da177e4 2055
52fd24ca 2056 BUG_ON(in_interrupt());
1da177e4 2057 size = PAGE_ALIGN(size);
31be8309
OH
2058 if (unlikely(!size))
2059 return NULL;
1da177e4 2060
252e5c6e 2061 if (flags & VM_IOREMAP)
2062 align = 1ul << clamp_t(int, get_count_order_long(size),
2063 PAGE_SHIFT, IOREMAP_MAX_ORDER);
2064
cf88c790 2065 area = kzalloc_node(sizeof(*area), gfp_mask & GFP_RECLAIM_MASK, node);
1da177e4
LT
2066 if (unlikely(!area))
2067 return NULL;
2068
71394fe5
AR
2069 if (!(flags & VM_NO_GUARD))
2070 size += PAGE_SIZE;
1da177e4 2071
db64fe02
NP
2072 va = alloc_vmap_area(size, align, start, end, node, gfp_mask);
2073 if (IS_ERR(va)) {
2074 kfree(area);
2075 return NULL;
1da177e4 2076 }
1da177e4 2077
d98c9e83 2078 kasan_unpoison_vmalloc((void *)va->va_start, requested_size);
f5252e00 2079
d98c9e83 2080 setup_vmalloc_vm(area, va, flags, caller);
3c5c3cfb 2081
1da177e4 2082 return area;
1da177e4
LT
2083}
2084
c2968612
BH
2085struct vm_struct *__get_vm_area_caller(unsigned long size, unsigned long flags,
2086 unsigned long start, unsigned long end,
5e6cafc8 2087 const void *caller)
c2968612 2088{
00ef2d2f
DR
2089 return __get_vm_area_node(size, 1, flags, start, end, NUMA_NO_NODE,
2090 GFP_KERNEL, caller);
c2968612
BH
2091}
2092
1da177e4 2093/**
92eac168
MR
2094 * get_vm_area - reserve a contiguous kernel virtual area
2095 * @size: size of the area
2096 * @flags: %VM_IOREMAP for I/O mappings or VM_ALLOC
1da177e4 2097 *
92eac168
MR
2098 * Search an area of @size in the kernel virtual mapping area,
2099 * and reserved it for out purposes. Returns the area descriptor
2100 * on success or %NULL on failure.
a862f68a
MR
2101 *
2102 * Return: the area descriptor on success or %NULL on failure.
1da177e4
LT
2103 */
2104struct vm_struct *get_vm_area(unsigned long size, unsigned long flags)
2105{
2dca6999 2106 return __get_vm_area_node(size, 1, flags, VMALLOC_START, VMALLOC_END,
00ef2d2f
DR
2107 NUMA_NO_NODE, GFP_KERNEL,
2108 __builtin_return_address(0));
23016969
CL
2109}
2110
2111struct vm_struct *get_vm_area_caller(unsigned long size, unsigned long flags,
5e6cafc8 2112 const void *caller)
23016969 2113{
2dca6999 2114 return __get_vm_area_node(size, 1, flags, VMALLOC_START, VMALLOC_END,
00ef2d2f 2115 NUMA_NO_NODE, GFP_KERNEL, caller);
1da177e4
LT
2116}
2117
e9da6e99 2118/**
92eac168
MR
2119 * find_vm_area - find a continuous kernel virtual area
2120 * @addr: base address
e9da6e99 2121 *
92eac168
MR
2122 * Search for the kernel VM area starting at @addr, and return it.
2123 * It is up to the caller to do all required locking to keep the returned
2124 * pointer valid.
a862f68a
MR
2125 *
2126 * Return: pointer to the found area or %NULL on faulure
e9da6e99
MS
2127 */
2128struct vm_struct *find_vm_area(const void *addr)
83342314 2129{
db64fe02 2130 struct vmap_area *va;
83342314 2131
db64fe02 2132 va = find_vmap_area((unsigned long)addr);
688fcbfc
PL
2133 if (!va)
2134 return NULL;
1da177e4 2135
688fcbfc 2136 return va->vm;
1da177e4
LT
2137}
2138
7856dfeb 2139/**
92eac168
MR
2140 * remove_vm_area - find and remove a continuous kernel virtual area
2141 * @addr: base address
7856dfeb 2142 *
92eac168
MR
2143 * Search for the kernel VM area starting at @addr, and remove it.
2144 * This function returns the found VM area, but using it is NOT safe
2145 * on SMP machines, except for its size or flags.
a862f68a
MR
2146 *
2147 * Return: pointer to the found area or %NULL on faulure
7856dfeb 2148 */
b3bdda02 2149struct vm_struct *remove_vm_area(const void *addr)
7856dfeb 2150{
db64fe02
NP
2151 struct vmap_area *va;
2152
5803ed29
CH
2153 might_sleep();
2154
dd3b8353
URS
2155 spin_lock(&vmap_area_lock);
2156 va = __find_vmap_area((unsigned long)addr);
688fcbfc 2157 if (va && va->vm) {
db1aecaf 2158 struct vm_struct *vm = va->vm;
f5252e00 2159
c69480ad 2160 va->vm = NULL;
c69480ad
JK
2161 spin_unlock(&vmap_area_lock);
2162
a5af5aa8 2163 kasan_free_shadow(vm);
dd32c279 2164 free_unmap_vmap_area(va);
dd32c279 2165
db64fe02
NP
2166 return vm;
2167 }
dd3b8353
URS
2168
2169 spin_unlock(&vmap_area_lock);
db64fe02 2170 return NULL;
7856dfeb
AK
2171}
2172
868b104d
RE
2173static inline void set_area_direct_map(const struct vm_struct *area,
2174 int (*set_direct_map)(struct page *page))
2175{
2176 int i;
2177
2178 for (i = 0; i < area->nr_pages; i++)
2179 if (page_address(area->pages[i]))
2180 set_direct_map(area->pages[i]);
2181}
2182
2183/* Handle removing and resetting vm mappings related to the vm_struct. */
2184static void vm_remove_mappings(struct vm_struct *area, int deallocate_pages)
2185{
868b104d
RE
2186 unsigned long start = ULONG_MAX, end = 0;
2187 int flush_reset = area->flags & VM_FLUSH_RESET_PERMS;
31e67340 2188 int flush_dmap = 0;
868b104d
RE
2189 int i;
2190
868b104d
RE
2191 remove_vm_area(area->addr);
2192
2193 /* If this is not VM_FLUSH_RESET_PERMS memory, no need for the below. */
2194 if (!flush_reset)
2195 return;
2196
2197 /*
2198 * If not deallocating pages, just do the flush of the VM area and
2199 * return.
2200 */
2201 if (!deallocate_pages) {
2202 vm_unmap_aliases();
2203 return;
2204 }
2205
2206 /*
2207 * If execution gets here, flush the vm mapping and reset the direct
2208 * map. Find the start and end range of the direct mappings to make sure
2209 * the vm_unmap_aliases() flush includes the direct map.
2210 */
2211 for (i = 0; i < area->nr_pages; i++) {
8e41f872
RE
2212 unsigned long addr = (unsigned long)page_address(area->pages[i]);
2213 if (addr) {
868b104d 2214 start = min(addr, start);
8e41f872 2215 end = max(addr + PAGE_SIZE, end);
31e67340 2216 flush_dmap = 1;
868b104d
RE
2217 }
2218 }
2219
2220 /*
2221 * Set direct map to something invalid so that it won't be cached if
2222 * there are any accesses after the TLB flush, then flush the TLB and
2223 * reset the direct map permissions to the default.
2224 */
2225 set_area_direct_map(area, set_direct_map_invalid_noflush);
31e67340 2226 _vm_unmap_aliases(start, end, flush_dmap);
868b104d
RE
2227 set_area_direct_map(area, set_direct_map_default_noflush);
2228}
2229
b3bdda02 2230static void __vunmap(const void *addr, int deallocate_pages)
1da177e4
LT
2231{
2232 struct vm_struct *area;
2233
2234 if (!addr)
2235 return;
2236
e69e9d4a 2237 if (WARN(!PAGE_ALIGNED(addr), "Trying to vfree() bad address (%p)\n",
ab15d9b4 2238 addr))
1da177e4 2239 return;
1da177e4 2240
6ade2032 2241 area = find_vm_area(addr);
1da177e4 2242 if (unlikely(!area)) {
4c8573e2 2243 WARN(1, KERN_ERR "Trying to vfree() nonexistent vm area (%p)\n",
1da177e4 2244 addr);
1da177e4
LT
2245 return;
2246 }
2247
05e3ff95
CP
2248 debug_check_no_locks_freed(area->addr, get_vm_area_size(area));
2249 debug_check_no_obj_freed(area->addr, get_vm_area_size(area));
9a11b49a 2250
d98c9e83 2251 kasan_poison_vmalloc(area->addr, area->size);
3c5c3cfb 2252
868b104d
RE
2253 vm_remove_mappings(area, deallocate_pages);
2254
1da177e4
LT
2255 if (deallocate_pages) {
2256 int i;
2257
2258 for (i = 0; i < area->nr_pages; i++) {
bf53d6f8
CL
2259 struct page *page = area->pages[i];
2260
2261 BUG_ON(!page);
4949148a 2262 __free_pages(page, 0);
1da177e4 2263 }
97105f0a 2264 atomic_long_sub(area->nr_pages, &nr_vmalloc_pages);
1da177e4 2265
244d63ee 2266 kvfree(area->pages);
1da177e4
LT
2267 }
2268
2269 kfree(area);
2270 return;
2271}
bf22e37a
AR
2272
2273static inline void __vfree_deferred(const void *addr)
2274{
2275 /*
2276 * Use raw_cpu_ptr() because this can be called from preemptible
2277 * context. Preemption is absolutely fine here, because the llist_add()
2278 * implementation is lockless, so it works even if we are adding to
73221d88 2279 * another cpu's list. schedule_work() should be fine with this too.
bf22e37a
AR
2280 */
2281 struct vfree_deferred *p = raw_cpu_ptr(&vfree_deferred);
2282
2283 if (llist_add((struct llist_node *)addr, &p->list))
2284 schedule_work(&p->wq);
2285}
2286
2287/**
92eac168
MR
2288 * vfree_atomic - release memory allocated by vmalloc()
2289 * @addr: memory base address
bf22e37a 2290 *
92eac168
MR
2291 * This one is just like vfree() but can be called in any atomic context
2292 * except NMIs.
bf22e37a
AR
2293 */
2294void vfree_atomic(const void *addr)
2295{
2296 BUG_ON(in_nmi());
2297
2298 kmemleak_free(addr);
2299
2300 if (!addr)
2301 return;
2302 __vfree_deferred(addr);
2303}
2304
c67dc624
RP
2305static void __vfree(const void *addr)
2306{
2307 if (unlikely(in_interrupt()))
2308 __vfree_deferred(addr);
2309 else
2310 __vunmap(addr, 1);
2311}
2312
1da177e4 2313/**
92eac168
MR
2314 * vfree - release memory allocated by vmalloc()
2315 * @addr: memory base address
1da177e4 2316 *
92eac168
MR
2317 * Free the virtually continuous memory area starting at @addr, as
2318 * obtained from vmalloc(), vmalloc_32() or __vmalloc(). If @addr is
2319 * NULL, no operation is performed.
1da177e4 2320 *
92eac168
MR
2321 * Must not be called in NMI context (strictly speaking, only if we don't
2322 * have CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG, but making the calling
2323 * conventions for vfree() arch-depenedent would be a really bad idea)
c9fcee51 2324 *
92eac168 2325 * May sleep if called *not* from interrupt context.
3ca4ea3a 2326 *
92eac168 2327 * NOTE: assumes that the object at @addr has a size >= sizeof(llist_node)
1da177e4 2328 */
b3bdda02 2329void vfree(const void *addr)
1da177e4 2330{
32fcfd40 2331 BUG_ON(in_nmi());
89219d37
CM
2332
2333 kmemleak_free(addr);
2334
a8dda165
AR
2335 might_sleep_if(!in_interrupt());
2336
32fcfd40
AV
2337 if (!addr)
2338 return;
c67dc624
RP
2339
2340 __vfree(addr);
1da177e4 2341}
1da177e4
LT
2342EXPORT_SYMBOL(vfree);
2343
2344/**
92eac168
MR
2345 * vunmap - release virtual mapping obtained by vmap()
2346 * @addr: memory base address
1da177e4 2347 *
92eac168
MR
2348 * Free the virtually contiguous memory area starting at @addr,
2349 * which was created from the page array passed to vmap().
1da177e4 2350 *
92eac168 2351 * Must not be called in interrupt context.
1da177e4 2352 */
b3bdda02 2353void vunmap(const void *addr)
1da177e4
LT
2354{
2355 BUG_ON(in_interrupt());
34754b69 2356 might_sleep();
32fcfd40
AV
2357 if (addr)
2358 __vunmap(addr, 0);
1da177e4 2359}
1da177e4
LT
2360EXPORT_SYMBOL(vunmap);
2361
2362/**
92eac168
MR
2363 * vmap - map an array of pages into virtually contiguous space
2364 * @pages: array of page pointers
2365 * @count: number of pages to map
2366 * @flags: vm_area->flags
2367 * @prot: page protection for the mapping
2368 *
2369 * Maps @count pages from @pages into contiguous kernel virtual
2370 * space.
a862f68a
MR
2371 *
2372 * Return: the address of the area or %NULL on failure
1da177e4
LT
2373 */
2374void *vmap(struct page **pages, unsigned int count,
92eac168 2375 unsigned long flags, pgprot_t prot)
1da177e4
LT
2376{
2377 struct vm_struct *area;
65ee03c4 2378 unsigned long size; /* In bytes */
1da177e4 2379
34754b69
PZ
2380 might_sleep();
2381
ca79b0c2 2382 if (count > totalram_pages())
1da177e4
LT
2383 return NULL;
2384
65ee03c4
GJM
2385 size = (unsigned long)count << PAGE_SHIFT;
2386 area = get_vm_area_caller(size, flags, __builtin_return_address(0));
1da177e4
LT
2387 if (!area)
2388 return NULL;
23016969 2389
cca98e9f 2390 if (map_kernel_range((unsigned long)area->addr, size, pgprot_nx(prot),
ed1f324c 2391 pages) < 0) {
1da177e4
LT
2392 vunmap(area->addr);
2393 return NULL;
2394 }
2395
2396 return area->addr;
2397}
1da177e4
LT
2398EXPORT_SYMBOL(vmap);
2399
e31d9eb5 2400static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask,
3722e13c 2401 pgprot_t prot, int node)
1da177e4
LT
2402{
2403 struct page **pages;
2404 unsigned int nr_pages, array_size, i;
930f036b 2405 const gfp_t nested_gfp = (gfp_mask & GFP_RECLAIM_MASK) | __GFP_ZERO;
704b862f
LA
2406 const gfp_t alloc_mask = gfp_mask | __GFP_NOWARN;
2407 const gfp_t highmem_mask = (gfp_mask & (GFP_DMA | GFP_DMA32)) ?
2408 0 :
2409 __GFP_HIGHMEM;
1da177e4 2410
762216ab 2411 nr_pages = get_vm_area_size(area) >> PAGE_SHIFT;
1da177e4
LT
2412 array_size = (nr_pages * sizeof(struct page *));
2413
1da177e4 2414 /* Please note that the recursion is strictly bounded. */
8757d5fa 2415 if (array_size > PAGE_SIZE) {
704b862f 2416 pages = __vmalloc_node(array_size, 1, nested_gfp|highmem_mask,
f38fcb9c 2417 node, area->caller);
286e1ea3 2418 } else {
976d6dfb 2419 pages = kmalloc_node(array_size, nested_gfp, node);
286e1ea3 2420 }
7ea36242
AK
2421
2422 if (!pages) {
1da177e4
LT
2423 remove_vm_area(area->addr);
2424 kfree(area);
2425 return NULL;
2426 }
1da177e4 2427
7ea36242
AK
2428 area->pages = pages;
2429 area->nr_pages = nr_pages;
2430
1da177e4 2431 for (i = 0; i < area->nr_pages; i++) {
bf53d6f8
CL
2432 struct page *page;
2433
4b90951c 2434 if (node == NUMA_NO_NODE)
704b862f 2435 page = alloc_page(alloc_mask|highmem_mask);
930fc45a 2436 else
704b862f 2437 page = alloc_pages_node(node, alloc_mask|highmem_mask, 0);
bf53d6f8
CL
2438
2439 if (unlikely(!page)) {
1da177e4
LT
2440 /* Successfully allocated i pages, free them in __vunmap() */
2441 area->nr_pages = i;
97105f0a 2442 atomic_long_add(area->nr_pages, &nr_vmalloc_pages);
1da177e4
LT
2443 goto fail;
2444 }
bf53d6f8 2445 area->pages[i] = page;
dcf61ff0 2446 if (gfpflags_allow_blocking(gfp_mask))
660654f9 2447 cond_resched();
1da177e4 2448 }
97105f0a 2449 atomic_long_add(area->nr_pages, &nr_vmalloc_pages);
1da177e4 2450
ed1f324c
CH
2451 if (map_kernel_range((unsigned long)area->addr, get_vm_area_size(area),
2452 prot, pages) < 0)
1da177e4 2453 goto fail;
ed1f324c 2454
1da177e4
LT
2455 return area->addr;
2456
2457fail:
a8e99259 2458 warn_alloc(gfp_mask, NULL,
7877cdcc 2459 "vmalloc: allocation failure, allocated %ld of %ld bytes",
22943ab1 2460 (area->nr_pages*PAGE_SIZE), area->size);
c67dc624 2461 __vfree(area->addr);
1da177e4
LT
2462 return NULL;
2463}
2464
2465/**
92eac168
MR
2466 * __vmalloc_node_range - allocate virtually contiguous memory
2467 * @size: allocation size
2468 * @align: desired alignment
2469 * @start: vm area range start
2470 * @end: vm area range end
2471 * @gfp_mask: flags for the page level allocator
2472 * @prot: protection mask for the allocated pages
2473 * @vm_flags: additional vm area flags (e.g. %VM_NO_GUARD)
2474 * @node: node to use for allocation or NUMA_NO_NODE
2475 * @caller: caller's return address
2476 *
2477 * Allocate enough pages to cover @size from the page level
2478 * allocator with @gfp_mask flags. Map them into contiguous
2479 * kernel virtual space, using a pagetable protection of @prot.
a862f68a
MR
2480 *
2481 * Return: the address of the area or %NULL on failure
1da177e4 2482 */
d0a21265
DR
2483void *__vmalloc_node_range(unsigned long size, unsigned long align,
2484 unsigned long start, unsigned long end, gfp_t gfp_mask,
cb9e3c29
AR
2485 pgprot_t prot, unsigned long vm_flags, int node,
2486 const void *caller)
1da177e4
LT
2487{
2488 struct vm_struct *area;
89219d37
CM
2489 void *addr;
2490 unsigned long real_size = size;
1da177e4
LT
2491
2492 size = PAGE_ALIGN(size);
ca79b0c2 2493 if (!size || (size >> PAGE_SHIFT) > totalram_pages())
de7d2b56 2494 goto fail;
1da177e4 2495
d98c9e83 2496 area = __get_vm_area_node(real_size, align, VM_ALLOC | VM_UNINITIALIZED |
cb9e3c29 2497 vm_flags, start, end, node, gfp_mask, caller);
1da177e4 2498 if (!area)
de7d2b56 2499 goto fail;
1da177e4 2500
3722e13c 2501 addr = __vmalloc_area_node(area, gfp_mask, prot, node);
1368edf0 2502 if (!addr)
b82225f3 2503 return NULL;
89219d37 2504
f5252e00 2505 /*
20fc02b4
ZY
2506 * In this function, newly allocated vm_struct has VM_UNINITIALIZED
2507 * flag. It means that vm_struct is not fully initialized.
4341fa45 2508 * Now, it is fully initialized, so remove this flag here.
f5252e00 2509 */
20fc02b4 2510 clear_vm_uninitialized_flag(area);
f5252e00 2511
94f4a161 2512 kmemleak_vmalloc(area, size, gfp_mask);
89219d37
CM
2513
2514 return addr;
de7d2b56
JP
2515
2516fail:
a8e99259 2517 warn_alloc(gfp_mask, NULL,
7877cdcc 2518 "vmalloc: allocation failure: %lu bytes", real_size);
de7d2b56 2519 return NULL;
1da177e4
LT
2520}
2521
d0a21265 2522/**
92eac168
MR
2523 * __vmalloc_node - allocate virtually contiguous memory
2524 * @size: allocation size
2525 * @align: desired alignment
2526 * @gfp_mask: flags for the page level allocator
92eac168
MR
2527 * @node: node to use for allocation or NUMA_NO_NODE
2528 * @caller: caller's return address
a7c3e901 2529 *
f38fcb9c
CH
2530 * Allocate enough pages to cover @size from the page level allocator with
2531 * @gfp_mask flags. Map them into contiguous kernel virtual space.
a7c3e901 2532 *
92eac168
MR
2533 * Reclaim modifiers in @gfp_mask - __GFP_NORETRY, __GFP_RETRY_MAYFAIL
2534 * and __GFP_NOFAIL are not supported
a7c3e901 2535 *
92eac168
MR
2536 * Any use of gfp flags outside of GFP_KERNEL should be consulted
2537 * with mm people.
a862f68a
MR
2538 *
2539 * Return: pointer to the allocated memory or %NULL on error
d0a21265 2540 */
2b905948 2541void *__vmalloc_node(unsigned long size, unsigned long align,
f38fcb9c 2542 gfp_t gfp_mask, int node, const void *caller)
d0a21265
DR
2543{
2544 return __vmalloc_node_range(size, align, VMALLOC_START, VMALLOC_END,
f38fcb9c 2545 gfp_mask, PAGE_KERNEL, 0, node, caller);
d0a21265 2546}
c3f896dc
CH
2547/*
2548 * This is only for performance analysis of vmalloc and stress purpose.
2549 * It is required by vmalloc test module, therefore do not use it other
2550 * than that.
2551 */
2552#ifdef CONFIG_TEST_VMALLOC_MODULE
2553EXPORT_SYMBOL_GPL(__vmalloc_node);
2554#endif
d0a21265 2555
88dca4ca 2556void *__vmalloc(unsigned long size, gfp_t gfp_mask)
930fc45a 2557{
f38fcb9c 2558 return __vmalloc_node(size, 1, gfp_mask, NUMA_NO_NODE,
23016969 2559 __builtin_return_address(0));
930fc45a 2560}
1da177e4
LT
2561EXPORT_SYMBOL(__vmalloc);
2562
2563/**
92eac168
MR
2564 * vmalloc - allocate virtually contiguous memory
2565 * @size: allocation size
2566 *
2567 * Allocate enough pages to cover @size from the page level
2568 * allocator and map them into contiguous kernel virtual space.
1da177e4 2569 *
92eac168
MR
2570 * For tight control over page level allocator and protection flags
2571 * use __vmalloc() instead.
a862f68a
MR
2572 *
2573 * Return: pointer to the allocated memory or %NULL on error
1da177e4
LT
2574 */
2575void *vmalloc(unsigned long size)
2576{
4d39d728
CH
2577 return __vmalloc_node(size, 1, GFP_KERNEL, NUMA_NO_NODE,
2578 __builtin_return_address(0));
1da177e4 2579}
1da177e4
LT
2580EXPORT_SYMBOL(vmalloc);
2581
e1ca7788 2582/**
92eac168
MR
2583 * vzalloc - allocate virtually contiguous memory with zero fill
2584 * @size: allocation size
2585 *
2586 * Allocate enough pages to cover @size from the page level
2587 * allocator and map them into contiguous kernel virtual space.
2588 * The memory allocated is set to zero.
2589 *
2590 * For tight control over page level allocator and protection flags
2591 * use __vmalloc() instead.
a862f68a
MR
2592 *
2593 * Return: pointer to the allocated memory or %NULL on error
e1ca7788
DY
2594 */
2595void *vzalloc(unsigned long size)
2596{
4d39d728
CH
2597 return __vmalloc_node(size, 1, GFP_KERNEL | __GFP_ZERO, NUMA_NO_NODE,
2598 __builtin_return_address(0));
e1ca7788
DY
2599}
2600EXPORT_SYMBOL(vzalloc);
2601
83342314 2602/**
ead04089
REB
2603 * vmalloc_user - allocate zeroed virtually contiguous memory for userspace
2604 * @size: allocation size
83342314 2605 *
ead04089
REB
2606 * The resulting memory area is zeroed so it can be mapped to userspace
2607 * without leaking data.
a862f68a
MR
2608 *
2609 * Return: pointer to the allocated memory or %NULL on error
83342314
NP
2610 */
2611void *vmalloc_user(unsigned long size)
2612{
bc84c535
RP
2613 return __vmalloc_node_range(size, SHMLBA, VMALLOC_START, VMALLOC_END,
2614 GFP_KERNEL | __GFP_ZERO, PAGE_KERNEL,
2615 VM_USERMAP, NUMA_NO_NODE,
2616 __builtin_return_address(0));
83342314
NP
2617}
2618EXPORT_SYMBOL(vmalloc_user);
2619
930fc45a 2620/**
92eac168
MR
2621 * vmalloc_node - allocate memory on a specific node
2622 * @size: allocation size
2623 * @node: numa node
930fc45a 2624 *
92eac168
MR
2625 * Allocate enough pages to cover @size from the page level
2626 * allocator and map them into contiguous kernel virtual space.
930fc45a 2627 *
92eac168
MR
2628 * For tight control over page level allocator and protection flags
2629 * use __vmalloc() instead.
a862f68a
MR
2630 *
2631 * Return: pointer to the allocated memory or %NULL on error
930fc45a
CL
2632 */
2633void *vmalloc_node(unsigned long size, int node)
2634{
f38fcb9c
CH
2635 return __vmalloc_node(size, 1, GFP_KERNEL, node,
2636 __builtin_return_address(0));
930fc45a
CL
2637}
2638EXPORT_SYMBOL(vmalloc_node);
2639
e1ca7788
DY
2640/**
2641 * vzalloc_node - allocate memory on a specific node with zero fill
2642 * @size: allocation size
2643 * @node: numa node
2644 *
2645 * Allocate enough pages to cover @size from the page level
2646 * allocator and map them into contiguous kernel virtual space.
2647 * The memory allocated is set to zero.
2648 *
a862f68a 2649 * Return: pointer to the allocated memory or %NULL on error
e1ca7788
DY
2650 */
2651void *vzalloc_node(unsigned long size, int node)
2652{
4d39d728
CH
2653 return __vmalloc_node(size, 1, GFP_KERNEL | __GFP_ZERO, node,
2654 __builtin_return_address(0));
e1ca7788
DY
2655}
2656EXPORT_SYMBOL(vzalloc_node);
2657
0d08e0d3 2658#if defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA32)
698d0831 2659#define GFP_VMALLOC32 (GFP_DMA32 | GFP_KERNEL)
0d08e0d3 2660#elif defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA)
698d0831 2661#define GFP_VMALLOC32 (GFP_DMA | GFP_KERNEL)
0d08e0d3 2662#else
698d0831
MH
2663/*
2664 * 64b systems should always have either DMA or DMA32 zones. For others
2665 * GFP_DMA32 should do the right thing and use the normal zone.
2666 */
2667#define GFP_VMALLOC32 GFP_DMA32 | GFP_KERNEL
0d08e0d3
AK
2668#endif
2669
1da177e4 2670/**
92eac168
MR
2671 * vmalloc_32 - allocate virtually contiguous memory (32bit addressable)
2672 * @size: allocation size
1da177e4 2673 *
92eac168
MR
2674 * Allocate enough 32bit PA addressable pages to cover @size from the
2675 * page level allocator and map them into contiguous kernel virtual space.
a862f68a
MR
2676 *
2677 * Return: pointer to the allocated memory or %NULL on error
1da177e4
LT
2678 */
2679void *vmalloc_32(unsigned long size)
2680{
f38fcb9c
CH
2681 return __vmalloc_node(size, 1, GFP_VMALLOC32, NUMA_NO_NODE,
2682 __builtin_return_address(0));
1da177e4 2683}
1da177e4
LT
2684EXPORT_SYMBOL(vmalloc_32);
2685
83342314 2686/**
ead04089 2687 * vmalloc_32_user - allocate zeroed virtually contiguous 32bit memory
92eac168 2688 * @size: allocation size
ead04089
REB
2689 *
2690 * The resulting memory area is 32bit addressable and zeroed so it can be
2691 * mapped to userspace without leaking data.
a862f68a
MR
2692 *
2693 * Return: pointer to the allocated memory or %NULL on error
83342314
NP
2694 */
2695void *vmalloc_32_user(unsigned long size)
2696{
bc84c535
RP
2697 return __vmalloc_node_range(size, SHMLBA, VMALLOC_START, VMALLOC_END,
2698 GFP_VMALLOC32 | __GFP_ZERO, PAGE_KERNEL,
2699 VM_USERMAP, NUMA_NO_NODE,
2700 __builtin_return_address(0));
83342314
NP
2701}
2702EXPORT_SYMBOL(vmalloc_32_user);
2703
d0107eb0
KH
2704/*
2705 * small helper routine , copy contents to buf from addr.
2706 * If the page is not present, fill zero.
2707 */
2708
2709static int aligned_vread(char *buf, char *addr, unsigned long count)
2710{
2711 struct page *p;
2712 int copied = 0;
2713
2714 while (count) {
2715 unsigned long offset, length;
2716
891c49ab 2717 offset = offset_in_page(addr);
d0107eb0
KH
2718 length = PAGE_SIZE - offset;
2719 if (length > count)
2720 length = count;
2721 p = vmalloc_to_page(addr);
2722 /*
2723 * To do safe access to this _mapped_ area, we need
2724 * lock. But adding lock here means that we need to add
2725 * overhead of vmalloc()/vfree() calles for this _debug_
2726 * interface, rarely used. Instead of that, we'll use
2727 * kmap() and get small overhead in this access function.
2728 */
2729 if (p) {
2730 /*
2731 * we can expect USER0 is not used (see vread/vwrite's
2732 * function description)
2733 */
9b04c5fe 2734 void *map = kmap_atomic(p);
d0107eb0 2735 memcpy(buf, map + offset, length);
9b04c5fe 2736 kunmap_atomic(map);
d0107eb0
KH
2737 } else
2738 memset(buf, 0, length);
2739
2740 addr += length;
2741 buf += length;
2742 copied += length;
2743 count -= length;
2744 }
2745 return copied;
2746}
2747
2748static int aligned_vwrite(char *buf, char *addr, unsigned long count)
2749{
2750 struct page *p;
2751 int copied = 0;
2752
2753 while (count) {
2754 unsigned long offset, length;
2755
891c49ab 2756 offset = offset_in_page(addr);
d0107eb0
KH
2757 length = PAGE_SIZE - offset;
2758 if (length > count)
2759 length = count;
2760 p = vmalloc_to_page(addr);
2761 /*
2762 * To do safe access to this _mapped_ area, we need
2763 * lock. But adding lock here means that we need to add
2764 * overhead of vmalloc()/vfree() calles for this _debug_
2765 * interface, rarely used. Instead of that, we'll use
2766 * kmap() and get small overhead in this access function.
2767 */
2768 if (p) {
2769 /*
2770 * we can expect USER0 is not used (see vread/vwrite's
2771 * function description)
2772 */
9b04c5fe 2773 void *map = kmap_atomic(p);
d0107eb0 2774 memcpy(map + offset, buf, length);
9b04c5fe 2775 kunmap_atomic(map);
d0107eb0
KH
2776 }
2777 addr += length;
2778 buf += length;
2779 copied += length;
2780 count -= length;
2781 }
2782 return copied;
2783}
2784
2785/**
92eac168
MR
2786 * vread() - read vmalloc area in a safe way.
2787 * @buf: buffer for reading data
2788 * @addr: vm address.
2789 * @count: number of bytes to be read.
2790 *
92eac168
MR
2791 * This function checks that addr is a valid vmalloc'ed area, and
2792 * copy data from that area to a given buffer. If the given memory range
2793 * of [addr...addr+count) includes some valid address, data is copied to
2794 * proper area of @buf. If there are memory holes, they'll be zero-filled.
2795 * IOREMAP area is treated as memory hole and no copy is done.
2796 *
2797 * If [addr...addr+count) doesn't includes any intersects with alive
2798 * vm_struct area, returns 0. @buf should be kernel's buffer.
2799 *
2800 * Note: In usual ops, vread() is never necessary because the caller
2801 * should know vmalloc() area is valid and can use memcpy().
2802 * This is for routines which have to access vmalloc area without
d9009d67 2803 * any information, as /dev/kmem.
a862f68a
MR
2804 *
2805 * Return: number of bytes for which addr and buf should be increased
2806 * (same number as @count) or %0 if [addr...addr+count) doesn't
2807 * include any intersection with valid vmalloc area
d0107eb0 2808 */
1da177e4
LT
2809long vread(char *buf, char *addr, unsigned long count)
2810{
e81ce85f
JK
2811 struct vmap_area *va;
2812 struct vm_struct *vm;
1da177e4 2813 char *vaddr, *buf_start = buf;
d0107eb0 2814 unsigned long buflen = count;
1da177e4
LT
2815 unsigned long n;
2816
2817 /* Don't allow overflow */
2818 if ((unsigned long) addr + count < count)
2819 count = -(unsigned long) addr;
2820
e81ce85f
JK
2821 spin_lock(&vmap_area_lock);
2822 list_for_each_entry(va, &vmap_area_list, list) {
2823 if (!count)
2824 break;
2825
688fcbfc 2826 if (!va->vm)
e81ce85f
JK
2827 continue;
2828
2829 vm = va->vm;
2830 vaddr = (char *) vm->addr;
762216ab 2831 if (addr >= vaddr + get_vm_area_size(vm))
1da177e4
LT
2832 continue;
2833 while (addr < vaddr) {
2834 if (count == 0)
2835 goto finished;
2836 *buf = '\0';
2837 buf++;
2838 addr++;
2839 count--;
2840 }
762216ab 2841 n = vaddr + get_vm_area_size(vm) - addr;
d0107eb0
KH
2842 if (n > count)
2843 n = count;
e81ce85f 2844 if (!(vm->flags & VM_IOREMAP))
d0107eb0
KH
2845 aligned_vread(buf, addr, n);
2846 else /* IOREMAP area is treated as memory hole */
2847 memset(buf, 0, n);
2848 buf += n;
2849 addr += n;
2850 count -= n;
1da177e4
LT
2851 }
2852finished:
e81ce85f 2853 spin_unlock(&vmap_area_lock);
d0107eb0
KH
2854
2855 if (buf == buf_start)
2856 return 0;
2857 /* zero-fill memory holes */
2858 if (buf != buf_start + buflen)
2859 memset(buf, 0, buflen - (buf - buf_start));
2860
2861 return buflen;
1da177e4
LT
2862}
2863
d0107eb0 2864/**
92eac168
MR
2865 * vwrite() - write vmalloc area in a safe way.
2866 * @buf: buffer for source data
2867 * @addr: vm address.
2868 * @count: number of bytes to be read.
2869 *
92eac168
MR
2870 * This function checks that addr is a valid vmalloc'ed area, and
2871 * copy data from a buffer to the given addr. If specified range of
2872 * [addr...addr+count) includes some valid address, data is copied from
2873 * proper area of @buf. If there are memory holes, no copy to hole.
2874 * IOREMAP area is treated as memory hole and no copy is done.
2875 *
2876 * If [addr...addr+count) doesn't includes any intersects with alive
2877 * vm_struct area, returns 0. @buf should be kernel's buffer.
2878 *
2879 * Note: In usual ops, vwrite() is never necessary because the caller
2880 * should know vmalloc() area is valid and can use memcpy().
2881 * This is for routines which have to access vmalloc area without
d9009d67 2882 * any information, as /dev/kmem.
a862f68a
MR
2883 *
2884 * Return: number of bytes for which addr and buf should be
2885 * increased (same number as @count) or %0 if [addr...addr+count)
2886 * doesn't include any intersection with valid vmalloc area
d0107eb0 2887 */
1da177e4
LT
2888long vwrite(char *buf, char *addr, unsigned long count)
2889{
e81ce85f
JK
2890 struct vmap_area *va;
2891 struct vm_struct *vm;
d0107eb0
KH
2892 char *vaddr;
2893 unsigned long n, buflen;
2894 int copied = 0;
1da177e4
LT
2895
2896 /* Don't allow overflow */
2897 if ((unsigned long) addr + count < count)
2898 count = -(unsigned long) addr;
d0107eb0 2899 buflen = count;
1da177e4 2900
e81ce85f
JK
2901 spin_lock(&vmap_area_lock);
2902 list_for_each_entry(va, &vmap_area_list, list) {
2903 if (!count)
2904 break;
2905
688fcbfc 2906 if (!va->vm)
e81ce85f
JK
2907 continue;
2908
2909 vm = va->vm;
2910 vaddr = (char *) vm->addr;
762216ab 2911 if (addr >= vaddr + get_vm_area_size(vm))
1da177e4
LT
2912 continue;
2913 while (addr < vaddr) {
2914 if (count == 0)
2915 goto finished;
2916 buf++;
2917 addr++;
2918 count--;
2919 }
762216ab 2920 n = vaddr + get_vm_area_size(vm) - addr;
d0107eb0
KH
2921 if (n > count)
2922 n = count;
e81ce85f 2923 if (!(vm->flags & VM_IOREMAP)) {
d0107eb0
KH
2924 aligned_vwrite(buf, addr, n);
2925 copied++;
2926 }
2927 buf += n;
2928 addr += n;
2929 count -= n;
1da177e4
LT
2930 }
2931finished:
e81ce85f 2932 spin_unlock(&vmap_area_lock);
d0107eb0
KH
2933 if (!copied)
2934 return 0;
2935 return buflen;
1da177e4 2936}
83342314
NP
2937
2938/**
92eac168
MR
2939 * remap_vmalloc_range_partial - map vmalloc pages to userspace
2940 * @vma: vma to cover
2941 * @uaddr: target user address to start at
2942 * @kaddr: virtual address of vmalloc kernel memory
bdebd6a2 2943 * @pgoff: offset from @kaddr to start at
92eac168 2944 * @size: size of map area
7682486b 2945 *
92eac168 2946 * Returns: 0 for success, -Exxx on failure
83342314 2947 *
92eac168
MR
2948 * This function checks that @kaddr is a valid vmalloc'ed area,
2949 * and that it is big enough to cover the range starting at
2950 * @uaddr in @vma. Will return failure if that criteria isn't
2951 * met.
83342314 2952 *
92eac168 2953 * Similar to remap_pfn_range() (see mm/memory.c)
83342314 2954 */
e69e9d4a 2955int remap_vmalloc_range_partial(struct vm_area_struct *vma, unsigned long uaddr,
bdebd6a2
JH
2956 void *kaddr, unsigned long pgoff,
2957 unsigned long size)
83342314
NP
2958{
2959 struct vm_struct *area;
bdebd6a2
JH
2960 unsigned long off;
2961 unsigned long end_index;
2962
2963 if (check_shl_overflow(pgoff, PAGE_SHIFT, &off))
2964 return -EINVAL;
83342314 2965
e69e9d4a
HD
2966 size = PAGE_ALIGN(size);
2967
2968 if (!PAGE_ALIGNED(uaddr) || !PAGE_ALIGNED(kaddr))
83342314
NP
2969 return -EINVAL;
2970
e69e9d4a 2971 area = find_vm_area(kaddr);
83342314 2972 if (!area)
db64fe02 2973 return -EINVAL;
83342314 2974
fe9041c2 2975 if (!(area->flags & (VM_USERMAP | VM_DMA_COHERENT)))
db64fe02 2976 return -EINVAL;
83342314 2977
bdebd6a2
JH
2978 if (check_add_overflow(size, off, &end_index) ||
2979 end_index > get_vm_area_size(area))
db64fe02 2980 return -EINVAL;
bdebd6a2 2981 kaddr += off;
83342314 2982
83342314 2983 do {
e69e9d4a 2984 struct page *page = vmalloc_to_page(kaddr);
db64fe02
NP
2985 int ret;
2986
83342314
NP
2987 ret = vm_insert_page(vma, uaddr, page);
2988 if (ret)
2989 return ret;
2990
2991 uaddr += PAGE_SIZE;
e69e9d4a
HD
2992 kaddr += PAGE_SIZE;
2993 size -= PAGE_SIZE;
2994 } while (size > 0);
83342314 2995
314e51b9 2996 vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
83342314 2997
db64fe02 2998 return 0;
83342314 2999}
e69e9d4a
HD
3000EXPORT_SYMBOL(remap_vmalloc_range_partial);
3001
3002/**
92eac168
MR
3003 * remap_vmalloc_range - map vmalloc pages to userspace
3004 * @vma: vma to cover (map full range of vma)
3005 * @addr: vmalloc memory
3006 * @pgoff: number of pages into addr before first page to map
e69e9d4a 3007 *
92eac168 3008 * Returns: 0 for success, -Exxx on failure
e69e9d4a 3009 *
92eac168
MR
3010 * This function checks that addr is a valid vmalloc'ed area, and
3011 * that it is big enough to cover the vma. Will return failure if
3012 * that criteria isn't met.
e69e9d4a 3013 *
92eac168 3014 * Similar to remap_pfn_range() (see mm/memory.c)
e69e9d4a
HD
3015 */
3016int remap_vmalloc_range(struct vm_area_struct *vma, void *addr,
3017 unsigned long pgoff)
3018{
3019 return remap_vmalloc_range_partial(vma, vma->vm_start,
bdebd6a2 3020 addr, pgoff,
e69e9d4a
HD
3021 vma->vm_end - vma->vm_start);
3022}
83342314
NP
3023EXPORT_SYMBOL(remap_vmalloc_range);
3024
8b1e0f81 3025static int f(pte_t *pte, unsigned long addr, void *data)
5f4352fb 3026{
cd12909c
DV
3027 pte_t ***p = data;
3028
3029 if (p) {
3030 *(*p) = pte;
3031 (*p)++;
3032 }
5f4352fb
JF
3033 return 0;
3034}
3035
3036/**
92eac168
MR
3037 * alloc_vm_area - allocate a range of kernel address space
3038 * @size: size of the area
3039 * @ptes: returns the PTEs for the address space
7682486b 3040 *
92eac168 3041 * Returns: NULL on failure, vm_struct on success
5f4352fb 3042 *
92eac168
MR
3043 * This function reserves a range of kernel address space, and
3044 * allocates pagetables to map that range. No actual mappings
3045 * are created.
cd12909c 3046 *
92eac168
MR
3047 * If @ptes is non-NULL, pointers to the PTEs (in init_mm)
3048 * allocated for the VM area are returned.
5f4352fb 3049 */
cd12909c 3050struct vm_struct *alloc_vm_area(size_t size, pte_t **ptes)
5f4352fb
JF
3051{
3052 struct vm_struct *area;
3053
23016969
CL
3054 area = get_vm_area_caller(size, VM_IOREMAP,
3055 __builtin_return_address(0));
5f4352fb
JF
3056 if (area == NULL)
3057 return NULL;
3058
3059 /*
3060 * This ensures that page tables are constructed for this region
3061 * of kernel virtual address space and mapped into init_mm.
3062 */
3063 if (apply_to_page_range(&init_mm, (unsigned long)area->addr,
cd12909c 3064 size, f, ptes ? &ptes : NULL)) {
5f4352fb
JF
3065 free_vm_area(area);
3066 return NULL;
3067 }
3068
5f4352fb
JF
3069 return area;
3070}
3071EXPORT_SYMBOL_GPL(alloc_vm_area);
3072
3073void free_vm_area(struct vm_struct *area)
3074{
3075 struct vm_struct *ret;
3076 ret = remove_vm_area(area->addr);
3077 BUG_ON(ret != area);
3078 kfree(area);
3079}
3080EXPORT_SYMBOL_GPL(free_vm_area);
a10aa579 3081
4f8b02b4 3082#ifdef CONFIG_SMP
ca23e405
TH
3083static struct vmap_area *node_to_va(struct rb_node *n)
3084{
4583e773 3085 return rb_entry_safe(n, struct vmap_area, rb_node);
ca23e405
TH
3086}
3087
3088/**
68ad4a33
URS
3089 * pvm_find_va_enclose_addr - find the vmap_area @addr belongs to
3090 * @addr: target address
ca23e405 3091 *
68ad4a33
URS
3092 * Returns: vmap_area if it is found. If there is no such area
3093 * the first highest(reverse order) vmap_area is returned
3094 * i.e. va->va_start < addr && va->va_end < addr or NULL
3095 * if there are no any areas before @addr.
ca23e405 3096 */
68ad4a33
URS
3097static struct vmap_area *
3098pvm_find_va_enclose_addr(unsigned long addr)
ca23e405 3099{
68ad4a33
URS
3100 struct vmap_area *va, *tmp;
3101 struct rb_node *n;
3102
3103 n = free_vmap_area_root.rb_node;
3104 va = NULL;
ca23e405
TH
3105
3106 while (n) {
68ad4a33
URS
3107 tmp = rb_entry(n, struct vmap_area, rb_node);
3108 if (tmp->va_start <= addr) {
3109 va = tmp;
3110 if (tmp->va_end >= addr)
3111 break;
3112
ca23e405 3113 n = n->rb_right;
68ad4a33
URS
3114 } else {
3115 n = n->rb_left;
3116 }
ca23e405
TH
3117 }
3118
68ad4a33 3119 return va;
ca23e405
TH
3120}
3121
3122/**
68ad4a33
URS
3123 * pvm_determine_end_from_reverse - find the highest aligned address
3124 * of free block below VMALLOC_END
3125 * @va:
3126 * in - the VA we start the search(reverse order);
3127 * out - the VA with the highest aligned end address.
ca23e405 3128 *
68ad4a33 3129 * Returns: determined end address within vmap_area
ca23e405 3130 */
68ad4a33
URS
3131static unsigned long
3132pvm_determine_end_from_reverse(struct vmap_area **va, unsigned long align)
ca23e405 3133{
68ad4a33 3134 unsigned long vmalloc_end = VMALLOC_END & ~(align - 1);
ca23e405
TH
3135 unsigned long addr;
3136
68ad4a33
URS
3137 if (likely(*va)) {
3138 list_for_each_entry_from_reverse((*va),
3139 &free_vmap_area_list, list) {
3140 addr = min((*va)->va_end & ~(align - 1), vmalloc_end);
3141 if ((*va)->va_start < addr)
3142 return addr;
3143 }
ca23e405
TH
3144 }
3145
68ad4a33 3146 return 0;
ca23e405
TH
3147}
3148
3149/**
3150 * pcpu_get_vm_areas - allocate vmalloc areas for percpu allocator
3151 * @offsets: array containing offset of each area
3152 * @sizes: array containing size of each area
3153 * @nr_vms: the number of areas to allocate
3154 * @align: alignment, all entries in @offsets and @sizes must be aligned to this
ca23e405
TH
3155 *
3156 * Returns: kmalloc'd vm_struct pointer array pointing to allocated
3157 * vm_structs on success, %NULL on failure
3158 *
3159 * Percpu allocator wants to use congruent vm areas so that it can
3160 * maintain the offsets among percpu areas. This function allocates
ec3f64fc
DR
3161 * congruent vmalloc areas for it with GFP_KERNEL. These areas tend to
3162 * be scattered pretty far, distance between two areas easily going up
3163 * to gigabytes. To avoid interacting with regular vmallocs, these
3164 * areas are allocated from top.
ca23e405 3165 *
68ad4a33
URS
3166 * Despite its complicated look, this allocator is rather simple. It
3167 * does everything top-down and scans free blocks from the end looking
3168 * for matching base. While scanning, if any of the areas do not fit the
3169 * base address is pulled down to fit the area. Scanning is repeated till
3170 * all the areas fit and then all necessary data structures are inserted
3171 * and the result is returned.
ca23e405
TH
3172 */
3173struct vm_struct **pcpu_get_vm_areas(const unsigned long *offsets,
3174 const size_t *sizes, int nr_vms,
ec3f64fc 3175 size_t align)
ca23e405
TH
3176{
3177 const unsigned long vmalloc_start = ALIGN(VMALLOC_START, align);
3178 const unsigned long vmalloc_end = VMALLOC_END & ~(align - 1);
68ad4a33 3179 struct vmap_area **vas, *va;
ca23e405
TH
3180 struct vm_struct **vms;
3181 int area, area2, last_area, term_area;
253a496d 3182 unsigned long base, start, size, end, last_end, orig_start, orig_end;
ca23e405 3183 bool purged = false;
68ad4a33 3184 enum fit_type type;
ca23e405 3185
ca23e405 3186 /* verify parameters and allocate data structures */
891c49ab 3187 BUG_ON(offset_in_page(align) || !is_power_of_2(align));
ca23e405
TH
3188 for (last_area = 0, area = 0; area < nr_vms; area++) {
3189 start = offsets[area];
3190 end = start + sizes[area];
3191
3192 /* is everything aligned properly? */
3193 BUG_ON(!IS_ALIGNED(offsets[area], align));
3194 BUG_ON(!IS_ALIGNED(sizes[area], align));
3195
3196 /* detect the area with the highest address */
3197 if (start > offsets[last_area])
3198 last_area = area;
3199
c568da28 3200 for (area2 = area + 1; area2 < nr_vms; area2++) {
ca23e405
TH
3201 unsigned long start2 = offsets[area2];
3202 unsigned long end2 = start2 + sizes[area2];
3203
c568da28 3204 BUG_ON(start2 < end && start < end2);
ca23e405
TH
3205 }
3206 }
3207 last_end = offsets[last_area] + sizes[last_area];
3208
3209 if (vmalloc_end - vmalloc_start < last_end) {
3210 WARN_ON(true);
3211 return NULL;
3212 }
3213
4d67d860
TM
3214 vms = kcalloc(nr_vms, sizeof(vms[0]), GFP_KERNEL);
3215 vas = kcalloc(nr_vms, sizeof(vas[0]), GFP_KERNEL);
ca23e405 3216 if (!vas || !vms)
f1db7afd 3217 goto err_free2;
ca23e405
TH
3218
3219 for (area = 0; area < nr_vms; area++) {
68ad4a33 3220 vas[area] = kmem_cache_zalloc(vmap_area_cachep, GFP_KERNEL);
ec3f64fc 3221 vms[area] = kzalloc(sizeof(struct vm_struct), GFP_KERNEL);
ca23e405
TH
3222 if (!vas[area] || !vms[area])
3223 goto err_free;
3224 }
3225retry:
e36176be 3226 spin_lock(&free_vmap_area_lock);
ca23e405
TH
3227
3228 /* start scanning - we scan from the top, begin with the last area */
3229 area = term_area = last_area;
3230 start = offsets[area];
3231 end = start + sizes[area];
3232
68ad4a33
URS
3233 va = pvm_find_va_enclose_addr(vmalloc_end);
3234 base = pvm_determine_end_from_reverse(&va, align) - end;
ca23e405
TH
3235
3236 while (true) {
ca23e405
TH
3237 /*
3238 * base might have underflowed, add last_end before
3239 * comparing.
3240 */
68ad4a33
URS
3241 if (base + last_end < vmalloc_start + last_end)
3242 goto overflow;
ca23e405
TH
3243
3244 /*
68ad4a33 3245 * Fitting base has not been found.
ca23e405 3246 */
68ad4a33
URS
3247 if (va == NULL)
3248 goto overflow;
ca23e405 3249
5336e52c 3250 /*
d8cc323d 3251 * If required width exceeds current VA block, move
5336e52c
KS
3252 * base downwards and then recheck.
3253 */
3254 if (base + end > va->va_end) {
3255 base = pvm_determine_end_from_reverse(&va, align) - end;
3256 term_area = area;
3257 continue;
3258 }
3259
ca23e405 3260 /*
68ad4a33 3261 * If this VA does not fit, move base downwards and recheck.
ca23e405 3262 */
5336e52c 3263 if (base + start < va->va_start) {
68ad4a33
URS
3264 va = node_to_va(rb_prev(&va->rb_node));
3265 base = pvm_determine_end_from_reverse(&va, align) - end;
ca23e405
TH
3266 term_area = area;
3267 continue;
3268 }
3269
3270 /*
3271 * This area fits, move on to the previous one. If
3272 * the previous one is the terminal one, we're done.
3273 */
3274 area = (area + nr_vms - 1) % nr_vms;
3275 if (area == term_area)
3276 break;
68ad4a33 3277
ca23e405
TH
3278 start = offsets[area];
3279 end = start + sizes[area];
68ad4a33 3280 va = pvm_find_va_enclose_addr(base + end);
ca23e405 3281 }
68ad4a33 3282
ca23e405
TH
3283 /* we've found a fitting base, insert all va's */
3284 for (area = 0; area < nr_vms; area++) {
68ad4a33 3285 int ret;
ca23e405 3286
68ad4a33
URS
3287 start = base + offsets[area];
3288 size = sizes[area];
ca23e405 3289
68ad4a33
URS
3290 va = pvm_find_va_enclose_addr(start);
3291 if (WARN_ON_ONCE(va == NULL))
3292 /* It is a BUG(), but trigger recovery instead. */
3293 goto recovery;
3294
3295 type = classify_va_fit_type(va, start, size);
3296 if (WARN_ON_ONCE(type == NOTHING_FIT))
3297 /* It is a BUG(), but trigger recovery instead. */
3298 goto recovery;
3299
3300 ret = adjust_va_to_fit_type(va, start, size, type);
3301 if (unlikely(ret))
3302 goto recovery;
3303
3304 /* Allocated area. */
3305 va = vas[area];
3306 va->va_start = start;
3307 va->va_end = start + size;
68ad4a33 3308 }
ca23e405 3309
e36176be 3310 spin_unlock(&free_vmap_area_lock);
ca23e405 3311
253a496d
DA
3312 /* populate the kasan shadow space */
3313 for (area = 0; area < nr_vms; area++) {
3314 if (kasan_populate_vmalloc(vas[area]->va_start, sizes[area]))
3315 goto err_free_shadow;
3316
3317 kasan_unpoison_vmalloc((void *)vas[area]->va_start,
3318 sizes[area]);
3319 }
3320
ca23e405 3321 /* insert all vm's */
e36176be
URS
3322 spin_lock(&vmap_area_lock);
3323 for (area = 0; area < nr_vms; area++) {
3324 insert_vmap_area(vas[area], &vmap_area_root, &vmap_area_list);
3325
3326 setup_vmalloc_vm_locked(vms[area], vas[area], VM_ALLOC,
3645cb4a 3327 pcpu_get_vm_areas);
e36176be
URS
3328 }
3329 spin_unlock(&vmap_area_lock);
ca23e405
TH
3330
3331 kfree(vas);
3332 return vms;
3333
68ad4a33 3334recovery:
e36176be
URS
3335 /*
3336 * Remove previously allocated areas. There is no
3337 * need in removing these areas from the busy tree,
3338 * because they are inserted only on the final step
3339 * and when pcpu_get_vm_areas() is success.
3340 */
68ad4a33 3341 while (area--) {
253a496d
DA
3342 orig_start = vas[area]->va_start;
3343 orig_end = vas[area]->va_end;
3344 va = merge_or_add_vmap_area(vas[area], &free_vmap_area_root,
3345 &free_vmap_area_list);
3346 kasan_release_vmalloc(orig_start, orig_end,
3347 va->va_start, va->va_end);
68ad4a33
URS
3348 vas[area] = NULL;
3349 }
3350
3351overflow:
e36176be 3352 spin_unlock(&free_vmap_area_lock);
68ad4a33
URS
3353 if (!purged) {
3354 purge_vmap_area_lazy();
3355 purged = true;
3356
3357 /* Before "retry", check if we recover. */
3358 for (area = 0; area < nr_vms; area++) {
3359 if (vas[area])
3360 continue;
3361
3362 vas[area] = kmem_cache_zalloc(
3363 vmap_area_cachep, GFP_KERNEL);
3364 if (!vas[area])
3365 goto err_free;
3366 }
3367
3368 goto retry;
3369 }
3370
ca23e405
TH
3371err_free:
3372 for (area = 0; area < nr_vms; area++) {
68ad4a33
URS
3373 if (vas[area])
3374 kmem_cache_free(vmap_area_cachep, vas[area]);
3375
f1db7afd 3376 kfree(vms[area]);
ca23e405 3377 }
f1db7afd 3378err_free2:
ca23e405
TH
3379 kfree(vas);
3380 kfree(vms);
3381 return NULL;
253a496d
DA
3382
3383err_free_shadow:
3384 spin_lock(&free_vmap_area_lock);
3385 /*
3386 * We release all the vmalloc shadows, even the ones for regions that
3387 * hadn't been successfully added. This relies on kasan_release_vmalloc
3388 * being able to tolerate this case.
3389 */
3390 for (area = 0; area < nr_vms; area++) {
3391 orig_start = vas[area]->va_start;
3392 orig_end = vas[area]->va_end;
3393 va = merge_or_add_vmap_area(vas[area], &free_vmap_area_root,
3394 &free_vmap_area_list);
3395 kasan_release_vmalloc(orig_start, orig_end,
3396 va->va_start, va->va_end);
3397 vas[area] = NULL;
3398 kfree(vms[area]);
3399 }
3400 spin_unlock(&free_vmap_area_lock);
3401 kfree(vas);
3402 kfree(vms);
3403 return NULL;
ca23e405
TH
3404}
3405
3406/**
3407 * pcpu_free_vm_areas - free vmalloc areas for percpu allocator
3408 * @vms: vm_struct pointer array returned by pcpu_get_vm_areas()
3409 * @nr_vms: the number of allocated areas
3410 *
3411 * Free vm_structs and the array allocated by pcpu_get_vm_areas().
3412 */
3413void pcpu_free_vm_areas(struct vm_struct **vms, int nr_vms)
3414{
3415 int i;
3416
3417 for (i = 0; i < nr_vms; i++)
3418 free_vm_area(vms[i]);
3419 kfree(vms);
3420}
4f8b02b4 3421#endif /* CONFIG_SMP */
a10aa579
CL
3422
3423#ifdef CONFIG_PROC_FS
3424static void *s_start(struct seq_file *m, loff_t *pos)
e36176be 3425 __acquires(&vmap_purge_lock)
d4033afd 3426 __acquires(&vmap_area_lock)
a10aa579 3427{
e36176be 3428 mutex_lock(&vmap_purge_lock);
d4033afd 3429 spin_lock(&vmap_area_lock);
e36176be 3430
3f500069 3431 return seq_list_start(&vmap_area_list, *pos);
a10aa579
CL
3432}
3433
3434static void *s_next(struct seq_file *m, void *p, loff_t *pos)
3435{
3f500069 3436 return seq_list_next(p, &vmap_area_list, pos);
a10aa579
CL
3437}
3438
3439static void s_stop(struct seq_file *m, void *p)
e36176be 3440 __releases(&vmap_purge_lock)
d4033afd 3441 __releases(&vmap_area_lock)
a10aa579 3442{
e36176be 3443 mutex_unlock(&vmap_purge_lock);
d4033afd 3444 spin_unlock(&vmap_area_lock);
a10aa579
CL
3445}
3446
a47a126a
ED
3447static void show_numa_info(struct seq_file *m, struct vm_struct *v)
3448{
e5adfffc 3449 if (IS_ENABLED(CONFIG_NUMA)) {
a47a126a
ED
3450 unsigned int nr, *counters = m->private;
3451
3452 if (!counters)
3453 return;
3454
af12346c
WL
3455 if (v->flags & VM_UNINITIALIZED)
3456 return;
7e5b528b
DV
3457 /* Pair with smp_wmb() in clear_vm_uninitialized_flag() */
3458 smp_rmb();
af12346c 3459
a47a126a
ED
3460 memset(counters, 0, nr_node_ids * sizeof(unsigned int));
3461
3462 for (nr = 0; nr < v->nr_pages; nr++)
3463 counters[page_to_nid(v->pages[nr])]++;
3464
3465 for_each_node_state(nr, N_HIGH_MEMORY)
3466 if (counters[nr])
3467 seq_printf(m, " N%u=%u", nr, counters[nr]);
3468 }
3469}
3470
dd3b8353
URS
3471static void show_purge_info(struct seq_file *m)
3472{
3473 struct llist_node *head;
3474 struct vmap_area *va;
3475
3476 head = READ_ONCE(vmap_purge_list.first);
3477 if (head == NULL)
3478 return;
3479
3480 llist_for_each_entry(va, head, purge_list) {
3481 seq_printf(m, "0x%pK-0x%pK %7ld unpurged vm_area\n",
3482 (void *)va->va_start, (void *)va->va_end,
3483 va->va_end - va->va_start);
3484 }
3485}
3486
a10aa579
CL
3487static int s_show(struct seq_file *m, void *p)
3488{
3f500069 3489 struct vmap_area *va;
d4033afd
JK
3490 struct vm_struct *v;
3491
3f500069 3492 va = list_entry(p, struct vmap_area, list);
3493
c2ce8c14 3494 /*
688fcbfc
PL
3495 * s_show can encounter race with remove_vm_area, !vm on behalf
3496 * of vmap area is being tear down or vm_map_ram allocation.
c2ce8c14 3497 */
688fcbfc 3498 if (!va->vm) {
dd3b8353 3499 seq_printf(m, "0x%pK-0x%pK %7ld vm_map_ram\n",
78c72746 3500 (void *)va->va_start, (void *)va->va_end,
dd3b8353 3501 va->va_end - va->va_start);
78c72746 3502
d4033afd 3503 return 0;
78c72746 3504 }
d4033afd
JK
3505
3506 v = va->vm;
a10aa579 3507
45ec1690 3508 seq_printf(m, "0x%pK-0x%pK %7ld",
a10aa579
CL
3509 v->addr, v->addr + v->size, v->size);
3510
62c70bce
JP
3511 if (v->caller)
3512 seq_printf(m, " %pS", v->caller);
23016969 3513
a10aa579
CL
3514 if (v->nr_pages)
3515 seq_printf(m, " pages=%d", v->nr_pages);
3516
3517 if (v->phys_addr)
199eaa05 3518 seq_printf(m, " phys=%pa", &v->phys_addr);
a10aa579
CL
3519
3520 if (v->flags & VM_IOREMAP)
f4527c90 3521 seq_puts(m, " ioremap");
a10aa579
CL
3522
3523 if (v->flags & VM_ALLOC)
f4527c90 3524 seq_puts(m, " vmalloc");
a10aa579
CL
3525
3526 if (v->flags & VM_MAP)
f4527c90 3527 seq_puts(m, " vmap");
a10aa579
CL
3528
3529 if (v->flags & VM_USERMAP)
f4527c90 3530 seq_puts(m, " user");
a10aa579 3531
fe9041c2
CH
3532 if (v->flags & VM_DMA_COHERENT)
3533 seq_puts(m, " dma-coherent");
3534
244d63ee 3535 if (is_vmalloc_addr(v->pages))
f4527c90 3536 seq_puts(m, " vpages");
a10aa579 3537
a47a126a 3538 show_numa_info(m, v);
a10aa579 3539 seq_putc(m, '\n');
dd3b8353
URS
3540
3541 /*
3542 * As a final step, dump "unpurged" areas. Note,
3543 * that entire "/proc/vmallocinfo" output will not
3544 * be address sorted, because the purge list is not
3545 * sorted.
3546 */
3547 if (list_is_last(&va->list, &vmap_area_list))
3548 show_purge_info(m);
3549
a10aa579
CL
3550 return 0;
3551}
3552
5f6a6a9c 3553static const struct seq_operations vmalloc_op = {
a10aa579
CL
3554 .start = s_start,
3555 .next = s_next,
3556 .stop = s_stop,
3557 .show = s_show,
3558};
5f6a6a9c 3559
5f6a6a9c
AD
3560static int __init proc_vmalloc_init(void)
3561{
fddda2b7 3562 if (IS_ENABLED(CONFIG_NUMA))
0825a6f9 3563 proc_create_seq_private("vmallocinfo", 0400, NULL,
44414d82
CH
3564 &vmalloc_op,
3565 nr_node_ids * sizeof(unsigned int), NULL);
fddda2b7 3566 else
0825a6f9 3567 proc_create_seq("vmallocinfo", 0400, NULL, &vmalloc_op);
5f6a6a9c
AD
3568 return 0;
3569}
3570module_init(proc_vmalloc_init);
db3808c1 3571
a10aa579 3572#endif