1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Copyright (C) 1993 Linus Torvalds
4 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
5 * SMP-safe vmalloc/vfree/ioremap, Tigran Aivazian <tigran@veritas.com>, May 2000
6 * Major rework to support vmap/vunmap, Christoph Hellwig, SGI, August 2002
7 * Numa awareness, Christoph Lameter, SGI, June 2005
8 * Improving global KVA allocator, Uladzislau Rezki, Sony, May 2019
9 */
10
11 #include <linux/vmalloc.h>
12 #include <linux/mm.h>
13 #include <linux/module.h>
14 #include <linux/highmem.h>
15 #include <linux/sched/signal.h>
16 #include <linux/slab.h>
17 #include <linux/spinlock.h>
18 #include <linux/interrupt.h>
19 #include <linux/proc_fs.h>
20 #include <linux/seq_file.h>
21 #include <linux/set_memory.h>
22 #include <linux/debugobjects.h>
23 #include <linux/kallsyms.h>
24 #include <linux/list.h>
25 #include <linux/notifier.h>
26 #include <linux/rbtree.h>
27 #include <linux/xarray.h>
28 #include <linux/io.h>
29 #include <linux/rcupdate.h>
30 #include <linux/pfn.h>
31 #include <linux/kmemleak.h>
32 #include <linux/atomic.h>
33 #include <linux/compiler.h>
34 #include <linux/memcontrol.h>
35 #include <linux/llist.h>
36 #include <linux/uio.h>
37 #include <linux/bitops.h>
38 #include <linux/rbtree_augmented.h>
39 #include <linux/overflow.h>
40 #include <linux/pgtable.h>
41 #include <linux/hugetlb.h>
42 #include <linux/io.h>
43 #include <linux/sched/mm.h>
44 #include <asm/tlbflush.h>
45 #include <asm/shmparam.h>
46
47 #define CREATE_TRACE_POINTS
48 #include <trace/events/vmalloc.h>
49
50 #undef CREATE_TRACE_POINTS
51 #include <trace/hooks/mm.h>
52
53 #include "internal.h"
54 #include "pgalloc-track.h"
55
56 #ifdef CONFIG_HAVE_ARCH_HUGE_VMAP
57 static unsigned int __ro_after_init ioremap_max_page_shift = BITS_PER_LONG - 1;
58
set_nohugeiomap(char * str)59 static int __init set_nohugeiomap(char *str)
60 {
61 ioremap_max_page_shift = PAGE_SHIFT;
62 return 0;
63 }
64 early_param("nohugeiomap", set_nohugeiomap);
65 #else /* CONFIG_HAVE_ARCH_HUGE_VMAP */
66 static const unsigned int ioremap_max_page_shift = PAGE_SHIFT;
67 #endif /* CONFIG_HAVE_ARCH_HUGE_VMAP */
68
69 #ifdef CONFIG_HAVE_ARCH_HUGE_VMALLOC
70 static bool __ro_after_init vmap_allow_huge = true;
71
set_nohugevmalloc(char * str)72 static int __init set_nohugevmalloc(char *str)
73 {
74 vmap_allow_huge = false;
75 return 0;
76 }
77 early_param("nohugevmalloc", set_nohugevmalloc);
78 #else /* CONFIG_HAVE_ARCH_HUGE_VMALLOC */
79 static const bool vmap_allow_huge = false;
80 #endif /* CONFIG_HAVE_ARCH_HUGE_VMALLOC */
81
is_vmalloc_addr(const void * x)82 bool is_vmalloc_addr(const void *x)
83 {
84 unsigned long addr = (unsigned long)kasan_reset_tag(x);
85
86 return addr >= VMALLOC_START && addr < VMALLOC_END;
87 }
88 EXPORT_SYMBOL(is_vmalloc_addr);
89
90 struct vfree_deferred {
91 struct llist_head list;
92 struct work_struct wq;
93 };
94 static DEFINE_PER_CPU(struct vfree_deferred, vfree_deferred);
95
96 /*** Page table manipulation functions ***/
vmap_pte_range(pmd_t * pmd,unsigned long addr,unsigned long end,phys_addr_t phys_addr,pgprot_t prot,unsigned int max_page_shift,pgtbl_mod_mask * mask)97 static int vmap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
98 phys_addr_t phys_addr, pgprot_t prot,
99 unsigned int max_page_shift, pgtbl_mod_mask *mask)
100 {
101 pte_t *pte;
102 u64 pfn;
103 unsigned long size = PAGE_SIZE;
104
105 pfn = phys_addr >> PAGE_SHIFT;
106 pte = pte_alloc_kernel_track(pmd, addr, mask);
107 if (!pte)
108 return -ENOMEM;
109 do {
110 BUG_ON(!pte_none(ptep_get(pte)));
111
112 #ifdef CONFIG_HUGETLB_PAGE
113 size = arch_vmap_pte_range_map_size(addr, end, pfn, max_page_shift);
114 if (size != PAGE_SIZE) {
115 pte_t entry = pfn_pte(pfn, prot);
116
117 entry = arch_make_huge_pte(entry, ilog2(size), 0);
118 set_huge_pte_at(&init_mm, addr, pte, entry, size);
119 pfn += PFN_DOWN(size);
120 continue;
121 }
122 #endif
123 set_pte_at(&init_mm, addr, pte, pfn_pte(pfn, prot));
124 pfn++;
125 } while (pte += PFN_DOWN(size), addr += size, addr != end);
126 *mask |= PGTBL_PTE_MODIFIED;
127 return 0;
128 }
129
vmap_try_huge_pmd(pmd_t * pmd,unsigned long addr,unsigned long end,phys_addr_t phys_addr,pgprot_t prot,unsigned int max_page_shift)130 static int vmap_try_huge_pmd(pmd_t *pmd, unsigned long addr, unsigned long end,
131 phys_addr_t phys_addr, pgprot_t prot,
132 unsigned int max_page_shift)
133 {
134 if (max_page_shift < PMD_SHIFT)
135 return 0;
136
137 if (!arch_vmap_pmd_supported(prot))
138 return 0;
139
140 if ((end - addr) != PMD_SIZE)
141 return 0;
142
143 if (!IS_ALIGNED(addr, PMD_SIZE))
144 return 0;
145
146 if (!IS_ALIGNED(phys_addr, PMD_SIZE))
147 return 0;
148
149 if (pmd_present(*pmd) && !pmd_free_pte_page(pmd, addr))
150 return 0;
151
152 return pmd_set_huge(pmd, phys_addr, prot);
153 }
154
vmap_pmd_range(pud_t * pud,unsigned long addr,unsigned long end,phys_addr_t phys_addr,pgprot_t prot,unsigned int max_page_shift,pgtbl_mod_mask * mask)155 static int vmap_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,
156 phys_addr_t phys_addr, pgprot_t prot,
157 unsigned int max_page_shift, pgtbl_mod_mask *mask)
158 {
159 pmd_t *pmd;
160 unsigned long next;
161
162 pmd = pmd_alloc_track(&init_mm, pud, addr, mask);
163 if (!pmd)
164 return -ENOMEM;
165 do {
166 next = pmd_addr_end(addr, end);
167
168 if (vmap_try_huge_pmd(pmd, addr, next, phys_addr, prot,
169 max_page_shift)) {
170 *mask |= PGTBL_PMD_MODIFIED;
171 continue;
172 }
173
174 if (vmap_pte_range(pmd, addr, next, phys_addr, prot, max_page_shift, mask))
175 return -ENOMEM;
176 } while (pmd++, phys_addr += (next - addr), addr = next, addr != end);
177 return 0;
178 }
179
vmap_try_huge_pud(pud_t * pud,unsigned long addr,unsigned long end,phys_addr_t phys_addr,pgprot_t prot,unsigned int max_page_shift)180 static int vmap_try_huge_pud(pud_t *pud, unsigned long addr, unsigned long end,
181 phys_addr_t phys_addr, pgprot_t prot,
182 unsigned int max_page_shift)
183 {
184 if (max_page_shift < PUD_SHIFT)
185 return 0;
186
187 if (!arch_vmap_pud_supported(prot))
188 return 0;
189
190 if ((end - addr) != PUD_SIZE)
191 return 0;
192
193 if (!IS_ALIGNED(addr, PUD_SIZE))
194 return 0;
195
196 if (!IS_ALIGNED(phys_addr, PUD_SIZE))
197 return 0;
198
199 if (pud_present(*pud) && !pud_free_pmd_page(pud, addr))
200 return 0;
201
202 return pud_set_huge(pud, phys_addr, prot);
203 }
204
vmap_pud_range(p4d_t * p4d,unsigned long addr,unsigned long end,phys_addr_t phys_addr,pgprot_t prot,unsigned int max_page_shift,pgtbl_mod_mask * mask)205 static int vmap_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end,
206 phys_addr_t phys_addr, pgprot_t prot,
207 unsigned int max_page_shift, pgtbl_mod_mask *mask)
208 {
209 pud_t *pud;
210 unsigned long next;
211
212 pud = pud_alloc_track(&init_mm, p4d, addr, mask);
213 if (!pud)
214 return -ENOMEM;
215 do {
216 next = pud_addr_end(addr, end);
217
218 if (vmap_try_huge_pud(pud, addr, next, phys_addr, prot,
219 max_page_shift)) {
220 *mask |= PGTBL_PUD_MODIFIED;
221 continue;
222 }
223
224 if (vmap_pmd_range(pud, addr, next, phys_addr, prot,
225 max_page_shift, mask))
226 return -ENOMEM;
227 } while (pud++, phys_addr += (next - addr), addr = next, addr != end);
228 return 0;
229 }
230
vmap_try_huge_p4d(p4d_t * p4d,unsigned long addr,unsigned long end,phys_addr_t phys_addr,pgprot_t prot,unsigned int max_page_shift)231 static int vmap_try_huge_p4d(p4d_t *p4d, unsigned long addr, unsigned long end,
232 phys_addr_t phys_addr, pgprot_t prot,
233 unsigned int max_page_shift)
234 {
235 if (max_page_shift < P4D_SHIFT)
236 return 0;
237
238 if (!arch_vmap_p4d_supported(prot))
239 return 0;
240
241 if ((end - addr) != P4D_SIZE)
242 return 0;
243
244 if (!IS_ALIGNED(addr, P4D_SIZE))
245 return 0;
246
247 if (!IS_ALIGNED(phys_addr, P4D_SIZE))
248 return 0;
249
250 if (p4d_present(*p4d) && !p4d_free_pud_page(p4d, addr))
251 return 0;
252
253 return p4d_set_huge(p4d, phys_addr, prot);
254 }
255
vmap_p4d_range(pgd_t * pgd,unsigned long addr,unsigned long end,phys_addr_t phys_addr,pgprot_t prot,unsigned int max_page_shift,pgtbl_mod_mask * mask)256 static int vmap_p4d_range(pgd_t *pgd, unsigned long addr, unsigned long end,
257 phys_addr_t phys_addr, pgprot_t prot,
258 unsigned int max_page_shift, pgtbl_mod_mask *mask)
259 {
260 p4d_t *p4d;
261 unsigned long next;
262
263 p4d = p4d_alloc_track(&init_mm, pgd, addr, mask);
264 if (!p4d)
265 return -ENOMEM;
266 do {
267 next = p4d_addr_end(addr, end);
268
269 if (vmap_try_huge_p4d(p4d, addr, next, phys_addr, prot,
270 max_page_shift)) {
271 *mask |= PGTBL_P4D_MODIFIED;
272 continue;
273 }
274
275 if (vmap_pud_range(p4d, addr, next, phys_addr, prot,
276 max_page_shift, mask))
277 return -ENOMEM;
278 } while (p4d++, phys_addr += (next - addr), addr = next, addr != end);
279 return 0;
280 }
281
vmap_range_noflush(unsigned long addr,unsigned long end,phys_addr_t phys_addr,pgprot_t prot,unsigned int max_page_shift)282 static int vmap_range_noflush(unsigned long addr, unsigned long end,
283 phys_addr_t phys_addr, pgprot_t prot,
284 unsigned int max_page_shift)
285 {
286 pgd_t *pgd;
287 unsigned long start;
288 unsigned long next;
289 int err;
290 pgtbl_mod_mask mask = 0;
291
292 might_sleep();
293 BUG_ON(addr >= end);
294
295 start = addr;
296 pgd = pgd_offset_k(addr);
297 do {
298 next = pgd_addr_end(addr, end);
299 err = vmap_p4d_range(pgd, addr, next, phys_addr, prot,
300 max_page_shift, &mask);
301 if (err)
302 break;
303 } while (pgd++, phys_addr += (next - addr), addr = next, addr != end);
304
305 if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
306 arch_sync_kernel_mappings(start, end);
307
308 return err;
309 }
310
ioremap_page_range(unsigned long addr,unsigned long end,phys_addr_t phys_addr,pgprot_t prot)311 int ioremap_page_range(unsigned long addr, unsigned long end,
312 phys_addr_t phys_addr, pgprot_t prot)
313 {
314 int err;
315
316 prot = pgprot_nx(prot);
317 err = vmap_range_noflush(addr, end, phys_addr, prot,
318 ioremap_max_page_shift);
319 flush_cache_vmap(addr, end);
320 if (!err)
321 err = kmsan_ioremap_page_range(addr, end, phys_addr, prot,
322 ioremap_max_page_shift);
323
324 if (IS_ENABLED(CONFIG_ARCH_HAS_IOREMAP_PHYS_HOOKS) && !err)
325 ioremap_phys_range_hook(phys_addr, end - addr, prot);
326
327 return err;
328 }
329
vunmap_pte_range(pmd_t * pmd,unsigned long addr,unsigned long end,pgtbl_mod_mask * mask)330 static void vunmap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
331 pgtbl_mod_mask *mask)
332 {
333 pte_t *pte;
334
335 pte = pte_offset_kernel(pmd, addr);
336 do {
337 pte_t ptent = ptep_get_and_clear(&init_mm, addr, pte);
338 WARN_ON(!pte_none(ptent) && !pte_present(ptent));
339 } while (pte++, addr += PAGE_SIZE, addr != end);
340 *mask |= PGTBL_PTE_MODIFIED;
341 }
342
vunmap_pmd_range(pud_t * pud,unsigned long addr,unsigned long end,pgtbl_mod_mask * mask)343 static void vunmap_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,
344 pgtbl_mod_mask *mask)
345 {
346 pmd_t *pmd;
347 unsigned long next;
348 int cleared;
349
350 pmd = pmd_offset(pud, addr);
351 do {
352 next = pmd_addr_end(addr, end);
353
354 cleared = pmd_clear_huge(pmd);
355 if (cleared || pmd_bad(*pmd))
356 *mask |= PGTBL_PMD_MODIFIED;
357
358 if (cleared)
359 continue;
360 if (pmd_none_or_clear_bad(pmd))
361 continue;
362 vunmap_pte_range(pmd, addr, next, mask);
363
364 cond_resched();
365 } while (pmd++, addr = next, addr != end);
366 }
367
vunmap_pud_range(p4d_t * p4d,unsigned long addr,unsigned long end,pgtbl_mod_mask * mask)368 static void vunmap_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end,
369 pgtbl_mod_mask *mask)
370 {
371 pud_t *pud;
372 unsigned long next;
373 int cleared;
374
375 pud = pud_offset(p4d, addr);
376 do {
377 next = pud_addr_end(addr, end);
378
379 cleared = pud_clear_huge(pud);
380 if (cleared || pud_bad(*pud))
381 *mask |= PGTBL_PUD_MODIFIED;
382
383 if (cleared)
384 continue;
385 if (pud_none_or_clear_bad(pud))
386 continue;
387 vunmap_pmd_range(pud, addr, next, mask);
388 } while (pud++, addr = next, addr != end);
389 }
390
vunmap_p4d_range(pgd_t * pgd,unsigned long addr,unsigned long end,pgtbl_mod_mask * mask)391 static void vunmap_p4d_range(pgd_t *pgd, unsigned long addr, unsigned long end,
392 pgtbl_mod_mask *mask)
393 {
394 p4d_t *p4d;
395 unsigned long next;
396
397 p4d = p4d_offset(pgd, addr);
398 do {
399 next = p4d_addr_end(addr, end);
400
401 p4d_clear_huge(p4d);
402 if (p4d_bad(*p4d))
403 *mask |= PGTBL_P4D_MODIFIED;
404
405 if (p4d_none_or_clear_bad(p4d))
406 continue;
407 vunmap_pud_range(p4d, addr, next, mask);
408 } while (p4d++, addr = next, addr != end);
409 }
410
411 /*
412 * vunmap_range_noflush is similar to vunmap_range, but does not
413 * flush caches or TLBs.
414 *
415 * The caller is responsible for calling flush_cache_vmap() before calling
416 * this function, and flush_tlb_kernel_range after it has returned
417 * successfully (and before the addresses are expected to cause a page fault
418 * or be re-mapped for something else, if TLB flushes are being delayed or
419 * coalesced).
420 *
421 * This is an internal function only. Do not use outside mm/.
422 */
__vunmap_range_noflush(unsigned long start,unsigned long end)423 void __vunmap_range_noflush(unsigned long start, unsigned long end)
424 {
425 unsigned long next;
426 pgd_t *pgd;
427 unsigned long addr = start;
428 pgtbl_mod_mask mask = 0;
429
430 BUG_ON(addr >= end);
431 pgd = pgd_offset_k(addr);
432 do {
433 next = pgd_addr_end(addr, end);
434 if (pgd_bad(*pgd))
435 mask |= PGTBL_PGD_MODIFIED;
436 if (pgd_none_or_clear_bad(pgd))
437 continue;
438 vunmap_p4d_range(pgd, addr, next, &mask);
439 } while (pgd++, addr = next, addr != end);
440
441 if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
442 arch_sync_kernel_mappings(start, end);
443 }
444
vunmap_range_noflush(unsigned long start,unsigned long end)445 void vunmap_range_noflush(unsigned long start, unsigned long end)
446 {
447 kmsan_vunmap_range_noflush(start, end);
448 __vunmap_range_noflush(start, end);
449 }
450
451 /**
452 * vunmap_range - unmap kernel virtual addresses
453 * @addr: start of the VM area to unmap
454 * @end: end of the VM area to unmap (non-inclusive)
455 *
456 * Clears any present PTEs in the virtual address range, flushes TLBs and
457 * caches. Any subsequent access to the address before it has been re-mapped
458 * is a kernel bug.
459 */
vunmap_range(unsigned long addr,unsigned long end)460 void vunmap_range(unsigned long addr, unsigned long end)
461 {
462 flush_cache_vunmap(addr, end);
463 vunmap_range_noflush(addr, end);
464 flush_tlb_kernel_range(addr, end);
465 }
466
vmap_pages_pte_range(pmd_t * pmd,unsigned long addr,unsigned long end,pgprot_t prot,struct page ** pages,int * nr,pgtbl_mod_mask * mask)467 static int vmap_pages_pte_range(pmd_t *pmd, unsigned long addr,
468 unsigned long end, pgprot_t prot, struct page **pages, int *nr,
469 pgtbl_mod_mask *mask)
470 {
471 pte_t *pte;
472
473 /*
474 * nr is a running index into the array which helps higher level
475 * callers keep track of where we're up to.
476 */
477
478 pte = pte_alloc_kernel_track(pmd, addr, mask);
479 if (!pte)
480 return -ENOMEM;
481 do {
482 struct page *page = pages[*nr];
483
484 if (WARN_ON(!pte_none(ptep_get(pte))))
485 return -EBUSY;
486 if (WARN_ON(!page))
487 return -ENOMEM;
488 if (WARN_ON(!pfn_valid(page_to_pfn(page))))
489 return -EINVAL;
490
491 set_pte_at(&init_mm, addr, pte, mk_pte(page, prot));
492 (*nr)++;
493 } while (pte++, addr += PAGE_SIZE, addr != end);
494 *mask |= PGTBL_PTE_MODIFIED;
495 return 0;
496 }
497
vmap_pages_pmd_range(pud_t * pud,unsigned long addr,unsigned long end,pgprot_t prot,struct page ** pages,int * nr,pgtbl_mod_mask * mask)498 static int vmap_pages_pmd_range(pud_t *pud, unsigned long addr,
499 unsigned long end, pgprot_t prot, struct page **pages, int *nr,
500 pgtbl_mod_mask *mask)
501 {
502 pmd_t *pmd;
503 unsigned long next;
504
505 pmd = pmd_alloc_track(&init_mm, pud, addr, mask);
506 if (!pmd)
507 return -ENOMEM;
508 do {
509 next = pmd_addr_end(addr, end);
510 if (vmap_pages_pte_range(pmd, addr, next, prot, pages, nr, mask))
511 return -ENOMEM;
512 } while (pmd++, addr = next, addr != end);
513 return 0;
514 }
515
vmap_pages_pud_range(p4d_t * p4d,unsigned long addr,unsigned long end,pgprot_t prot,struct page ** pages,int * nr,pgtbl_mod_mask * mask)516 static int vmap_pages_pud_range(p4d_t *p4d, unsigned long addr,
517 unsigned long end, pgprot_t prot, struct page **pages, int *nr,
518 pgtbl_mod_mask *mask)
519 {
520 pud_t *pud;
521 unsigned long next;
522
523 pud = pud_alloc_track(&init_mm, p4d, addr, mask);
524 if (!pud)
525 return -ENOMEM;
526 do {
527 next = pud_addr_end(addr, end);
528 if (vmap_pages_pmd_range(pud, addr, next, prot, pages, nr, mask))
529 return -ENOMEM;
530 } while (pud++, addr = next, addr != end);
531 return 0;
532 }
533
vmap_pages_p4d_range(pgd_t * pgd,unsigned long addr,unsigned long end,pgprot_t prot,struct page ** pages,int * nr,pgtbl_mod_mask * mask)534 static int vmap_pages_p4d_range(pgd_t *pgd, unsigned long addr,
535 unsigned long end, pgprot_t prot, struct page **pages, int *nr,
536 pgtbl_mod_mask *mask)
537 {
538 p4d_t *p4d;
539 unsigned long next;
540
541 p4d = p4d_alloc_track(&init_mm, pgd, addr, mask);
542 if (!p4d)
543 return -ENOMEM;
544 do {
545 next = p4d_addr_end(addr, end);
546 if (vmap_pages_pud_range(p4d, addr, next, prot, pages, nr, mask))
547 return -ENOMEM;
548 } while (p4d++, addr = next, addr != end);
549 return 0;
550 }
551
vmap_small_pages_range_noflush(unsigned long addr,unsigned long end,pgprot_t prot,struct page ** pages)552 static int vmap_small_pages_range_noflush(unsigned long addr, unsigned long end,
553 pgprot_t prot, struct page **pages)
554 {
555 unsigned long start = addr;
556 pgd_t *pgd;
557 unsigned long next;
558 int err = 0;
559 int nr = 0;
560 pgtbl_mod_mask mask = 0;
561
562 BUG_ON(addr >= end);
563 pgd = pgd_offset_k(addr);
564 do {
565 next = pgd_addr_end(addr, end);
566 if (pgd_bad(*pgd))
567 mask |= PGTBL_PGD_MODIFIED;
568 err = vmap_pages_p4d_range(pgd, addr, next, prot, pages, &nr, &mask);
569 if (err)
570 return err;
571 } while (pgd++, addr = next, addr != end);
572
573 if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
574 arch_sync_kernel_mappings(start, end);
575
576 return 0;
577 }
578
579 /*
580 * vmap_pages_range_noflush is similar to vmap_pages_range, but does not
581 * flush caches.
582 *
583 * The caller is responsible for calling flush_cache_vmap() after this
584 * function returns successfully and before the addresses are accessed.
585 *
586 * This is an internal function only. Do not use outside mm/.
587 */
__vmap_pages_range_noflush(unsigned long addr,unsigned long end,pgprot_t prot,struct page ** pages,unsigned int page_shift)588 int __vmap_pages_range_noflush(unsigned long addr, unsigned long end,
589 pgprot_t prot, struct page **pages, unsigned int page_shift)
590 {
591 unsigned int i, nr = (end - addr) >> PAGE_SHIFT;
592
593 WARN_ON(page_shift < PAGE_SHIFT);
594
595 if (!IS_ENABLED(CONFIG_HAVE_ARCH_HUGE_VMALLOC) ||
596 page_shift == PAGE_SHIFT)
597 return vmap_small_pages_range_noflush(addr, end, prot, pages);
598
599 for (i = 0; i < nr; i += 1U << (page_shift - PAGE_SHIFT)) {
600 int err;
601
602 err = vmap_range_noflush(addr, addr + (1UL << page_shift),
603 page_to_phys(pages[i]), prot,
604 page_shift);
605 if (err)
606 return err;
607
608 addr += 1UL << page_shift;
609 }
610
611 return 0;
612 }
613
vmap_pages_range_noflush(unsigned long addr,unsigned long end,pgprot_t prot,struct page ** pages,unsigned int page_shift)614 int vmap_pages_range_noflush(unsigned long addr, unsigned long end,
615 pgprot_t prot, struct page **pages, unsigned int page_shift)
616 {
617 int ret = kmsan_vmap_pages_range_noflush(addr, end, prot, pages,
618 page_shift);
619
620 if (ret)
621 return ret;
622 return __vmap_pages_range_noflush(addr, end, prot, pages, page_shift);
623 }
624
625 /**
626 * vmap_pages_range - map pages to a kernel virtual address
627 * @addr: start of the VM area to map
628 * @end: end of the VM area to map (non-inclusive)
629 * @prot: page protection flags to use
630 * @pages: pages to map (always PAGE_SIZE pages)
631 * @page_shift: maximum shift that the pages may be mapped with, @pages must
632 * be aligned and contiguous up to at least this shift.
633 *
634 * RETURNS:
635 * 0 on success, -errno on failure.
636 */
vmap_pages_range(unsigned long addr,unsigned long end,pgprot_t prot,struct page ** pages,unsigned int page_shift)637 static int vmap_pages_range(unsigned long addr, unsigned long end,
638 pgprot_t prot, struct page **pages, unsigned int page_shift)
639 {
640 int err;
641
642 err = vmap_pages_range_noflush(addr, end, prot, pages, page_shift);
643 flush_cache_vmap(addr, end);
644 return err;
645 }
646
is_vmalloc_or_module_addr(const void * x)647 int is_vmalloc_or_module_addr(const void *x)
648 {
649 /*
650 * ARM, x86-64 and sparc64 put modules in a special place,
651 * and fall back on vmalloc() if that fails. Others
652 * just put it in the vmalloc space.
653 */
654 #if defined(CONFIG_MODULES) && defined(MODULES_VADDR)
655 unsigned long addr = (unsigned long)kasan_reset_tag(x);
656 if (addr >= MODULES_VADDR && addr < MODULES_END)
657 return 1;
658 #endif
659 return is_vmalloc_addr(x);
660 }
661 EXPORT_SYMBOL_GPL(is_vmalloc_or_module_addr);
662
663 /*
664 * Walk a vmap address to the struct page it maps. Huge vmap mappings will
665 * return the tail page that corresponds to the base page address, which
666 * matches small vmap mappings.
667 */
vmalloc_to_page(const void * vmalloc_addr)668 struct page *vmalloc_to_page(const void *vmalloc_addr)
669 {
670 unsigned long addr = (unsigned long) vmalloc_addr;
671 struct page *page = NULL;
672 pgd_t *pgd = pgd_offset_k(addr);
673 p4d_t *p4d;
674 pud_t *pud;
675 pmd_t *pmd;
676 pte_t *ptep, pte;
677
678 /*
679 * XXX we might need to change this if we add VIRTUAL_BUG_ON for
680 * architectures that do not vmalloc module space
681 */
682 VIRTUAL_BUG_ON(!is_vmalloc_or_module_addr(vmalloc_addr));
683
684 if (pgd_none(*pgd))
685 return NULL;
686 if (WARN_ON_ONCE(pgd_leaf(*pgd)))
687 return NULL; /* XXX: no allowance for huge pgd */
688 if (WARN_ON_ONCE(pgd_bad(*pgd)))
689 return NULL;
690
691 p4d = p4d_offset(pgd, addr);
692 if (p4d_none(*p4d))
693 return NULL;
694 if (p4d_leaf(*p4d))
695 return p4d_page(*p4d) + ((addr & ~P4D_MASK) >> PAGE_SHIFT);
696 if (WARN_ON_ONCE(p4d_bad(*p4d)))
697 return NULL;
698
699 pud = pud_offset(p4d, addr);
700 if (pud_none(*pud))
701 return NULL;
702 if (pud_leaf(*pud))
703 return pud_page(*pud) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
704 if (WARN_ON_ONCE(pud_bad(*pud)))
705 return NULL;
706
707 pmd = pmd_offset(pud, addr);
708 if (pmd_none(*pmd))
709 return NULL;
710 if (pmd_leaf(*pmd))
711 return pmd_page(*pmd) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
712 if (WARN_ON_ONCE(pmd_bad(*pmd)))
713 return NULL;
714
715 ptep = pte_offset_kernel(pmd, addr);
716 pte = ptep_get(ptep);
717 if (pte_present(pte))
718 page = pte_page(pte);
719
720 return page;
721 }
722 EXPORT_SYMBOL(vmalloc_to_page);
723
724 /*
725 * Map a vmalloc()-space virtual address to the physical page frame number.
726 */
vmalloc_to_pfn(const void * vmalloc_addr)727 unsigned long vmalloc_to_pfn(const void *vmalloc_addr)
728 {
729 return page_to_pfn(vmalloc_to_page(vmalloc_addr));
730 }
731 EXPORT_SYMBOL(vmalloc_to_pfn);
732
733
734 /*** Global kva allocator ***/
735
736 #define DEBUG_AUGMENT_PROPAGATE_CHECK 0
737 #define DEBUG_AUGMENT_LOWEST_MATCH_CHECK 0
738
739
740 static DEFINE_SPINLOCK(vmap_area_lock);
741 static DEFINE_SPINLOCK(free_vmap_area_lock);
742 /* Export for kexec only */
743 LIST_HEAD(vmap_area_list);
744 static struct rb_root vmap_area_root = RB_ROOT;
745 static bool vmap_initialized __read_mostly;
746
747 static struct rb_root purge_vmap_area_root = RB_ROOT;
748 static LIST_HEAD(purge_vmap_area_list);
749 static DEFINE_SPINLOCK(purge_vmap_area_lock);
750
751 /*
752 * This kmem_cache is used for vmap_area objects. Instead of
753 * allocating from slab we reuse an object from this cache to
754 * make things faster. Especially in "no edge" splitting of
755 * free block.
756 */
757 static struct kmem_cache *vmap_area_cachep;
758
759 /*
760 * This linked list is used in pair with free_vmap_area_root.
761 * It gives O(1) access to prev/next to perform fast coalescing.
762 */
763 static LIST_HEAD(free_vmap_area_list);
764
765 /*
766 * This augment red-black tree represents the free vmap space.
767 * All vmap_area objects in this tree are sorted by va->va_start
768 * address. It is used for allocation and merging when a vmap
769 * object is released.
770 *
771 * Each vmap_area node contains a maximum available free block
772 * of its sub-tree, right or left. Therefore it is possible to
773 * find a lowest match of free area.
774 */
775 static struct rb_root free_vmap_area_root = RB_ROOT;
776
777 /*
778 * Preload a CPU with one object for "no edge" split case. The
779 * aim is to get rid of allocations from the atomic context, thus
780 * to use more permissive allocation masks.
781 */
782 static DEFINE_PER_CPU(struct vmap_area *, ne_fit_preload_node);
783
784 static __always_inline unsigned long
va_size(struct vmap_area * va)785 va_size(struct vmap_area *va)
786 {
787 return (va->va_end - va->va_start);
788 }
789
790 static __always_inline unsigned long
get_subtree_max_size(struct rb_node * node)791 get_subtree_max_size(struct rb_node *node)
792 {
793 struct vmap_area *va;
794
795 va = rb_entry_safe(node, struct vmap_area, rb_node);
796 return va ? va->subtree_max_size : 0;
797 }
798
799 RB_DECLARE_CALLBACKS_MAX(static, free_vmap_area_rb_augment_cb,
800 struct vmap_area, rb_node, unsigned long, subtree_max_size, va_size)
801
802 static void reclaim_and_purge_vmap_areas(void);
803 static BLOCKING_NOTIFIER_HEAD(vmap_notify_list);
804 static void drain_vmap_area_work(struct work_struct *work);
805 static DECLARE_WORK(drain_vmap_work, drain_vmap_area_work);
806
807 static atomic_long_t nr_vmalloc_pages;
808
vmalloc_nr_pages(void)809 unsigned long vmalloc_nr_pages(void)
810 {
811 return atomic_long_read(&nr_vmalloc_pages);
812 }
813 EXPORT_SYMBOL_GPL(vmalloc_nr_pages);
814
815 /* Look up the first VA which satisfies addr < va_end, NULL if none. */
find_vmap_area_exceed_addr(unsigned long addr)816 static struct vmap_area *find_vmap_area_exceed_addr(unsigned long addr)
817 {
818 struct vmap_area *va = NULL;
819 struct rb_node *n = vmap_area_root.rb_node;
820
821 addr = (unsigned long)kasan_reset_tag((void *)addr);
822
823 while (n) {
824 struct vmap_area *tmp;
825
826 tmp = rb_entry(n, struct vmap_area, rb_node);
827 if (tmp->va_end > addr) {
828 va = tmp;
829 if (tmp->va_start <= addr)
830 break;
831
832 n = n->rb_left;
833 } else
834 n = n->rb_right;
835 }
836
837 return va;
838 }
839
__find_vmap_area(unsigned long addr,struct rb_root * root)840 static struct vmap_area *__find_vmap_area(unsigned long addr, struct rb_root *root)
841 {
842 struct rb_node *n = root->rb_node;
843
844 addr = (unsigned long)kasan_reset_tag((void *)addr);
845
846 while (n) {
847 struct vmap_area *va;
848
849 va = rb_entry(n, struct vmap_area, rb_node);
850 if (addr < va->va_start)
851 n = n->rb_left;
852 else if (addr >= va->va_end)
853 n = n->rb_right;
854 else
855 return va;
856 }
857
858 return NULL;
859 }
860
861 /*
862 * This function returns back addresses of parent node
863 * and its left or right link for further processing.
864 *
865 * Otherwise NULL is returned. In that case all further
866 * steps regarding inserting of conflicting overlap range
867 * have to be declined and actually considered as a bug.
868 */
869 static __always_inline struct rb_node **
find_va_links(struct vmap_area * va,struct rb_root * root,struct rb_node * from,struct rb_node ** parent)870 find_va_links(struct vmap_area *va,
871 struct rb_root *root, struct rb_node *from,
872 struct rb_node **parent)
873 {
874 struct vmap_area *tmp_va;
875 struct rb_node **link;
876
877 if (root) {
878 link = &root->rb_node;
879 if (unlikely(!*link)) {
880 *parent = NULL;
881 return link;
882 }
883 } else {
884 link = &from;
885 }
886
887 /*
888 * Go to the bottom of the tree. When we hit the last point
889 * we end up with parent rb_node and correct direction, i name
890 * it link, where the new va->rb_node will be attached to.
891 */
892 do {
893 tmp_va = rb_entry(*link, struct vmap_area, rb_node);
894
895 /*
896 * During the traversal we also do some sanity check.
897 * Trigger the BUG() if there are sides(left/right)
898 * or full overlaps.
899 */
900 if (va->va_end <= tmp_va->va_start)
901 link = &(*link)->rb_left;
902 else if (va->va_start >= tmp_va->va_end)
903 link = &(*link)->rb_right;
904 else {
905 WARN(1, "vmalloc bug: 0x%lx-0x%lx overlaps with 0x%lx-0x%lx\n",
906 va->va_start, va->va_end, tmp_va->va_start, tmp_va->va_end);
907
908 return NULL;
909 }
910 } while (*link);
911
912 *parent = &tmp_va->rb_node;
913 return link;
914 }
915
916 static __always_inline struct list_head *
get_va_next_sibling(struct rb_node * parent,struct rb_node ** link)917 get_va_next_sibling(struct rb_node *parent, struct rb_node **link)
918 {
919 struct list_head *list;
920
921 if (unlikely(!parent))
922 /*
923 * The red-black tree where we try to find VA neighbors
924 * before merging or inserting is empty, i.e. it means
925 * there is no free vmap space. Normally it does not
926 * happen but we handle this case anyway.
927 */
928 return NULL;
929
930 list = &rb_entry(parent, struct vmap_area, rb_node)->list;
931 return (&parent->rb_right == link ? list->next : list);
932 }
933
934 static __always_inline void
__link_va(struct vmap_area * va,struct rb_root * root,struct rb_node * parent,struct rb_node ** link,struct list_head * head,bool augment)935 __link_va(struct vmap_area *va, struct rb_root *root,
936 struct rb_node *parent, struct rb_node **link,
937 struct list_head *head, bool augment)
938 {
939 /*
940 * VA is still not in the list, but we can
941 * identify its future previous list_head node.
942 */
943 if (likely(parent)) {
944 head = &rb_entry(parent, struct vmap_area, rb_node)->list;
945 if (&parent->rb_right != link)
946 head = head->prev;
947 }
948
949 /* Insert to the rb-tree */
950 rb_link_node(&va->rb_node, parent, link);
951 if (augment) {
952 /*
953 * Some explanation here. Just perform simple insertion
954 * to the tree. We do not set va->subtree_max_size to
955 * its current size before calling rb_insert_augmented().
956 * It is because we populate the tree from the bottom
957 * to parent levels when the node _is_ in the tree.
958 *
959 * Therefore we set subtree_max_size to zero after insertion,
960 * to let __augment_tree_propagate_from() puts everything to
961 * the correct order later on.
962 */
963 rb_insert_augmented(&va->rb_node,
964 root, &free_vmap_area_rb_augment_cb);
965 va->subtree_max_size = 0;
966 } else {
967 rb_insert_color(&va->rb_node, root);
968 }
969
970 /* Address-sort this list */
971 list_add(&va->list, head);
972 }
973
974 static __always_inline void
link_va(struct vmap_area * va,struct rb_root * root,struct rb_node * parent,struct rb_node ** link,struct list_head * head)975 link_va(struct vmap_area *va, struct rb_root *root,
976 struct rb_node *parent, struct rb_node **link,
977 struct list_head *head)
978 {
979 __link_va(va, root, parent, link, head, false);
980 }
981
982 static __always_inline void
link_va_augment(struct vmap_area * va,struct rb_root * root,struct rb_node * parent,struct rb_node ** link,struct list_head * head)983 link_va_augment(struct vmap_area *va, struct rb_root *root,
984 struct rb_node *parent, struct rb_node **link,
985 struct list_head *head)
986 {
987 __link_va(va, root, parent, link, head, true);
988 }
989
990 static __always_inline void
__unlink_va(struct vmap_area * va,struct rb_root * root,bool augment)991 __unlink_va(struct vmap_area *va, struct rb_root *root, bool augment)
992 {
993 if (WARN_ON(RB_EMPTY_NODE(&va->rb_node)))
994 return;
995
996 if (augment)
997 rb_erase_augmented(&va->rb_node,
998 root, &free_vmap_area_rb_augment_cb);
999 else
1000 rb_erase(&va->rb_node, root);
1001
1002 list_del_init(&va->list);
1003 RB_CLEAR_NODE(&va->rb_node);
1004 }
1005
1006 static __always_inline void
unlink_va(struct vmap_area * va,struct rb_root * root)1007 unlink_va(struct vmap_area *va, struct rb_root *root)
1008 {
1009 __unlink_va(va, root, false);
1010 }
1011
1012 static __always_inline void
unlink_va_augment(struct vmap_area * va,struct rb_root * root)1013 unlink_va_augment(struct vmap_area *va, struct rb_root *root)
1014 {
1015 __unlink_va(va, root, true);
1016 }
1017
1018 #if DEBUG_AUGMENT_PROPAGATE_CHECK
1019 /*
1020 * Gets called when remove the node and rotate.
1021 */
1022 static __always_inline unsigned long
compute_subtree_max_size(struct vmap_area * va)1023 compute_subtree_max_size(struct vmap_area *va)
1024 {
1025 return max3(va_size(va),
1026 get_subtree_max_size(va->rb_node.rb_left),
1027 get_subtree_max_size(va->rb_node.rb_right));
1028 }
1029
1030 static void
augment_tree_propagate_check(void)1031 augment_tree_propagate_check(void)
1032 {
1033 struct vmap_area *va;
1034 unsigned long computed_size;
1035
1036 list_for_each_entry(va, &free_vmap_area_list, list) {
1037 computed_size = compute_subtree_max_size(va);
1038 if (computed_size != va->subtree_max_size)
1039 pr_emerg("tree is corrupted: %lu, %lu\n",
1040 va_size(va), va->subtree_max_size);
1041 }
1042 }
1043 #endif
1044
1045 /*
1046 * This function populates subtree_max_size from bottom to upper
1047 * levels starting from VA point. The propagation must be done
1048 * when VA size is modified by changing its va_start/va_end. Or
1049 * in case of newly inserting of VA to the tree.
1050 *
1051 * It means that __augment_tree_propagate_from() must be called:
1052 * - After VA has been inserted to the tree(free path);
1053 * - After VA has been shrunk(allocation path);
1054 * - After VA has been increased(merging path).
1055 *
1056 * Please note that, it does not mean that upper parent nodes
1057 * and their subtree_max_size are recalculated all the time up
1058 * to the root node.
1059 *
1060 * 4--8
1061 * /\
1062 * / \
1063 * / \
1064 * 2--2 8--8
1065 *
1066 * For example if we modify the node 4, shrinking it to 2, then
1067 * no any modification is required. If we shrink the node 2 to 1
1068 * its subtree_max_size is updated only, and set to 1. If we shrink
1069 * the node 8 to 6, then its subtree_max_size is set to 6 and parent
1070 * node becomes 4--6.
1071 */
1072 static __always_inline void
augment_tree_propagate_from(struct vmap_area * va)1073 augment_tree_propagate_from(struct vmap_area *va)
1074 {
1075 /*
1076 * Populate the tree from bottom towards the root until
1077 * the calculated maximum available size of checked node
1078 * is equal to its current one.
1079 */
1080 free_vmap_area_rb_augment_cb_propagate(&va->rb_node, NULL);
1081
1082 #if DEBUG_AUGMENT_PROPAGATE_CHECK
1083 augment_tree_propagate_check();
1084 #endif
1085 }
1086
1087 static void
insert_vmap_area(struct vmap_area * va,struct rb_root * root,struct list_head * head)1088 insert_vmap_area(struct vmap_area *va,
1089 struct rb_root *root, struct list_head *head)
1090 {
1091 struct rb_node **link;
1092 struct rb_node *parent;
1093
1094 link = find_va_links(va, root, NULL, &parent);
1095 if (link)
1096 link_va(va, root, parent, link, head);
1097 }
1098
1099 static void
insert_vmap_area_augment(struct vmap_area * va,struct rb_node * from,struct rb_root * root,struct list_head * head)1100 insert_vmap_area_augment(struct vmap_area *va,
1101 struct rb_node *from, struct rb_root *root,
1102 struct list_head *head)
1103 {
1104 struct rb_node **link;
1105 struct rb_node *parent;
1106
1107 if (from)
1108 link = find_va_links(va, NULL, from, &parent);
1109 else
1110 link = find_va_links(va, root, NULL, &parent);
1111
1112 if (link) {
1113 link_va_augment(va, root, parent, link, head);
1114 augment_tree_propagate_from(va);
1115 }
1116 }
1117
1118 /*
1119 * Merge de-allocated chunk of VA memory with previous
1120 * and next free blocks. If coalesce is not done a new
1121 * free area is inserted. If VA has been merged, it is
1122 * freed.
1123 *
1124 * Please note, it can return NULL in case of overlap
1125 * ranges, followed by WARN() report. Despite it is a
1126 * buggy behaviour, a system can be alive and keep
1127 * ongoing.
1128 */
1129 static __always_inline struct vmap_area *
__merge_or_add_vmap_area(struct vmap_area * va,struct rb_root * root,struct list_head * head,bool augment)1130 __merge_or_add_vmap_area(struct vmap_area *va,
1131 struct rb_root *root, struct list_head *head, bool augment)
1132 {
1133 struct vmap_area *sibling;
1134 struct list_head *next;
1135 struct rb_node **link;
1136 struct rb_node *parent;
1137 bool merged = false;
1138
1139 /*
1140 * Find a place in the tree where VA potentially will be
1141 * inserted, unless it is merged with its sibling/siblings.
1142 */
1143 link = find_va_links(va, root, NULL, &parent);
1144 if (!link)
1145 return NULL;
1146
1147 /*
1148 * Get next node of VA to check if merging can be done.
1149 */
1150 next = get_va_next_sibling(parent, link);
1151 if (unlikely(next == NULL))
1152 goto insert;
1153
1154 /*
1155 * start end
1156 * | |
1157 * |<------VA------>|<-----Next----->|
1158 * | |
1159 * start end
1160 */
1161 if (next != head) {
1162 sibling = list_entry(next, struct vmap_area, list);
1163 if (sibling->va_start == va->va_end) {
1164 sibling->va_start = va->va_start;
1165
1166 /* Free vmap_area object. */
1167 kmem_cache_free(vmap_area_cachep, va);
1168
1169 /* Point to the new merged area. */
1170 va = sibling;
1171 merged = true;
1172 }
1173 }
1174
1175 /*
1176 * start end
1177 * | |
1178 * |<-----Prev----->|<------VA------>|
1179 * | |
1180 * start end
1181 */
1182 if (next->prev != head) {
1183 sibling = list_entry(next->prev, struct vmap_area, list);
1184 if (sibling->va_end == va->va_start) {
1185 /*
1186 * If both neighbors are coalesced, it is important
1187 * to unlink the "next" node first, followed by merging
1188 * with "previous" one. Otherwise the tree might not be
1189 * fully populated if a sibling's augmented value is
1190 * "normalized" because of rotation operations.
1191 */
1192 if (merged)
1193 __unlink_va(va, root, augment);
1194
1195 sibling->va_end = va->va_end;
1196
1197 /* Free vmap_area object. */
1198 kmem_cache_free(vmap_area_cachep, va);
1199
1200 /* Point to the new merged area. */
1201 va = sibling;
1202 merged = true;
1203 }
1204 }
1205
1206 insert:
1207 if (!merged)
1208 __link_va(va, root, parent, link, head, augment);
1209
1210 return va;
1211 }
1212
1213 static __always_inline struct vmap_area *
merge_or_add_vmap_area(struct vmap_area * va,struct rb_root * root,struct list_head * head)1214 merge_or_add_vmap_area(struct vmap_area *va,
1215 struct rb_root *root, struct list_head *head)
1216 {
1217 return __merge_or_add_vmap_area(va, root, head, false);
1218 }
1219
1220 static __always_inline struct vmap_area *
merge_or_add_vmap_area_augment(struct vmap_area * va,struct rb_root * root,struct list_head * head)1221 merge_or_add_vmap_area_augment(struct vmap_area *va,
1222 struct rb_root *root, struct list_head *head)
1223 {
1224 va = __merge_or_add_vmap_area(va, root, head, true);
1225 if (va)
1226 augment_tree_propagate_from(va);
1227
1228 return va;
1229 }
1230
1231 static __always_inline bool
is_within_this_va(struct vmap_area * va,unsigned long size,unsigned long align,unsigned long vstart)1232 is_within_this_va(struct vmap_area *va, unsigned long size,
1233 unsigned long align, unsigned long vstart)
1234 {
1235 unsigned long nva_start_addr;
1236
1237 if (va->va_start > vstart)
1238 nva_start_addr = ALIGN(va->va_start, align);
1239 else
1240 nva_start_addr = ALIGN(vstart, align);
1241
1242 /* Can be overflowed due to big size or alignment. */
1243 if (nva_start_addr + size < nva_start_addr ||
1244 nva_start_addr < vstart)
1245 return false;
1246
1247 return (nva_start_addr + size <= va->va_end);
1248 }
1249
1250 /*
1251 * Find the first free block(lowest start address) in the tree,
1252 * that will accomplish the request corresponding to passing
1253 * parameters. Please note, with an alignment bigger than PAGE_SIZE,
1254 * a search length is adjusted to account for worst case alignment
1255 * overhead.
1256 */
1257 static __always_inline struct vmap_area *
find_vmap_lowest_match(struct rb_root * root,unsigned long size,unsigned long align,unsigned long vstart,bool adjust_search_size)1258 find_vmap_lowest_match(struct rb_root *root, unsigned long size,
1259 unsigned long align, unsigned long vstart, bool adjust_search_size)
1260 {
1261 struct vmap_area *va;
1262 struct rb_node *node;
1263 unsigned long length;
1264
1265 /* Start from the root. */
1266 node = root->rb_node;
1267
1268 /* Adjust the search size for alignment overhead. */
1269 length = adjust_search_size ? size + align - 1 : size;
1270
1271 while (node) {
1272 va = rb_entry(node, struct vmap_area, rb_node);
1273
1274 if (get_subtree_max_size(node->rb_left) >= length &&
1275 vstart < va->va_start) {
1276 node = node->rb_left;
1277 } else {
1278 if (is_within_this_va(va, size, align, vstart))
1279 return va;
1280
1281 /*
1282 * Does not make sense to go deeper towards the right
1283 * sub-tree if it does not have a free block that is
1284 * equal or bigger to the requested search length.
1285 */
1286 if (get_subtree_max_size(node->rb_right) >= length) {
1287 node = node->rb_right;
1288 continue;
1289 }
1290
1291 /*
1292 * OK. We roll back and find the first right sub-tree,
1293 * that will satisfy the search criteria. It can happen
1294 * due to "vstart" restriction or an alignment overhead
1295 * that is bigger then PAGE_SIZE.
1296 */
1297 while ((node = rb_parent(node))) {
1298 va = rb_entry(node, struct vmap_area, rb_node);
1299 if (is_within_this_va(va, size, align, vstart))
1300 return va;
1301
1302 if (get_subtree_max_size(node->rb_right) >= length &&
1303 vstart <= va->va_start) {
1304 /*
1305 * Shift the vstart forward. Please note, we update it with
1306 * parent's start address adding "1" because we do not want
1307 * to enter same sub-tree after it has already been checked
1308 * and no suitable free block found there.
1309 */
1310 vstart = va->va_start + 1;
1311 node = node->rb_right;
1312 break;
1313 }
1314 }
1315 }
1316 }
1317
1318 return NULL;
1319 }
1320
1321 #if DEBUG_AUGMENT_LOWEST_MATCH_CHECK
1322 #include <linux/random.h>
1323
1324 static struct vmap_area *
find_vmap_lowest_linear_match(struct list_head * head,unsigned long size,unsigned long align,unsigned long vstart)1325 find_vmap_lowest_linear_match(struct list_head *head, unsigned long size,
1326 unsigned long align, unsigned long vstart)
1327 {
1328 struct vmap_area *va;
1329
1330 list_for_each_entry(va, head, list) {
1331 if (!is_within_this_va(va, size, align, vstart))
1332 continue;
1333
1334 return va;
1335 }
1336
1337 return NULL;
1338 }
1339
1340 static void
find_vmap_lowest_match_check(struct rb_root * root,struct list_head * head,unsigned long size,unsigned long align)1341 find_vmap_lowest_match_check(struct rb_root *root, struct list_head *head,
1342 unsigned long size, unsigned long align)
1343 {
1344 struct vmap_area *va_1, *va_2;
1345 unsigned long vstart;
1346 unsigned int rnd;
1347
1348 get_random_bytes(&rnd, sizeof(rnd));
1349 vstart = VMALLOC_START + rnd;
1350
1351 va_1 = find_vmap_lowest_match(root, size, align, vstart, false);
1352 va_2 = find_vmap_lowest_linear_match(head, size, align, vstart);
1353
1354 if (va_1 != va_2)
1355 pr_emerg("not lowest: t: 0x%p, l: 0x%p, v: 0x%lx\n",
1356 va_1, va_2, vstart);
1357 }
1358 #endif
1359
1360 enum fit_type {
1361 NOTHING_FIT = 0,
1362 FL_FIT_TYPE = 1, /* full fit */
1363 LE_FIT_TYPE = 2, /* left edge fit */
1364 RE_FIT_TYPE = 3, /* right edge fit */
1365 NE_FIT_TYPE = 4 /* no edge fit */
1366 };
1367
1368 static __always_inline enum fit_type
classify_va_fit_type(struct vmap_area * va,unsigned long nva_start_addr,unsigned long size)1369 classify_va_fit_type(struct vmap_area *va,
1370 unsigned long nva_start_addr, unsigned long size)
1371 {
1372 enum fit_type type;
1373
1374 /* Check if it is within VA. */
1375 if (nva_start_addr < va->va_start ||
1376 nva_start_addr + size > va->va_end)
1377 return NOTHING_FIT;
1378
1379 /* Now classify. */
1380 if (va->va_start == nva_start_addr) {
1381 if (va->va_end == nva_start_addr + size)
1382 type = FL_FIT_TYPE;
1383 else
1384 type = LE_FIT_TYPE;
1385 } else if (va->va_end == nva_start_addr + size) {
1386 type = RE_FIT_TYPE;
1387 } else {
1388 type = NE_FIT_TYPE;
1389 }
1390
1391 return type;
1392 }
1393
1394 static __always_inline int
adjust_va_to_fit_type(struct rb_root * root,struct list_head * head,struct vmap_area * va,unsigned long nva_start_addr,unsigned long size)1395 adjust_va_to_fit_type(struct rb_root *root, struct list_head *head,
1396 struct vmap_area *va, unsigned long nva_start_addr,
1397 unsigned long size)
1398 {
1399 struct vmap_area *lva = NULL;
1400 enum fit_type type = classify_va_fit_type(va, nva_start_addr, size);
1401
1402 if (type == FL_FIT_TYPE) {
1403 /*
1404 * No need to split VA, it fully fits.
1405 *
1406 * | |
1407 * V NVA V
1408 * |---------------|
1409 */
1410 unlink_va_augment(va, root);
1411 kmem_cache_free(vmap_area_cachep, va);
1412 } else if (type == LE_FIT_TYPE) {
1413 /*
1414 * Split left edge of fit VA.
1415 *
1416 * | |
1417 * V NVA V R
1418 * |-------|-------|
1419 */
1420 va->va_start += size;
1421 } else if (type == RE_FIT_TYPE) {
1422 /*
1423 * Split right edge of fit VA.
1424 *
1425 * | |
1426 * L V NVA V
1427 * |-------|-------|
1428 */
1429 va->va_end = nva_start_addr;
1430 } else if (type == NE_FIT_TYPE) {
1431 /*
1432 * Split no edge of fit VA.
1433 *
1434 * | |
1435 * L V NVA V R
1436 * |---|-------|---|
1437 */
1438 lva = __this_cpu_xchg(ne_fit_preload_node, NULL);
1439 if (unlikely(!lva)) {
1440 /*
1441 * For percpu allocator we do not do any pre-allocation
1442 * and leave it as it is. The reason is it most likely
1443 * never ends up with NE_FIT_TYPE splitting. In case of
1444 * percpu allocations offsets and sizes are aligned to
1445 * fixed align request, i.e. RE_FIT_TYPE and FL_FIT_TYPE
1446 * are its main fitting cases.
1447 *
1448 * There are a few exceptions though, as an example it is
1449 * a first allocation (early boot up) when we have "one"
1450 * big free space that has to be split.
1451 *
1452 * Also we can hit this path in case of regular "vmap"
1453 * allocations, if "this" current CPU was not preloaded.
1454 * See the comment in alloc_vmap_area() why. If so, then
1455 * GFP_NOWAIT is used instead to get an extra object for
1456 * split purpose. That is rare and most time does not
1457 * occur.
1458 *
1459 * What happens if an allocation gets failed. Basically,
1460 * an "overflow" path is triggered to purge lazily freed
1461 * areas to free some memory, then, the "retry" path is
1462 * triggered to repeat one more time. See more details
1463 * in alloc_vmap_area() function.
1464 */
1465 lva = kmem_cache_alloc(vmap_area_cachep, GFP_NOWAIT);
1466 if (!lva)
1467 return -1;
1468 }
1469
1470 /*
1471 * Build the remainder.
1472 */
1473 lva->va_start = va->va_start;
1474 lva->va_end = nva_start_addr;
1475
1476 /*
1477 * Shrink this VA to remaining size.
1478 */
1479 va->va_start = nva_start_addr + size;
1480 } else {
1481 return -1;
1482 }
1483
1484 if (type != FL_FIT_TYPE) {
1485 augment_tree_propagate_from(va);
1486
1487 if (lva) /* type == NE_FIT_TYPE */
1488 insert_vmap_area_augment(lva, &va->rb_node, root, head);
1489 }
1490
1491 return 0;
1492 }
1493
1494 /*
1495 * Returns a start address of the newly allocated area, if success.
1496 * Otherwise a vend is returned that indicates failure.
1497 */
1498 static __always_inline unsigned long
__alloc_vmap_area(struct rb_root * root,struct list_head * head,unsigned long size,unsigned long align,unsigned long vstart,unsigned long vend)1499 __alloc_vmap_area(struct rb_root *root, struct list_head *head,
1500 unsigned long size, unsigned long align,
1501 unsigned long vstart, unsigned long vend)
1502 {
1503 bool adjust_search_size = true;
1504 unsigned long nva_start_addr;
1505 struct vmap_area *va;
1506 int ret;
1507
1508 /*
1509 * Do not adjust when:
1510 * a) align <= PAGE_SIZE, because it does not make any sense.
1511 * All blocks(their start addresses) are at least PAGE_SIZE
1512 * aligned anyway;
1513 * b) a short range where a requested size corresponds to exactly
1514 * specified [vstart:vend] interval and an alignment > PAGE_SIZE.
1515 * With adjusted search length an allocation would not succeed.
1516 */
1517 if (align <= PAGE_SIZE || (align > PAGE_SIZE && (vend - vstart) == size))
1518 adjust_search_size = false;
1519
1520 va = find_vmap_lowest_match(root, size, align, vstart, adjust_search_size);
1521 if (unlikely(!va))
1522 return vend;
1523
1524 if (va->va_start > vstart)
1525 nva_start_addr = ALIGN(va->va_start, align);
1526 else
1527 nva_start_addr = ALIGN(vstart, align);
1528
1529 /* Check the "vend" restriction. */
1530 if (nva_start_addr + size > vend)
1531 return vend;
1532
1533 /* Update the free vmap_area. */
1534 ret = adjust_va_to_fit_type(root, head, va, nva_start_addr, size);
1535 if (WARN_ON_ONCE(ret))
1536 return vend;
1537
1538 #if DEBUG_AUGMENT_LOWEST_MATCH_CHECK
1539 find_vmap_lowest_match_check(root, head, size, align);
1540 #endif
1541
1542 return nva_start_addr;
1543 }
1544
1545 /*
1546 * Free a region of KVA allocated by alloc_vmap_area
1547 */
free_vmap_area(struct vmap_area * va)1548 static void free_vmap_area(struct vmap_area *va)
1549 {
1550 /*
1551 * Remove from the busy tree/list.
1552 */
1553 spin_lock(&vmap_area_lock);
1554 unlink_va(va, &vmap_area_root);
1555 spin_unlock(&vmap_area_lock);
1556
1557 /*
1558 * Insert/Merge it back to the free tree/list.
1559 */
1560 spin_lock(&free_vmap_area_lock);
1561 merge_or_add_vmap_area_augment(va, &free_vmap_area_root, &free_vmap_area_list);
1562 spin_unlock(&free_vmap_area_lock);
1563 }
1564
1565 static inline void
preload_this_cpu_lock(spinlock_t * lock,gfp_t gfp_mask,int node)1566 preload_this_cpu_lock(spinlock_t *lock, gfp_t gfp_mask, int node)
1567 {
1568 struct vmap_area *va = NULL;
1569
1570 /*
1571 * Preload this CPU with one extra vmap_area object. It is used
1572 * when fit type of free area is NE_FIT_TYPE. It guarantees that
1573 * a CPU that does an allocation is preloaded.
1574 *
1575 * We do it in non-atomic context, thus it allows us to use more
1576 * permissive allocation masks to be more stable under low memory
1577 * condition and high memory pressure.
1578 */
1579 if (!this_cpu_read(ne_fit_preload_node))
1580 va = kmem_cache_alloc_node(vmap_area_cachep, gfp_mask, node);
1581
1582 spin_lock(lock);
1583
1584 if (va && __this_cpu_cmpxchg(ne_fit_preload_node, NULL, va))
1585 kmem_cache_free(vmap_area_cachep, va);
1586 }
1587
1588 /*
1589 * Allocate a region of KVA of the specified size and alignment, within the
1590 * vstart and vend.
1591 */
alloc_vmap_area(unsigned long size,unsigned long align,unsigned long vstart,unsigned long vend,int node,gfp_t gfp_mask,unsigned long va_flags)1592 static struct vmap_area *alloc_vmap_area(unsigned long size,
1593 unsigned long align,
1594 unsigned long vstart, unsigned long vend,
1595 int node, gfp_t gfp_mask,
1596 unsigned long va_flags)
1597 {
1598 struct vmap_area *va;
1599 unsigned long freed;
1600 unsigned long addr;
1601 int purged = 0;
1602 int ret;
1603
1604 if (unlikely(!size || offset_in_page(size) || !is_power_of_2(align)))
1605 return ERR_PTR(-EINVAL);
1606
1607 if (unlikely(!vmap_initialized))
1608 return ERR_PTR(-EBUSY);
1609
1610 might_sleep();
1611 gfp_mask = gfp_mask & GFP_RECLAIM_MASK;
1612
1613 va = kmem_cache_alloc_node(vmap_area_cachep, gfp_mask, node);
1614 if (unlikely(!va))
1615 return ERR_PTR(-ENOMEM);
1616
1617 /*
1618 * Only scan the relevant parts containing pointers to other objects
1619 * to avoid false negatives.
1620 */
1621 kmemleak_scan_area(&va->rb_node, SIZE_MAX, gfp_mask);
1622
1623 retry:
1624 preload_this_cpu_lock(&free_vmap_area_lock, gfp_mask, node);
1625 addr = __alloc_vmap_area(&free_vmap_area_root, &free_vmap_area_list,
1626 size, align, vstart, vend);
1627 spin_unlock(&free_vmap_area_lock);
1628
1629 trace_alloc_vmap_area(addr, size, align, vstart, vend, addr == vend);
1630
1631 /*
1632 * If an allocation fails, the "vend" address is
1633 * returned. Therefore trigger the overflow path.
1634 */
1635 if (unlikely(addr == vend))
1636 goto overflow;
1637
1638 va->va_start = addr;
1639 va->va_end = addr + size;
1640 va->vm = NULL;
1641 va->flags = va_flags;
1642
1643 spin_lock(&vmap_area_lock);
1644 insert_vmap_area(va, &vmap_area_root, &vmap_area_list);
1645 spin_unlock(&vmap_area_lock);
1646
1647 BUG_ON(!IS_ALIGNED(va->va_start, align));
1648 BUG_ON(va->va_start < vstart);
1649 BUG_ON(va->va_end > vend);
1650
1651 ret = kasan_populate_vmalloc(addr, size);
1652 if (ret) {
1653 free_vmap_area(va);
1654 return ERR_PTR(ret);
1655 }
1656
1657 return va;
1658
1659 overflow:
1660 if (!purged) {
1661 reclaim_and_purge_vmap_areas();
1662 purged = 1;
1663 goto retry;
1664 }
1665
1666 freed = 0;
1667 blocking_notifier_call_chain(&vmap_notify_list, 0, &freed);
1668
1669 if (freed > 0) {
1670 purged = 0;
1671 goto retry;
1672 }
1673
1674 if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit())
1675 pr_warn("vmap allocation for size %lu failed: use vmalloc=<size> to increase size\n",
1676 size);
1677
1678 kmem_cache_free(vmap_area_cachep, va);
1679 return ERR_PTR(-EBUSY);
1680 }
1681
register_vmap_purge_notifier(struct notifier_block * nb)1682 int register_vmap_purge_notifier(struct notifier_block *nb)
1683 {
1684 return blocking_notifier_chain_register(&vmap_notify_list, nb);
1685 }
1686 EXPORT_SYMBOL_GPL(register_vmap_purge_notifier);
1687
unregister_vmap_purge_notifier(struct notifier_block * nb)1688 int unregister_vmap_purge_notifier(struct notifier_block *nb)
1689 {
1690 return blocking_notifier_chain_unregister(&vmap_notify_list, nb);
1691 }
1692 EXPORT_SYMBOL_GPL(unregister_vmap_purge_notifier);
1693
1694 /*
1695 * lazy_max_pages is the maximum amount of virtual address space we gather up
1696 * before attempting to purge with a TLB flush.
1697 *
1698 * There is a tradeoff here: a larger number will cover more kernel page tables
1699 * and take slightly longer to purge, but it will linearly reduce the number of
1700 * global TLB flushes that must be performed. It would seem natural to scale
1701 * this number up linearly with the number of CPUs (because vmapping activity
1702 * could also scale linearly with the number of CPUs), however it is likely
1703 * that in practice, workloads might be constrained in other ways that mean
1704 * vmap activity will not scale linearly with CPUs. Also, I want to be
1705 * conservative and not introduce a big latency on huge systems, so go with
1706 * a less aggressive log scale. It will still be an improvement over the old
1707 * code, and it will be simple to change the scale factor if we find that it
1708 * becomes a problem on bigger systems.
1709 */
lazy_max_pages(void)1710 static unsigned long lazy_max_pages(void)
1711 {
1712 unsigned int log;
1713
1714 log = fls(num_online_cpus());
1715
1716 return log * (32UL * 1024 * 1024 / PAGE_SIZE);
1717 }
1718
1719 static atomic_long_t vmap_lazy_nr = ATOMIC_LONG_INIT(0);
1720
1721 /*
1722 * Serialize vmap purging. There is no actual critical section protected
1723 * by this lock, but we want to avoid concurrent calls for performance
1724 * reasons and to make the pcpu_get_vm_areas more deterministic.
1725 */
1726 static DEFINE_MUTEX(vmap_purge_lock);
1727
1728 /* for per-CPU blocks */
1729 static void purge_fragmented_blocks_allcpus(void);
1730
1731 /*
1732 * Purges all lazily-freed vmap areas.
1733 */
__purge_vmap_area_lazy(unsigned long start,unsigned long end)1734 static bool __purge_vmap_area_lazy(unsigned long start, unsigned long end)
1735 {
1736 unsigned long resched_threshold;
1737 unsigned int num_purged_areas = 0;
1738 struct list_head local_purge_list;
1739 struct vmap_area *va, *n_va;
1740
1741 lockdep_assert_held(&vmap_purge_lock);
1742
1743 spin_lock(&purge_vmap_area_lock);
1744 purge_vmap_area_root = RB_ROOT;
1745 list_replace_init(&purge_vmap_area_list, &local_purge_list);
1746 spin_unlock(&purge_vmap_area_lock);
1747
1748 if (unlikely(list_empty(&local_purge_list)))
1749 goto out;
1750
1751 start = min(start,
1752 list_first_entry(&local_purge_list,
1753 struct vmap_area, list)->va_start);
1754
1755 end = max(end,
1756 list_last_entry(&local_purge_list,
1757 struct vmap_area, list)->va_end);
1758
1759 flush_tlb_kernel_range(start, end);
1760 resched_threshold = lazy_max_pages() << 1;
1761
1762 spin_lock(&free_vmap_area_lock);
1763 list_for_each_entry_safe(va, n_va, &local_purge_list, list) {
1764 unsigned long nr = (va->va_end - va->va_start) >> PAGE_SHIFT;
1765 unsigned long orig_start = va->va_start;
1766 unsigned long orig_end = va->va_end;
1767
1768 /*
1769 * Finally insert or merge lazily-freed area. It is
1770 * detached and there is no need to "unlink" it from
1771 * anything.
1772 */
1773 va = merge_or_add_vmap_area_augment(va, &free_vmap_area_root,
1774 &free_vmap_area_list);
1775
1776 if (!va)
1777 continue;
1778
1779 if (is_vmalloc_or_module_addr((void *)orig_start))
1780 kasan_release_vmalloc(orig_start, orig_end,
1781 va->va_start, va->va_end);
1782
1783 atomic_long_sub(nr, &vmap_lazy_nr);
1784 num_purged_areas++;
1785
1786 if (atomic_long_read(&vmap_lazy_nr) < resched_threshold)
1787 cond_resched_lock(&free_vmap_area_lock);
1788 }
1789 spin_unlock(&free_vmap_area_lock);
1790
1791 out:
1792 trace_purge_vmap_area_lazy(start, end, num_purged_areas);
1793 return num_purged_areas > 0;
1794 }
1795
1796 /*
1797 * Reclaim vmap areas by purging fragmented blocks and purge_vmap_area_list.
1798 */
reclaim_and_purge_vmap_areas(void)1799 static void reclaim_and_purge_vmap_areas(void)
1800
1801 {
1802 mutex_lock(&vmap_purge_lock);
1803 purge_fragmented_blocks_allcpus();
1804 __purge_vmap_area_lazy(ULONG_MAX, 0);
1805 mutex_unlock(&vmap_purge_lock);
1806 }
1807
drain_vmap_area_work(struct work_struct * work)1808 static void drain_vmap_area_work(struct work_struct *work)
1809 {
1810 unsigned long nr_lazy;
1811
1812 do {
1813 mutex_lock(&vmap_purge_lock);
1814 __purge_vmap_area_lazy(ULONG_MAX, 0);
1815 mutex_unlock(&vmap_purge_lock);
1816
1817 /* Recheck if further work is required. */
1818 nr_lazy = atomic_long_read(&vmap_lazy_nr);
1819 } while (nr_lazy > lazy_max_pages());
1820 }
1821
1822 /*
1823 * Free a vmap area, caller ensuring that the area has been unmapped,
1824 * unlinked and flush_cache_vunmap had been called for the correct
1825 * range previously.
1826 */
free_vmap_area_noflush(struct vmap_area * va)1827 static void free_vmap_area_noflush(struct vmap_area *va)
1828 {
1829 unsigned long nr_lazy_max = lazy_max_pages();
1830 unsigned long va_start = va->va_start;
1831 unsigned long nr_lazy;
1832
1833 if (WARN_ON_ONCE(!list_empty(&va->list)))
1834 return;
1835
1836 nr_lazy = atomic_long_add_return((va->va_end - va->va_start) >>
1837 PAGE_SHIFT, &vmap_lazy_nr);
1838
1839 /*
1840 * Merge or place it to the purge tree/list.
1841 */
1842 spin_lock(&purge_vmap_area_lock);
1843 merge_or_add_vmap_area(va,
1844 &purge_vmap_area_root, &purge_vmap_area_list);
1845 spin_unlock(&purge_vmap_area_lock);
1846
1847 trace_free_vmap_area_noflush(va_start, nr_lazy, nr_lazy_max);
1848
1849 /* After this point, we may free va at any time */
1850 if (unlikely(nr_lazy > nr_lazy_max))
1851 schedule_work(&drain_vmap_work);
1852 }
1853
1854 /*
1855 * Free and unmap a vmap area
1856 */
free_unmap_vmap_area(struct vmap_area * va)1857 static void free_unmap_vmap_area(struct vmap_area *va)
1858 {
1859 flush_cache_vunmap(va->va_start, va->va_end);
1860 vunmap_range_noflush(va->va_start, va->va_end);
1861 if (debug_pagealloc_enabled_static())
1862 flush_tlb_kernel_range(va->va_start, va->va_end);
1863
1864 free_vmap_area_noflush(va);
1865 }
1866
find_vmap_area(unsigned long addr)1867 struct vmap_area *find_vmap_area(unsigned long addr)
1868 {
1869 struct vmap_area *va;
1870
1871 spin_lock(&vmap_area_lock);
1872 va = __find_vmap_area(addr, &vmap_area_root);
1873 spin_unlock(&vmap_area_lock);
1874
1875 return va;
1876 }
1877
find_unlink_vmap_area(unsigned long addr)1878 static struct vmap_area *find_unlink_vmap_area(unsigned long addr)
1879 {
1880 struct vmap_area *va;
1881
1882 spin_lock(&vmap_area_lock);
1883 va = __find_vmap_area(addr, &vmap_area_root);
1884 if (va)
1885 unlink_va(va, &vmap_area_root);
1886 spin_unlock(&vmap_area_lock);
1887
1888 return va;
1889 }
1890
1891 /*** Per cpu kva allocator ***/
1892
1893 /*
1894 * vmap space is limited especially on 32 bit architectures. Ensure there is
1895 * room for at least 16 percpu vmap blocks per CPU.
1896 */
1897 /*
1898 * If we had a constant VMALLOC_START and VMALLOC_END, we'd like to be able
1899 * to #define VMALLOC_SPACE (VMALLOC_END-VMALLOC_START). Guess
1900 * instead (we just need a rough idea)
1901 */
1902 #if BITS_PER_LONG == 32
1903 #define VMALLOC_SPACE (128UL*1024*1024)
1904 #else
1905 #define VMALLOC_SPACE (128UL*1024*1024*1024)
1906 #endif
1907
1908 #define VMALLOC_PAGES (VMALLOC_SPACE / PAGE_SIZE)
1909 #define VMAP_MAX_ALLOC BITS_PER_LONG /* 256K with 4K pages */
1910 #define VMAP_BBMAP_BITS_MAX 1024 /* 4MB with 4K pages */
1911 #define VMAP_BBMAP_BITS_MIN (VMAP_MAX_ALLOC*2)
1912 #define VMAP_MIN(x, y) ((x) < (y) ? (x) : (y)) /* can't use min() */
1913 #define VMAP_MAX(x, y) ((x) > (y) ? (x) : (y)) /* can't use max() */
1914 #define VMAP_BBMAP_BITS \
1915 VMAP_MIN(VMAP_BBMAP_BITS_MAX, \
1916 VMAP_MAX(VMAP_BBMAP_BITS_MIN, \
1917 VMALLOC_PAGES / roundup_pow_of_two(NR_CPUS) / 16))
1918
1919 #define VMAP_BLOCK_SIZE (VMAP_BBMAP_BITS * PAGE_SIZE)
1920
1921 /*
1922 * Purge threshold to prevent overeager purging of fragmented blocks for
1923 * regular operations: Purge if vb->free is less than 1/4 of the capacity.
1924 */
1925 #define VMAP_PURGE_THRESHOLD (VMAP_BBMAP_BITS / 4)
1926
1927 #define VMAP_RAM 0x1 /* indicates vm_map_ram area*/
1928 #define VMAP_BLOCK 0x2 /* mark out the vmap_block sub-type*/
1929 #define VMAP_FLAGS_MASK 0x3
1930
1931 struct vmap_block_queue {
1932 spinlock_t lock;
1933 struct list_head free;
1934
1935 /*
1936 * An xarray requires an extra memory dynamically to
1937 * be allocated. If it is an issue, we can use rb-tree
1938 * instead.
1939 */
1940 struct xarray vmap_blocks;
1941 };
1942
1943 struct vmap_block {
1944 spinlock_t lock;
1945 struct vmap_area *va;
1946 unsigned long free, dirty;
1947 DECLARE_BITMAP(used_map, VMAP_BBMAP_BITS);
1948 unsigned long dirty_min, dirty_max; /*< dirty range */
1949 struct list_head free_list;
1950 struct rcu_head rcu_head;
1951 struct list_head purge;
1952 unsigned int cpu;
1953 };
1954
1955 /* Queue of free and dirty vmap blocks, for allocation and flushing purposes */
1956 static DEFINE_PER_CPU(struct vmap_block_queue, vmap_block_queue);
1957
1958 /*
1959 * In order to fast access to any "vmap_block" associated with a
1960 * specific address, we use a hash.
1961 *
1962 * A per-cpu vmap_block_queue is used in both ways, to serialize
1963 * an access to free block chains among CPUs(alloc path) and it
1964 * also acts as a vmap_block hash(alloc/free paths). It means we
1965 * overload it, since we already have the per-cpu array which is
1966 * used as a hash table. When used as a hash a 'cpu' passed to
1967 * per_cpu() is not actually a CPU but rather a hash index.
1968 *
1969 * A hash function is addr_to_vb_xa() which hashes any address
1970 * to a specific index(in a hash) it belongs to. This then uses a
1971 * per_cpu() macro to access an array with generated index.
1972 *
1973 * An example:
1974 *
1975 * CPU_1 CPU_2 CPU_0
1976 * | | |
1977 * V V V
1978 * 0 10 20 30 40 50 60
1979 * |------|------|------|------|------|------|...<vmap address space>
1980 * CPU0 CPU1 CPU2 CPU0 CPU1 CPU2
1981 *
1982 * - CPU_1 invokes vm_unmap_ram(6), 6 belongs to CPU0 zone, thus
1983 * it access: CPU0/INDEX0 -> vmap_blocks -> xa_lock;
1984 *
1985 * - CPU_2 invokes vm_unmap_ram(11), 11 belongs to CPU1 zone, thus
1986 * it access: CPU1/INDEX1 -> vmap_blocks -> xa_lock;
1987 *
1988 * - CPU_0 invokes vm_unmap_ram(20), 20 belongs to CPU2 zone, thus
1989 * it access: CPU2/INDEX2 -> vmap_blocks -> xa_lock.
1990 *
1991 * This technique almost always avoids lock contention on insert/remove,
1992 * however xarray spinlocks protect against any contention that remains.
1993 */
1994 static struct xarray *
addr_to_vb_xa(unsigned long addr)1995 addr_to_vb_xa(unsigned long addr)
1996 {
1997 int index = (addr / VMAP_BLOCK_SIZE) % nr_cpu_ids;
1998
1999 /*
2000 * Please note, nr_cpu_ids points on a highest set
2001 * possible bit, i.e. we never invoke cpumask_next()
2002 * if an index points on it which is nr_cpu_ids - 1.
2003 */
2004 if (!cpu_possible(index))
2005 index = cpumask_next(index, cpu_possible_mask);
2006
2007 return &per_cpu(vmap_block_queue, index).vmap_blocks;
2008 }
2009
2010 /*
2011 * We should probably have a fallback mechanism to allocate virtual memory
2012 * out of partially filled vmap blocks. However vmap block sizing should be
2013 * fairly reasonable according to the vmalloc size, so it shouldn't be a
2014 * big problem.
2015 */
2016
addr_to_vb_idx(unsigned long addr)2017 static unsigned long addr_to_vb_idx(unsigned long addr)
2018 {
2019 addr -= VMALLOC_START & ~(VMAP_BLOCK_SIZE-1);
2020 addr /= VMAP_BLOCK_SIZE;
2021 return addr;
2022 }
2023
vmap_block_vaddr(unsigned long va_start,unsigned long pages_off)2024 static void *vmap_block_vaddr(unsigned long va_start, unsigned long pages_off)
2025 {
2026 unsigned long addr;
2027
2028 addr = va_start + (pages_off << PAGE_SHIFT);
2029 BUG_ON(addr_to_vb_idx(addr) != addr_to_vb_idx(va_start));
2030 return (void *)addr;
2031 }
2032
2033 /**
2034 * new_vmap_block - allocates new vmap_block and occupies 2^order pages in this
2035 * block. Of course pages number can't exceed VMAP_BBMAP_BITS
2036 * @order: how many 2^order pages should be occupied in newly allocated block
2037 * @gfp_mask: flags for the page level allocator
2038 *
2039 * Return: virtual address in a newly allocated block or ERR_PTR(-errno)
2040 */
new_vmap_block(unsigned int order,gfp_t gfp_mask)2041 static void *new_vmap_block(unsigned int order, gfp_t gfp_mask)
2042 {
2043 struct vmap_block_queue *vbq;
2044 struct vmap_block *vb;
2045 struct vmap_area *va;
2046 struct xarray *xa;
2047 unsigned long vb_idx;
2048 int node, err;
2049 void *vaddr;
2050
2051 node = numa_node_id();
2052
2053 vb = kmalloc_node(sizeof(struct vmap_block),
2054 gfp_mask & GFP_RECLAIM_MASK, node);
2055 if (unlikely(!vb))
2056 return ERR_PTR(-ENOMEM);
2057
2058 va = alloc_vmap_area(VMAP_BLOCK_SIZE, VMAP_BLOCK_SIZE,
2059 VMALLOC_START, VMALLOC_END,
2060 node, gfp_mask,
2061 VMAP_RAM|VMAP_BLOCK);
2062 if (IS_ERR(va)) {
2063 kfree(vb);
2064 return ERR_CAST(va);
2065 }
2066
2067 vaddr = vmap_block_vaddr(va->va_start, 0);
2068 spin_lock_init(&vb->lock);
2069 vb->va = va;
2070 /* At least something should be left free */
2071 BUG_ON(VMAP_BBMAP_BITS <= (1UL << order));
2072 bitmap_zero(vb->used_map, VMAP_BBMAP_BITS);
2073 vb->free = VMAP_BBMAP_BITS - (1UL << order);
2074 vb->dirty = 0;
2075 vb->dirty_min = VMAP_BBMAP_BITS;
2076 vb->dirty_max = 0;
2077 bitmap_set(vb->used_map, 0, (1UL << order));
2078 INIT_LIST_HEAD(&vb->free_list);
2079
2080 xa = addr_to_vb_xa(va->va_start);
2081 vb_idx = addr_to_vb_idx(va->va_start);
2082 err = xa_insert(xa, vb_idx, vb, gfp_mask);
2083 if (err) {
2084 kfree(vb);
2085 free_vmap_area(va);
2086 return ERR_PTR(err);
2087 }
2088 /*
2089 * list_add_tail_rcu could happened in another core
2090 * rather than vb->cpu due to task migration, which
2091 * is safe as list_add_tail_rcu will ensure the list's
2092 * integrity together with list_for_each_rcu from read
2093 * side.
2094 */
2095 vb->cpu = raw_smp_processor_id();
2096 vbq = per_cpu_ptr(&vmap_block_queue, vb->cpu);
2097 spin_lock(&vbq->lock);
2098 list_add_tail_rcu(&vb->free_list, &vbq->free);
2099 spin_unlock(&vbq->lock);
2100
2101 return vaddr;
2102 }
2103
free_vmap_block(struct vmap_block * vb)2104 static void free_vmap_block(struct vmap_block *vb)
2105 {
2106 struct vmap_block *tmp;
2107 struct xarray *xa;
2108
2109 xa = addr_to_vb_xa(vb->va->va_start);
2110 tmp = xa_erase(xa, addr_to_vb_idx(vb->va->va_start));
2111 BUG_ON(tmp != vb);
2112
2113 spin_lock(&vmap_area_lock);
2114 unlink_va(vb->va, &vmap_area_root);
2115 spin_unlock(&vmap_area_lock);
2116
2117 free_vmap_area_noflush(vb->va);
2118 kfree_rcu(vb, rcu_head);
2119 }
2120
purge_fragmented_block(struct vmap_block * vb,struct list_head * purge_list,bool force_purge)2121 static bool purge_fragmented_block(struct vmap_block *vb,
2122 struct list_head *purge_list, bool force_purge)
2123 {
2124 struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, vb->cpu);
2125
2126 if (vb->free + vb->dirty != VMAP_BBMAP_BITS ||
2127 vb->dirty == VMAP_BBMAP_BITS)
2128 return false;
2129
2130 /* Don't overeagerly purge usable blocks unless requested */
2131 if (!(force_purge || vb->free < VMAP_PURGE_THRESHOLD))
2132 return false;
2133
2134 /* prevent further allocs after releasing lock */
2135 WRITE_ONCE(vb->free, 0);
2136 /* prevent purging it again */
2137 WRITE_ONCE(vb->dirty, VMAP_BBMAP_BITS);
2138 vb->dirty_min = 0;
2139 vb->dirty_max = VMAP_BBMAP_BITS;
2140 spin_lock(&vbq->lock);
2141 list_del_rcu(&vb->free_list);
2142 spin_unlock(&vbq->lock);
2143 list_add_tail(&vb->purge, purge_list);
2144 return true;
2145 }
2146
free_purged_blocks(struct list_head * purge_list)2147 static void free_purged_blocks(struct list_head *purge_list)
2148 {
2149 struct vmap_block *vb, *n_vb;
2150
2151 list_for_each_entry_safe(vb, n_vb, purge_list, purge) {
2152 list_del(&vb->purge);
2153 free_vmap_block(vb);
2154 }
2155 }
2156
purge_fragmented_blocks(int cpu)2157 static void purge_fragmented_blocks(int cpu)
2158 {
2159 LIST_HEAD(purge);
2160 struct vmap_block *vb;
2161 struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu);
2162
2163 rcu_read_lock();
2164 list_for_each_entry_rcu(vb, &vbq->free, free_list) {
2165 unsigned long free = READ_ONCE(vb->free);
2166 unsigned long dirty = READ_ONCE(vb->dirty);
2167
2168 if (free + dirty != VMAP_BBMAP_BITS ||
2169 dirty == VMAP_BBMAP_BITS)
2170 continue;
2171
2172 spin_lock(&vb->lock);
2173 purge_fragmented_block(vb, &purge, true);
2174 spin_unlock(&vb->lock);
2175 }
2176 rcu_read_unlock();
2177 free_purged_blocks(&purge);
2178 }
2179
purge_fragmented_blocks_allcpus(void)2180 static void purge_fragmented_blocks_allcpus(void)
2181 {
2182 int cpu;
2183
2184 for_each_possible_cpu(cpu)
2185 purge_fragmented_blocks(cpu);
2186 }
2187
vb_alloc(unsigned long size,gfp_t gfp_mask)2188 static void *vb_alloc(unsigned long size, gfp_t gfp_mask)
2189 {
2190 struct vmap_block_queue *vbq;
2191 struct vmap_block *vb;
2192 void *vaddr = NULL;
2193 unsigned int order;
2194
2195 BUG_ON(offset_in_page(size));
2196 BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
2197 if (WARN_ON(size == 0)) {
2198 /*
2199 * Allocating 0 bytes isn't what caller wants since
2200 * get_order(0) returns funny result. Just warn and terminate
2201 * early.
2202 */
2203 return NULL;
2204 }
2205 order = get_order(size);
2206
2207 rcu_read_lock();
2208 vbq = raw_cpu_ptr(&vmap_block_queue);
2209 list_for_each_entry_rcu(vb, &vbq->free, free_list) {
2210 unsigned long pages_off;
2211
2212 if (READ_ONCE(vb->free) < (1UL << order))
2213 continue;
2214
2215 spin_lock(&vb->lock);
2216 if (vb->free < (1UL << order)) {
2217 spin_unlock(&vb->lock);
2218 continue;
2219 }
2220
2221 pages_off = VMAP_BBMAP_BITS - vb->free;
2222 vaddr = vmap_block_vaddr(vb->va->va_start, pages_off);
2223 WRITE_ONCE(vb->free, vb->free - (1UL << order));
2224 bitmap_set(vb->used_map, pages_off, (1UL << order));
2225 if (vb->free == 0) {
2226 spin_lock(&vbq->lock);
2227 list_del_rcu(&vb->free_list);
2228 spin_unlock(&vbq->lock);
2229 }
2230
2231 spin_unlock(&vb->lock);
2232 break;
2233 }
2234
2235 rcu_read_unlock();
2236
2237 /* Allocate new block if nothing was found */
2238 if (!vaddr)
2239 vaddr = new_vmap_block(order, gfp_mask);
2240
2241 return vaddr;
2242 }
2243
vb_free(unsigned long addr,unsigned long size)2244 static void vb_free(unsigned long addr, unsigned long size)
2245 {
2246 unsigned long offset;
2247 unsigned int order;
2248 struct vmap_block *vb;
2249 struct xarray *xa;
2250
2251 BUG_ON(offset_in_page(size));
2252 BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
2253
2254 flush_cache_vunmap(addr, addr + size);
2255
2256 order = get_order(size);
2257 offset = (addr & (VMAP_BLOCK_SIZE - 1)) >> PAGE_SHIFT;
2258
2259 xa = addr_to_vb_xa(addr);
2260 vb = xa_load(xa, addr_to_vb_idx(addr));
2261
2262 spin_lock(&vb->lock);
2263 bitmap_clear(vb->used_map, offset, (1UL << order));
2264 spin_unlock(&vb->lock);
2265
2266 vunmap_range_noflush(addr, addr + size);
2267
2268 if (debug_pagealloc_enabled_static())
2269 flush_tlb_kernel_range(addr, addr + size);
2270
2271 spin_lock(&vb->lock);
2272
2273 /* Expand the not yet TLB flushed dirty range */
2274 vb->dirty_min = min(vb->dirty_min, offset);
2275 vb->dirty_max = max(vb->dirty_max, offset + (1UL << order));
2276
2277 WRITE_ONCE(vb->dirty, vb->dirty + (1UL << order));
2278 if (vb->dirty == VMAP_BBMAP_BITS) {
2279 BUG_ON(vb->free);
2280 spin_unlock(&vb->lock);
2281 free_vmap_block(vb);
2282 } else
2283 spin_unlock(&vb->lock);
2284 }
2285
_vm_unmap_aliases(unsigned long start,unsigned long end,int flush)2286 static void _vm_unmap_aliases(unsigned long start, unsigned long end, int flush)
2287 {
2288 LIST_HEAD(purge_list);
2289 int cpu;
2290
2291 if (unlikely(!vmap_initialized))
2292 return;
2293
2294 mutex_lock(&vmap_purge_lock);
2295
2296 for_each_possible_cpu(cpu) {
2297 struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu);
2298 struct vmap_block *vb;
2299 unsigned long idx;
2300
2301 rcu_read_lock();
2302 xa_for_each(&vbq->vmap_blocks, idx, vb) {
2303 spin_lock(&vb->lock);
2304
2305 /*
2306 * Try to purge a fragmented block first. If it's
2307 * not purgeable, check whether there is dirty
2308 * space to be flushed.
2309 */
2310 if (!purge_fragmented_block(vb, &purge_list, false) &&
2311 vb->dirty_max && vb->dirty != VMAP_BBMAP_BITS) {
2312 unsigned long va_start = vb->va->va_start;
2313 unsigned long s, e;
2314
2315 s = va_start + (vb->dirty_min << PAGE_SHIFT);
2316 e = va_start + (vb->dirty_max << PAGE_SHIFT);
2317
2318 start = min(s, start);
2319 end = max(e, end);
2320
2321 /* Prevent that this is flushed again */
2322 vb->dirty_min = VMAP_BBMAP_BITS;
2323 vb->dirty_max = 0;
2324
2325 flush = 1;
2326 }
2327 spin_unlock(&vb->lock);
2328 }
2329 rcu_read_unlock();
2330 }
2331 free_purged_blocks(&purge_list);
2332
2333 if (!__purge_vmap_area_lazy(start, end) && flush)
2334 flush_tlb_kernel_range(start, end);
2335 mutex_unlock(&vmap_purge_lock);
2336 }
2337
2338 /**
2339 * vm_unmap_aliases - unmap outstanding lazy aliases in the vmap layer
2340 *
2341 * The vmap/vmalloc layer lazily flushes kernel virtual mappings primarily
2342 * to amortize TLB flushing overheads. What this means is that any page you
2343 * have now, may, in a former life, have been mapped into kernel virtual
2344 * address by the vmap layer and so there might be some CPUs with TLB entries
2345 * still referencing that page (additional to the regular 1:1 kernel mapping).
2346 *
2347 * vm_unmap_aliases flushes all such lazy mappings. After it returns, we can
2348 * be sure that none of the pages we have control over will have any aliases
2349 * from the vmap layer.
2350 */
vm_unmap_aliases(void)2351 void vm_unmap_aliases(void)
2352 {
2353 unsigned long start = ULONG_MAX, end = 0;
2354 int flush = 0;
2355
2356 _vm_unmap_aliases(start, end, flush);
2357 }
2358 EXPORT_SYMBOL_GPL(vm_unmap_aliases);
2359
2360 /**
2361 * vm_unmap_ram - unmap linear kernel address space set up by vm_map_ram
2362 * @mem: the pointer returned by vm_map_ram
2363 * @count: the count passed to that vm_map_ram call (cannot unmap partial)
2364 */
vm_unmap_ram(const void * mem,unsigned int count)2365 void vm_unmap_ram(const void *mem, unsigned int count)
2366 {
2367 unsigned long size = (unsigned long)count << PAGE_SHIFT;
2368 unsigned long addr = (unsigned long)kasan_reset_tag(mem);
2369 struct vmap_area *va;
2370
2371 might_sleep();
2372 BUG_ON(!addr);
2373 BUG_ON(addr < VMALLOC_START);
2374 BUG_ON(addr > VMALLOC_END);
2375 BUG_ON(!PAGE_ALIGNED(addr));
2376
2377 kasan_poison_vmalloc(mem, size);
2378
2379 if (likely(count <= VMAP_MAX_ALLOC)) {
2380 debug_check_no_locks_freed(mem, size);
2381 vb_free(addr, size);
2382 return;
2383 }
2384
2385 va = find_unlink_vmap_area(addr);
2386 if (WARN_ON_ONCE(!va))
2387 return;
2388
2389 debug_check_no_locks_freed((void *)va->va_start,
2390 (va->va_end - va->va_start));
2391
2392 if (IS_ENABLED(CONFIG_ARCH_HAS_IOREMAP_PHYS_HOOKS) && va->vm &&
2393 va->vm->flags & VM_IOREMAP)
2394 iounmap_phys_range_hook(va->vm->phys_addr, get_vm_area_size(va->vm));
2395
2396 free_unmap_vmap_area(va);
2397 }
2398 EXPORT_SYMBOL(vm_unmap_ram);
2399
2400 /**
2401 * vm_map_ram - map pages linearly into kernel virtual address (vmalloc space)
2402 * @pages: an array of pointers to the pages to be mapped
2403 * @count: number of pages
2404 * @node: prefer to allocate data structures on this node
2405 *
2406 * If you use this function for less than VMAP_MAX_ALLOC pages, it could be
2407 * faster than vmap so it's good. But if you mix long-life and short-life
2408 * objects with vm_map_ram(), it could consume lots of address space through
2409 * fragmentation (especially on a 32bit machine). You could see failures in
2410 * the end. Please use this function for short-lived objects.
2411 *
2412 * Returns: a pointer to the address that has been mapped, or %NULL on failure
2413 */
vm_map_ram(struct page ** pages,unsigned int count,int node)2414 void *vm_map_ram(struct page **pages, unsigned int count, int node)
2415 {
2416 unsigned long size = (unsigned long)count << PAGE_SHIFT;
2417 unsigned long addr;
2418 void *mem;
2419
2420 if (likely(count <= VMAP_MAX_ALLOC)) {
2421 mem = vb_alloc(size, GFP_KERNEL);
2422 if (IS_ERR(mem))
2423 return NULL;
2424 addr = (unsigned long)mem;
2425 } else {
2426 struct vmap_area *va;
2427 va = alloc_vmap_area(size, PAGE_SIZE,
2428 VMALLOC_START, VMALLOC_END,
2429 node, GFP_KERNEL, VMAP_RAM);
2430 if (IS_ERR(va))
2431 return NULL;
2432
2433 addr = va->va_start;
2434 mem = (void *)addr;
2435 }
2436
2437 if (vmap_pages_range(addr, addr + size, PAGE_KERNEL,
2438 pages, PAGE_SHIFT) < 0) {
2439 vm_unmap_ram(mem, count);
2440 return NULL;
2441 }
2442
2443 /*
2444 * Mark the pages as accessible, now that they are mapped.
2445 * With hardware tag-based KASAN, marking is skipped for
2446 * non-VM_ALLOC mappings, see __kasan_unpoison_vmalloc().
2447 */
2448 mem = kasan_unpoison_vmalloc(mem, size, KASAN_VMALLOC_PROT_NORMAL);
2449
2450 return mem;
2451 }
2452 EXPORT_SYMBOL(vm_map_ram);
2453
2454 static struct vm_struct *vmlist __initdata;
2455
vm_area_page_order(struct vm_struct * vm)2456 static inline unsigned int vm_area_page_order(struct vm_struct *vm)
2457 {
2458 #ifdef CONFIG_HAVE_ARCH_HUGE_VMALLOC
2459 return vm->page_order;
2460 #else
2461 return 0;
2462 #endif
2463 }
2464
set_vm_area_page_order(struct vm_struct * vm,unsigned int order)2465 static inline void set_vm_area_page_order(struct vm_struct *vm, unsigned int order)
2466 {
2467 #ifdef CONFIG_HAVE_ARCH_HUGE_VMALLOC
2468 vm->page_order = order;
2469 #else
2470 BUG_ON(order != 0);
2471 #endif
2472 }
2473
2474 /**
2475 * vm_area_add_early - add vmap area early during boot
2476 * @vm: vm_struct to add
2477 *
2478 * This function is used to add fixed kernel vm area to vmlist before
2479 * vmalloc_init() is called. @vm->addr, @vm->size, and @vm->flags
2480 * should contain proper values and the other fields should be zero.
2481 *
2482 * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING.
2483 */
vm_area_add_early(struct vm_struct * vm)2484 void __init vm_area_add_early(struct vm_struct *vm)
2485 {
2486 struct vm_struct *tmp, **p;
2487
2488 BUG_ON(vmap_initialized);
2489 for (p = &vmlist; (tmp = *p) != NULL; p = &tmp->next) {
2490 if (tmp->addr >= vm->addr) {
2491 BUG_ON(tmp->addr < vm->addr + vm->size);
2492 break;
2493 } else
2494 BUG_ON(tmp->addr + tmp->size > vm->addr);
2495 }
2496 vm->next = *p;
2497 *p = vm;
2498 }
2499
2500 /**
2501 * vm_area_register_early - register vmap area early during boot
2502 * @vm: vm_struct to register
2503 * @align: requested alignment
2504 *
2505 * This function is used to register kernel vm area before
2506 * vmalloc_init() is called. @vm->size and @vm->flags should contain
2507 * proper values on entry and other fields should be zero. On return,
2508 * vm->addr contains the allocated address.
2509 *
2510 * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING.
2511 */
vm_area_register_early(struct vm_struct * vm,size_t align)2512 void __init vm_area_register_early(struct vm_struct *vm, size_t align)
2513 {
2514 unsigned long addr = ALIGN(VMALLOC_START, align);
2515 struct vm_struct *cur, **p;
2516
2517 BUG_ON(vmap_initialized);
2518
2519 for (p = &vmlist; (cur = *p) != NULL; p = &cur->next) {
2520 if ((unsigned long)cur->addr - addr >= vm->size)
2521 break;
2522 addr = ALIGN((unsigned long)cur->addr + cur->size, align);
2523 }
2524
2525 BUG_ON(addr > VMALLOC_END - vm->size);
2526 vm->addr = (void *)addr;
2527 vm->next = *p;
2528 *p = vm;
2529 kasan_populate_early_vm_area_shadow(vm->addr, vm->size);
2530 }
2531
vmap_init_free_space(void)2532 static void vmap_init_free_space(void)
2533 {
2534 unsigned long vmap_start = 1;
2535 const unsigned long vmap_end = ULONG_MAX;
2536 struct vmap_area *busy, *free;
2537
2538 /*
2539 * B F B B B F
2540 * -|-----|.....|-----|-----|-----|.....|-
2541 * | The KVA space |
2542 * |<--------------------------------->|
2543 */
2544 list_for_each_entry(busy, &vmap_area_list, list) {
2545 if (busy->va_start - vmap_start > 0) {
2546 free = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
2547 if (!WARN_ON_ONCE(!free)) {
2548 free->va_start = vmap_start;
2549 free->va_end = busy->va_start;
2550
2551 insert_vmap_area_augment(free, NULL,
2552 &free_vmap_area_root,
2553 &free_vmap_area_list);
2554 }
2555 }
2556
2557 vmap_start = busy->va_end;
2558 }
2559
2560 if (vmap_end - vmap_start > 0) {
2561 free = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
2562 if (!WARN_ON_ONCE(!free)) {
2563 free->va_start = vmap_start;
2564 free->va_end = vmap_end;
2565
2566 insert_vmap_area_augment(free, NULL,
2567 &free_vmap_area_root,
2568 &free_vmap_area_list);
2569 }
2570 }
2571 }
2572
setup_vmalloc_vm_locked(struct vm_struct * vm,struct vmap_area * va,unsigned long flags,const void * caller)2573 static inline void setup_vmalloc_vm_locked(struct vm_struct *vm,
2574 struct vmap_area *va, unsigned long flags, const void *caller)
2575 {
2576 vm->flags = flags;
2577 vm->addr = (void *)va->va_start;
2578 vm->size = va->va_end - va->va_start;
2579 vm->caller = caller;
2580 va->vm = vm;
2581 trace_android_vh_save_vmalloc_stack(flags, vm);
2582 }
2583
setup_vmalloc_vm(struct vm_struct * vm,struct vmap_area * va,unsigned long flags,const void * caller)2584 static void setup_vmalloc_vm(struct vm_struct *vm, struct vmap_area *va,
2585 unsigned long flags, const void *caller)
2586 {
2587 spin_lock(&vmap_area_lock);
2588 setup_vmalloc_vm_locked(vm, va, flags, caller);
2589 spin_unlock(&vmap_area_lock);
2590 }
2591
clear_vm_uninitialized_flag(struct vm_struct * vm)2592 static void clear_vm_uninitialized_flag(struct vm_struct *vm)
2593 {
2594 /*
2595 * Before removing VM_UNINITIALIZED,
2596 * we should make sure that vm has proper values.
2597 * Pair with smp_rmb() in show_numa_info().
2598 */
2599 smp_wmb();
2600 vm->flags &= ~VM_UNINITIALIZED;
2601 }
2602
__get_vm_area_node(unsigned long size,unsigned long align,unsigned long shift,unsigned long flags,unsigned long start,unsigned long end,int node,gfp_t gfp_mask,const void * caller)2603 static struct vm_struct *__get_vm_area_node(unsigned long size,
2604 unsigned long align, unsigned long shift, unsigned long flags,
2605 unsigned long start, unsigned long end, int node,
2606 gfp_t gfp_mask, const void *caller)
2607 {
2608 struct vmap_area *va;
2609 struct vm_struct *area;
2610 unsigned long requested_size = size;
2611
2612 BUG_ON(in_interrupt());
2613 size = ALIGN(size, 1ul << shift);
2614 if (unlikely(!size))
2615 return NULL;
2616
2617 if (flags & VM_IOREMAP)
2618 align = 1ul << clamp_t(int, get_count_order_long(size),
2619 PAGE_SHIFT, IOREMAP_MAX_ORDER);
2620
2621 area = kzalloc_node(sizeof(*area), gfp_mask & GFP_RECLAIM_MASK, node);
2622 if (unlikely(!area))
2623 return NULL;
2624
2625 if (!(flags & VM_NO_GUARD))
2626 size += PAGE_SIZE;
2627
2628 va = alloc_vmap_area(size, align, start, end, node, gfp_mask, 0);
2629 if (IS_ERR(va)) {
2630 kfree(area);
2631 return NULL;
2632 }
2633
2634 setup_vmalloc_vm(area, va, flags, caller);
2635
2636 /*
2637 * Mark pages for non-VM_ALLOC mappings as accessible. Do it now as a
2638 * best-effort approach, as they can be mapped outside of vmalloc code.
2639 * For VM_ALLOC mappings, the pages are marked as accessible after
2640 * getting mapped in __vmalloc_node_range().
2641 * With hardware tag-based KASAN, marking is skipped for
2642 * non-VM_ALLOC mappings, see __kasan_unpoison_vmalloc().
2643 */
2644 if (!(flags & VM_ALLOC))
2645 area->addr = kasan_unpoison_vmalloc(area->addr, requested_size,
2646 KASAN_VMALLOC_PROT_NORMAL);
2647
2648 return area;
2649 }
2650
__get_vm_area_caller(unsigned long size,unsigned long flags,unsigned long start,unsigned long end,const void * caller)2651 struct vm_struct *__get_vm_area_caller(unsigned long size, unsigned long flags,
2652 unsigned long start, unsigned long end,
2653 const void *caller)
2654 {
2655 return __get_vm_area_node(size, 1, PAGE_SHIFT, flags, start, end,
2656 NUMA_NO_NODE, GFP_KERNEL, caller);
2657 }
2658
2659 /**
2660 * get_vm_area - reserve a contiguous kernel virtual area
2661 * @size: size of the area
2662 * @flags: %VM_IOREMAP for I/O mappings or VM_ALLOC
2663 *
2664 * Search an area of @size in the kernel virtual mapping area,
2665 * and reserved it for out purposes. Returns the area descriptor
2666 * on success or %NULL on failure.
2667 *
2668 * Return: the area descriptor on success or %NULL on failure.
2669 */
get_vm_area(unsigned long size,unsigned long flags)2670 struct vm_struct *get_vm_area(unsigned long size, unsigned long flags)
2671 {
2672 return __get_vm_area_node(size, 1, PAGE_SHIFT, flags,
2673 VMALLOC_START, VMALLOC_END,
2674 NUMA_NO_NODE, GFP_KERNEL,
2675 __builtin_return_address(0));
2676 }
2677
get_vm_area_caller(unsigned long size,unsigned long flags,const void * caller)2678 struct vm_struct *get_vm_area_caller(unsigned long size, unsigned long flags,
2679 const void *caller)
2680 {
2681 return __get_vm_area_node(size, 1, PAGE_SHIFT, flags,
2682 VMALLOC_START, VMALLOC_END,
2683 NUMA_NO_NODE, GFP_KERNEL, caller);
2684 }
2685
2686 /**
2687 * find_vm_area - find a continuous kernel virtual area
2688 * @addr: base address
2689 *
2690 * Search for the kernel VM area starting at @addr, and return it.
2691 * It is up to the caller to do all required locking to keep the returned
2692 * pointer valid.
2693 *
2694 * Return: the area descriptor on success or %NULL on failure.
2695 */
find_vm_area(const void * addr)2696 struct vm_struct *find_vm_area(const void *addr)
2697 {
2698 struct vmap_area *va;
2699
2700 va = find_vmap_area((unsigned long)addr);
2701 if (!va)
2702 return NULL;
2703
2704 return va->vm;
2705 }
2706 EXPORT_SYMBOL_GPL(find_vm_area);
2707
2708 /**
2709 * remove_vm_area - find and remove a continuous kernel virtual area
2710 * @addr: base address
2711 *
2712 * Search for the kernel VM area starting at @addr, and remove it.
2713 * This function returns the found VM area, but using it is NOT safe
2714 * on SMP machines, except for its size or flags.
2715 *
2716 * Return: the area descriptor on success or %NULL on failure.
2717 */
remove_vm_area(const void * addr)2718 struct vm_struct *remove_vm_area(const void *addr)
2719 {
2720 struct vmap_area *va;
2721 struct vm_struct *vm;
2722
2723 might_sleep();
2724
2725 if (WARN(!PAGE_ALIGNED(addr), "Trying to vfree() bad address (%p)\n",
2726 addr))
2727 return NULL;
2728
2729 va = find_unlink_vmap_area((unsigned long)addr);
2730 if (!va || !va->vm)
2731 return NULL;
2732 vm = va->vm;
2733
2734 debug_check_no_locks_freed(vm->addr, get_vm_area_size(vm));
2735 debug_check_no_obj_freed(vm->addr, get_vm_area_size(vm));
2736 kasan_free_module_shadow(vm);
2737 kasan_poison_vmalloc(vm->addr, get_vm_area_size(vm));
2738
2739 free_unmap_vmap_area(va);
2740 return vm;
2741 }
2742
set_area_direct_map(const struct vm_struct * area,int (* set_direct_map)(struct page * page))2743 static inline void set_area_direct_map(const struct vm_struct *area,
2744 int (*set_direct_map)(struct page *page))
2745 {
2746 int i;
2747
2748 /* HUGE_VMALLOC passes small pages to set_direct_map */
2749 for (i = 0; i < area->nr_pages; i++)
2750 if (page_address(area->pages[i]))
2751 set_direct_map(area->pages[i]);
2752 }
2753
2754 /*
2755 * Flush the vm mapping and reset the direct map.
2756 */
vm_reset_perms(struct vm_struct * area)2757 static void vm_reset_perms(struct vm_struct *area)
2758 {
2759 unsigned long start = ULONG_MAX, end = 0;
2760 unsigned int page_order = vm_area_page_order(area);
2761 int flush_dmap = 0;
2762 int i;
2763
2764 /*
2765 * Find the start and end range of the direct mappings to make sure that
2766 * the vm_unmap_aliases() flush includes the direct map.
2767 */
2768 for (i = 0; i < area->nr_pages; i += 1U << page_order) {
2769 unsigned long addr = (unsigned long)page_address(area->pages[i]);
2770
2771 if (addr) {
2772 unsigned long page_size;
2773
2774 page_size = PAGE_SIZE << page_order;
2775 start = min(addr, start);
2776 end = max(addr + page_size, end);
2777 flush_dmap = 1;
2778 }
2779 }
2780
2781 /*
2782 * Set direct map to something invalid so that it won't be cached if
2783 * there are any accesses after the TLB flush, then flush the TLB and
2784 * reset the direct map permissions to the default.
2785 */
2786 set_area_direct_map(area, set_direct_map_invalid_noflush);
2787 _vm_unmap_aliases(start, end, flush_dmap);
2788 set_area_direct_map(area, set_direct_map_default_noflush);
2789 }
2790
delayed_vfree_work(struct work_struct * w)2791 static void delayed_vfree_work(struct work_struct *w)
2792 {
2793 struct vfree_deferred *p = container_of(w, struct vfree_deferred, wq);
2794 struct llist_node *t, *llnode;
2795
2796 llist_for_each_safe(llnode, t, llist_del_all(&p->list))
2797 vfree(llnode);
2798 }
2799
2800 /**
2801 * vfree_atomic - release memory allocated by vmalloc()
2802 * @addr: memory base address
2803 *
2804 * This one is just like vfree() but can be called in any atomic context
2805 * except NMIs.
2806 */
vfree_atomic(const void * addr)2807 void vfree_atomic(const void *addr)
2808 {
2809 struct vfree_deferred *p = raw_cpu_ptr(&vfree_deferred);
2810
2811 BUG_ON(in_nmi());
2812 kmemleak_free(addr);
2813
2814 /*
2815 * Use raw_cpu_ptr() because this can be called from preemptible
2816 * context. Preemption is absolutely fine here, because the llist_add()
2817 * implementation is lockless, so it works even if we are adding to
2818 * another cpu's list. schedule_work() should be fine with this too.
2819 */
2820 if (addr && llist_add((struct llist_node *)addr, &p->list))
2821 schedule_work(&p->wq);
2822 }
2823
2824 /**
2825 * vfree - Release memory allocated by vmalloc()
2826 * @addr: Memory base address
2827 *
2828 * Free the virtually continuous memory area starting at @addr, as obtained
2829 * from one of the vmalloc() family of APIs. This will usually also free the
2830 * physical memory underlying the virtual allocation, but that memory is
2831 * reference counted, so it will not be freed until the last user goes away.
2832 *
2833 * If @addr is NULL, no operation is performed.
2834 *
2835 * Context:
2836 * May sleep if called *not* from interrupt context.
2837 * Must not be called in NMI context (strictly speaking, it could be
2838 * if we have CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG, but making the calling
2839 * conventions for vfree() arch-dependent would be a really bad idea).
2840 */
vfree(const void * addr)2841 void vfree(const void *addr)
2842 {
2843 struct vm_struct *vm;
2844 int i;
2845
2846 if (unlikely(in_interrupt())) {
2847 vfree_atomic(addr);
2848 return;
2849 }
2850
2851 BUG_ON(in_nmi());
2852 kmemleak_free(addr);
2853 might_sleep();
2854
2855 if (!addr)
2856 return;
2857
2858 vm = remove_vm_area(addr);
2859 if (unlikely(!vm)) {
2860 WARN(1, KERN_ERR "Trying to vfree() nonexistent vm area (%p)\n",
2861 addr);
2862 return;
2863 }
2864
2865 if (unlikely(vm->flags & VM_FLUSH_RESET_PERMS))
2866 vm_reset_perms(vm);
2867 for (i = 0; i < vm->nr_pages; i++) {
2868 struct page *page = vm->pages[i];
2869
2870 BUG_ON(!page);
2871 mod_memcg_page_state(page, MEMCG_VMALLOC, -1);
2872 /*
2873 * High-order allocs for huge vmallocs are split, so
2874 * can be freed as an array of order-0 allocations
2875 */
2876 __free_page(page);
2877 cond_resched();
2878 }
2879 atomic_long_sub(vm->nr_pages, &nr_vmalloc_pages);
2880 kvfree(vm->pages);
2881 kfree(vm);
2882 }
2883 EXPORT_SYMBOL(vfree);
2884
2885 /**
2886 * vunmap - release virtual mapping obtained by vmap()
2887 * @addr: memory base address
2888 *
2889 * Free the virtually contiguous memory area starting at @addr,
2890 * which was created from the page array passed to vmap().
2891 *
2892 * Must not be called in interrupt context.
2893 */
vunmap(const void * addr)2894 void vunmap(const void *addr)
2895 {
2896 struct vm_struct *vm;
2897
2898 BUG_ON(in_interrupt());
2899 might_sleep();
2900
2901 if (!addr)
2902 return;
2903 vm = remove_vm_area(addr);
2904 if (unlikely(!vm)) {
2905 WARN(1, KERN_ERR "Trying to vunmap() nonexistent vm area (%p)\n",
2906 addr);
2907 return;
2908 }
2909 kfree(vm);
2910 }
2911 EXPORT_SYMBOL(vunmap);
2912
2913 /**
2914 * vmap - map an array of pages into virtually contiguous space
2915 * @pages: array of page pointers
2916 * @count: number of pages to map
2917 * @flags: vm_area->flags
2918 * @prot: page protection for the mapping
2919 *
2920 * Maps @count pages from @pages into contiguous kernel virtual space.
2921 * If @flags contains %VM_MAP_PUT_PAGES the ownership of the pages array itself
2922 * (which must be kmalloc or vmalloc memory) and one reference per pages in it
2923 * are transferred from the caller to vmap(), and will be freed / dropped when
2924 * vfree() is called on the return value.
2925 *
2926 * Return: the address of the area or %NULL on failure
2927 */
vmap(struct page ** pages,unsigned int count,unsigned long flags,pgprot_t prot)2928 void *vmap(struct page **pages, unsigned int count,
2929 unsigned long flags, pgprot_t prot)
2930 {
2931 struct vm_struct *area;
2932 unsigned long addr;
2933 unsigned long size; /* In bytes */
2934
2935 might_sleep();
2936
2937 if (WARN_ON_ONCE(flags & VM_FLUSH_RESET_PERMS))
2938 return NULL;
2939
2940 /*
2941 * Your top guard is someone else's bottom guard. Not having a top
2942 * guard compromises someone else's mappings too.
2943 */
2944 if (WARN_ON_ONCE(flags & VM_NO_GUARD))
2945 flags &= ~VM_NO_GUARD;
2946
2947 if (count > totalram_pages())
2948 return NULL;
2949
2950 size = (unsigned long)count << PAGE_SHIFT;
2951 area = get_vm_area_caller(size, flags, __builtin_return_address(0));
2952 if (!area)
2953 return NULL;
2954
2955 addr = (unsigned long)area->addr;
2956 if (vmap_pages_range(addr, addr + size, pgprot_nx(prot),
2957 pages, PAGE_SHIFT) < 0) {
2958 vunmap(area->addr);
2959 return NULL;
2960 }
2961
2962 if (flags & VM_MAP_PUT_PAGES) {
2963 area->pages = pages;
2964 area->nr_pages = count;
2965 }
2966 return area->addr;
2967 }
2968 EXPORT_SYMBOL(vmap);
2969
2970 #ifdef CONFIG_VMAP_PFN
2971 struct vmap_pfn_data {
2972 unsigned long *pfns;
2973 pgprot_t prot;
2974 unsigned int idx;
2975 };
2976
vmap_pfn_apply(pte_t * pte,unsigned long addr,void * private)2977 static int vmap_pfn_apply(pte_t *pte, unsigned long addr, void *private)
2978 {
2979 struct vmap_pfn_data *data = private;
2980 unsigned long pfn = data->pfns[data->idx];
2981 pte_t ptent;
2982
2983 if (WARN_ON_ONCE(pfn_valid(pfn)))
2984 return -EINVAL;
2985
2986 ptent = pte_mkspecial(pfn_pte(pfn, data->prot));
2987 set_pte_at(&init_mm, addr, pte, ptent);
2988
2989 data->idx++;
2990 return 0;
2991 }
2992
2993 /**
2994 * vmap_pfn - map an array of PFNs into virtually contiguous space
2995 * @pfns: array of PFNs
2996 * @count: number of pages to map
2997 * @prot: page protection for the mapping
2998 *
2999 * Maps @count PFNs from @pfns into contiguous kernel virtual space and returns
3000 * the start address of the mapping.
3001 */
vmap_pfn(unsigned long * pfns,unsigned int count,pgprot_t prot)3002 void *vmap_pfn(unsigned long *pfns, unsigned int count, pgprot_t prot)
3003 {
3004 struct vmap_pfn_data data = { .pfns = pfns, .prot = pgprot_nx(prot) };
3005 struct vm_struct *area;
3006
3007 area = get_vm_area_caller(count * PAGE_SIZE, VM_IOREMAP,
3008 __builtin_return_address(0));
3009 if (!area)
3010 return NULL;
3011 if (apply_to_page_range(&init_mm, (unsigned long)area->addr,
3012 count * PAGE_SIZE, vmap_pfn_apply, &data)) {
3013 free_vm_area(area);
3014 return NULL;
3015 }
3016
3017 flush_cache_vmap((unsigned long)area->addr,
3018 (unsigned long)area->addr + count * PAGE_SIZE);
3019
3020 return area->addr;
3021 }
3022 EXPORT_SYMBOL_GPL(vmap_pfn);
3023 #endif /* CONFIG_VMAP_PFN */
3024
3025 static inline unsigned int
vm_area_alloc_pages(gfp_t gfp,int nid,unsigned int order,unsigned int nr_pages,struct page ** pages)3026 vm_area_alloc_pages(gfp_t gfp, int nid,
3027 unsigned int order, unsigned int nr_pages, struct page **pages)
3028 {
3029 unsigned int nr_allocated = 0;
3030 gfp_t alloc_gfp = gfp;
3031 bool nofail = gfp & __GFP_NOFAIL;
3032 struct page *page;
3033 int i;
3034
3035 /*
3036 * For order-0 pages we make use of bulk allocator, if
3037 * the page array is partly or not at all populated due
3038 * to fails, fallback to a single page allocator that is
3039 * more permissive.
3040 */
3041 if (!order) {
3042 /* bulk allocator doesn't support nofail req. officially */
3043 gfp_t bulk_gfp = gfp & ~__GFP_NOFAIL;
3044
3045 while (nr_allocated < nr_pages) {
3046 unsigned int nr, nr_pages_request;
3047
3048 /*
3049 * A maximum allowed request is hard-coded and is 100
3050 * pages per call. That is done in order to prevent a
3051 * long preemption off scenario in the bulk-allocator
3052 * so the range is [1:100].
3053 */
3054 nr_pages_request = min(100U, nr_pages - nr_allocated);
3055
3056 /* memory allocation should consider mempolicy, we can't
3057 * wrongly use nearest node when nid == NUMA_NO_NODE,
3058 * otherwise memory may be allocated in only one node,
3059 * but mempolicy wants to alloc memory by interleaving.
3060 */
3061 if (IS_ENABLED(CONFIG_NUMA) && nid == NUMA_NO_NODE)
3062 nr = alloc_pages_bulk_array_mempolicy(bulk_gfp,
3063 nr_pages_request,
3064 pages + nr_allocated);
3065
3066 else
3067 nr = alloc_pages_bulk_array_node(bulk_gfp, nid,
3068 nr_pages_request,
3069 pages + nr_allocated);
3070
3071 nr_allocated += nr;
3072 cond_resched();
3073
3074 /*
3075 * If zero or pages were obtained partly,
3076 * fallback to a single page allocator.
3077 */
3078 if (nr != nr_pages_request)
3079 break;
3080 }
3081 } else if (gfp & __GFP_NOFAIL) {
3082 /*
3083 * Higher order nofail allocations are really expensive and
3084 * potentially dangerous (pre-mature OOM, disruptive reclaim
3085 * and compaction etc.
3086 */
3087 alloc_gfp &= ~__GFP_NOFAIL;
3088 }
3089
3090 /* High-order pages or fallback path if "bulk" fails. */
3091 while (nr_allocated < nr_pages) {
3092 if (!nofail && fatal_signal_pending(current))
3093 break;
3094
3095 if (nid == NUMA_NO_NODE)
3096 page = alloc_pages(alloc_gfp, order);
3097 else
3098 page = alloc_pages_node(nid, alloc_gfp, order);
3099 if (unlikely(!page))
3100 break;
3101
3102 /*
3103 * Higher order allocations must be able to be treated as
3104 * indepdenent small pages by callers (as they can with
3105 * small-page vmallocs). Some drivers do their own refcounting
3106 * on vmalloc_to_page() pages, some use page->mapping,
3107 * page->lru, etc.
3108 */
3109 if (order)
3110 split_page(page, order);
3111
3112 /*
3113 * Careful, we allocate and map page-order pages, but
3114 * tracking is done per PAGE_SIZE page so as to keep the
3115 * vm_struct APIs independent of the physical/mapped size.
3116 */
3117 for (i = 0; i < (1U << order); i++)
3118 pages[nr_allocated + i] = page + i;
3119
3120 cond_resched();
3121 nr_allocated += 1U << order;
3122 }
3123
3124 return nr_allocated;
3125 }
3126
__vmalloc_area_node(struct vm_struct * area,gfp_t gfp_mask,pgprot_t prot,unsigned int page_shift,int node)3127 static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask,
3128 pgprot_t prot, unsigned int page_shift,
3129 int node)
3130 {
3131 const gfp_t nested_gfp = (gfp_mask & GFP_RECLAIM_MASK) | __GFP_ZERO;
3132 bool nofail = gfp_mask & __GFP_NOFAIL;
3133 unsigned long addr = (unsigned long)area->addr;
3134 unsigned long size = get_vm_area_size(area);
3135 unsigned long array_size;
3136 unsigned int nr_small_pages = size >> PAGE_SHIFT;
3137 unsigned int page_order;
3138 unsigned int flags;
3139 int ret;
3140
3141 array_size = (unsigned long)nr_small_pages * sizeof(struct page *);
3142
3143 if (!(gfp_mask & (GFP_DMA | GFP_DMA32)))
3144 gfp_mask |= __GFP_HIGHMEM;
3145
3146 /* Please note that the recursion is strictly bounded. */
3147 if (array_size > PAGE_SIZE) {
3148 area->pages = __vmalloc_node(array_size, 1, nested_gfp, node,
3149 area->caller);
3150 } else {
3151 area->pages = kmalloc_node(array_size, nested_gfp, node);
3152 }
3153
3154 if (!area->pages) {
3155 warn_alloc(gfp_mask, NULL,
3156 "vmalloc error: size %lu, failed to allocated page array size %lu",
3157 nr_small_pages * PAGE_SIZE, array_size);
3158 free_vm_area(area);
3159 return NULL;
3160 }
3161
3162 set_vm_area_page_order(area, page_shift - PAGE_SHIFT);
3163 page_order = vm_area_page_order(area);
3164
3165 area->nr_pages = vm_area_alloc_pages(gfp_mask | __GFP_NOWARN,
3166 node, page_order, nr_small_pages, area->pages);
3167
3168 atomic_long_add(area->nr_pages, &nr_vmalloc_pages);
3169 if (gfp_mask & __GFP_ACCOUNT) {
3170 int i;
3171
3172 for (i = 0; i < area->nr_pages; i++)
3173 mod_memcg_page_state(area->pages[i], MEMCG_VMALLOC, 1);
3174 }
3175
3176 /*
3177 * If not enough pages were obtained to accomplish an
3178 * allocation request, free them via vfree() if any.
3179 */
3180 if (area->nr_pages != nr_small_pages) {
3181 /*
3182 * vm_area_alloc_pages() can fail due to insufficient memory but
3183 * also:-
3184 *
3185 * - a pending fatal signal
3186 * - insufficient huge page-order pages
3187 *
3188 * Since we always retry allocations at order-0 in the huge page
3189 * case a warning for either is spurious.
3190 */
3191 if (!fatal_signal_pending(current) && page_order == 0)
3192 warn_alloc(gfp_mask, NULL,
3193 "vmalloc error: size %lu, failed to allocate pages",
3194 area->nr_pages * PAGE_SIZE);
3195 goto fail;
3196 }
3197
3198 /*
3199 * page tables allocations ignore external gfp mask, enforce it
3200 * by the scope API
3201 */
3202 if ((gfp_mask & (__GFP_FS | __GFP_IO)) == __GFP_IO)
3203 flags = memalloc_nofs_save();
3204 else if ((gfp_mask & (__GFP_FS | __GFP_IO)) == 0)
3205 flags = memalloc_noio_save();
3206
3207 do {
3208 ret = vmap_pages_range(addr, addr + size, prot, area->pages,
3209 page_shift);
3210 if (nofail && (ret < 0))
3211 schedule_timeout_uninterruptible(1);
3212 } while (nofail && (ret < 0));
3213
3214 if ((gfp_mask & (__GFP_FS | __GFP_IO)) == __GFP_IO)
3215 memalloc_nofs_restore(flags);
3216 else if ((gfp_mask & (__GFP_FS | __GFP_IO)) == 0)
3217 memalloc_noio_restore(flags);
3218
3219 if (ret < 0) {
3220 warn_alloc(gfp_mask, NULL,
3221 "vmalloc error: size %lu, failed to map pages",
3222 area->nr_pages * PAGE_SIZE);
3223 goto fail;
3224 }
3225
3226 return area->addr;
3227
3228 fail:
3229 vfree(area->addr);
3230 return NULL;
3231 }
3232
3233 /**
3234 * __vmalloc_node_range - allocate virtually contiguous memory
3235 * @size: allocation size
3236 * @align: desired alignment
3237 * @start: vm area range start
3238 * @end: vm area range end
3239 * @gfp_mask: flags for the page level allocator
3240 * @prot: protection mask for the allocated pages
3241 * @vm_flags: additional vm area flags (e.g. %VM_NO_GUARD)
3242 * @node: node to use for allocation or NUMA_NO_NODE
3243 * @caller: caller's return address
3244 *
3245 * Allocate enough pages to cover @size from the page level
3246 * allocator with @gfp_mask flags. Please note that the full set of gfp
3247 * flags are not supported. GFP_KERNEL, GFP_NOFS and GFP_NOIO are all
3248 * supported.
3249 * Zone modifiers are not supported. From the reclaim modifiers
3250 * __GFP_DIRECT_RECLAIM is required (aka GFP_NOWAIT is not supported)
3251 * and only __GFP_NOFAIL is supported (i.e. __GFP_NORETRY and
3252 * __GFP_RETRY_MAYFAIL are not supported).
3253 *
3254 * __GFP_NOWARN can be used to suppress failures messages.
3255 *
3256 * Map them into contiguous kernel virtual space, using a pagetable
3257 * protection of @prot.
3258 *
3259 * Return: the address of the area or %NULL on failure
3260 */
__vmalloc_node_range(unsigned long size,unsigned long align,unsigned long start,unsigned long end,gfp_t gfp_mask,pgprot_t prot,unsigned long vm_flags,int node,const void * caller)3261 void *__vmalloc_node_range(unsigned long size, unsigned long align,
3262 unsigned long start, unsigned long end, gfp_t gfp_mask,
3263 pgprot_t prot, unsigned long vm_flags, int node,
3264 const void *caller)
3265 {
3266 struct vm_struct *area;
3267 void *ret;
3268 kasan_vmalloc_flags_t kasan_flags = KASAN_VMALLOC_NONE;
3269 unsigned long real_size = size;
3270 unsigned long real_align = align;
3271 unsigned int shift = PAGE_SHIFT;
3272
3273 if (WARN_ON_ONCE(!size))
3274 return NULL;
3275
3276 if ((size >> PAGE_SHIFT) > totalram_pages()) {
3277 warn_alloc(gfp_mask, NULL,
3278 "vmalloc error: size %lu, exceeds total pages",
3279 real_size);
3280 return NULL;
3281 }
3282
3283 if (vmap_allow_huge && (vm_flags & VM_ALLOW_HUGE_VMAP)) {
3284 unsigned long size_per_node;
3285
3286 /*
3287 * Try huge pages. Only try for PAGE_KERNEL allocations,
3288 * others like modules don't yet expect huge pages in
3289 * their allocations due to apply_to_page_range not
3290 * supporting them.
3291 */
3292
3293 size_per_node = size;
3294 if (node == NUMA_NO_NODE)
3295 size_per_node /= num_online_nodes();
3296 if (arch_vmap_pmd_supported(prot) && size_per_node >= PMD_SIZE)
3297 shift = PMD_SHIFT;
3298 else
3299 shift = arch_vmap_pte_supported_shift(size_per_node);
3300
3301 align = max(real_align, 1UL << shift);
3302 size = ALIGN(real_size, 1UL << shift);
3303 }
3304
3305 again:
3306 area = __get_vm_area_node(real_size, align, shift, VM_ALLOC |
3307 VM_UNINITIALIZED | vm_flags, start, end, node,
3308 gfp_mask, caller);
3309 if (!area) {
3310 bool nofail = gfp_mask & __GFP_NOFAIL;
3311 warn_alloc(gfp_mask, NULL,
3312 "vmalloc error: size %lu, vm_struct allocation failed%s",
3313 real_size, (nofail) ? ". Retrying." : "");
3314 if (nofail) {
3315 schedule_timeout_uninterruptible(1);
3316 goto again;
3317 }
3318 goto fail;
3319 }
3320
3321 /*
3322 * Prepare arguments for __vmalloc_area_node() and
3323 * kasan_unpoison_vmalloc().
3324 */
3325 if (pgprot_val(prot) == pgprot_val(PAGE_KERNEL)) {
3326 if (kasan_hw_tags_enabled()) {
3327 /*
3328 * Modify protection bits to allow tagging.
3329 * This must be done before mapping.
3330 */
3331 prot = arch_vmap_pgprot_tagged(prot);
3332
3333 /*
3334 * Skip page_alloc poisoning and zeroing for physical
3335 * pages backing VM_ALLOC mapping. Memory is instead
3336 * poisoned and zeroed by kasan_unpoison_vmalloc().
3337 */
3338 gfp_mask |= __GFP_SKIP_KASAN | __GFP_SKIP_ZERO;
3339 }
3340
3341 /* Take note that the mapping is PAGE_KERNEL. */
3342 kasan_flags |= KASAN_VMALLOC_PROT_NORMAL;
3343 }
3344
3345 /* Allocate physical pages and map them into vmalloc space. */
3346 ret = __vmalloc_area_node(area, gfp_mask, prot, shift, node);
3347 if (!ret)
3348 goto fail;
3349
3350 /*
3351 * Mark the pages as accessible, now that they are mapped.
3352 * The condition for setting KASAN_VMALLOC_INIT should complement the
3353 * one in post_alloc_hook() with regards to the __GFP_SKIP_ZERO check
3354 * to make sure that memory is initialized under the same conditions.
3355 * Tag-based KASAN modes only assign tags to normal non-executable
3356 * allocations, see __kasan_unpoison_vmalloc().
3357 */
3358 kasan_flags |= KASAN_VMALLOC_VM_ALLOC;
3359 if (!want_init_on_free() && want_init_on_alloc(gfp_mask) &&
3360 (gfp_mask & __GFP_SKIP_ZERO))
3361 kasan_flags |= KASAN_VMALLOC_INIT;
3362 /* KASAN_VMALLOC_PROT_NORMAL already set if required. */
3363 area->addr = kasan_unpoison_vmalloc(area->addr, real_size, kasan_flags);
3364
3365 /*
3366 * In this function, newly allocated vm_struct has VM_UNINITIALIZED
3367 * flag. It means that vm_struct is not fully initialized.
3368 * Now, it is fully initialized, so remove this flag here.
3369 */
3370 clear_vm_uninitialized_flag(area);
3371
3372 size = PAGE_ALIGN(size);
3373 if (!(vm_flags & VM_DEFER_KMEMLEAK))
3374 kmemleak_vmalloc(area, size, gfp_mask);
3375
3376 return area->addr;
3377
3378 fail:
3379 if (shift > PAGE_SHIFT) {
3380 shift = PAGE_SHIFT;
3381 align = real_align;
3382 size = real_size;
3383 goto again;
3384 }
3385
3386 return NULL;
3387 }
3388
3389 /**
3390 * __vmalloc_node - allocate virtually contiguous memory
3391 * @size: allocation size
3392 * @align: desired alignment
3393 * @gfp_mask: flags for the page level allocator
3394 * @node: node to use for allocation or NUMA_NO_NODE
3395 * @caller: caller's return address
3396 *
3397 * Allocate enough pages to cover @size from the page level allocator with
3398 * @gfp_mask flags. Map them into contiguous kernel virtual space.
3399 *
3400 * Reclaim modifiers in @gfp_mask - __GFP_NORETRY, __GFP_RETRY_MAYFAIL
3401 * and __GFP_NOFAIL are not supported
3402 *
3403 * Any use of gfp flags outside of GFP_KERNEL should be consulted
3404 * with mm people.
3405 *
3406 * Return: pointer to the allocated memory or %NULL on error
3407 */
__vmalloc_node(unsigned long size,unsigned long align,gfp_t gfp_mask,int node,const void * caller)3408 void *__vmalloc_node(unsigned long size, unsigned long align,
3409 gfp_t gfp_mask, int node, const void *caller)
3410 {
3411 return __vmalloc_node_range(size, align, VMALLOC_START, VMALLOC_END,
3412 gfp_mask, PAGE_KERNEL, 0, node, caller);
3413 }
3414 /*
3415 * This is only for performance analysis of vmalloc and stress purpose.
3416 * It is required by vmalloc test module, therefore do not use it other
3417 * than that.
3418 */
3419 #ifdef CONFIG_TEST_VMALLOC_MODULE
3420 EXPORT_SYMBOL_GPL(__vmalloc_node);
3421 #endif
3422
__vmalloc(unsigned long size,gfp_t gfp_mask)3423 void *__vmalloc(unsigned long size, gfp_t gfp_mask)
3424 {
3425 return __vmalloc_node(size, 1, gfp_mask, NUMA_NO_NODE,
3426 __builtin_return_address(0));
3427 }
3428 EXPORT_SYMBOL(__vmalloc);
3429
3430 /**
3431 * vmalloc - allocate virtually contiguous memory
3432 * @size: allocation size
3433 *
3434 * Allocate enough pages to cover @size from the page level
3435 * allocator and map them into contiguous kernel virtual space.
3436 *
3437 * For tight control over page level allocator and protection flags
3438 * use __vmalloc() instead.
3439 *
3440 * Return: pointer to the allocated memory or %NULL on error
3441 */
vmalloc(unsigned long size)3442 void *vmalloc(unsigned long size)
3443 {
3444 return __vmalloc_node(size, 1, GFP_KERNEL, NUMA_NO_NODE,
3445 __builtin_return_address(0));
3446 }
3447 EXPORT_SYMBOL(vmalloc);
3448
3449 /**
3450 * vmalloc_huge - allocate virtually contiguous memory, allow huge pages
3451 * @size: allocation size
3452 * @gfp_mask: flags for the page level allocator
3453 *
3454 * Allocate enough pages to cover @size from the page level
3455 * allocator and map them into contiguous kernel virtual space.
3456 * If @size is greater than or equal to PMD_SIZE, allow using
3457 * huge pages for the memory
3458 *
3459 * Return: pointer to the allocated memory or %NULL on error
3460 */
vmalloc_huge(unsigned long size,gfp_t gfp_mask)3461 void *vmalloc_huge(unsigned long size, gfp_t gfp_mask)
3462 {
3463 return __vmalloc_node_range(size, 1, VMALLOC_START, VMALLOC_END,
3464 gfp_mask, PAGE_KERNEL, VM_ALLOW_HUGE_VMAP,
3465 NUMA_NO_NODE, __builtin_return_address(0));
3466 }
3467 EXPORT_SYMBOL_GPL(vmalloc_huge);
3468
3469 /**
3470 * vzalloc - allocate virtually contiguous memory with zero fill
3471 * @size: allocation size
3472 *
3473 * Allocate enough pages to cover @size from the page level
3474 * allocator and map them into contiguous kernel virtual space.
3475 * The memory allocated is set to zero.
3476 *
3477 * For tight control over page level allocator and protection flags
3478 * use __vmalloc() instead.
3479 *
3480 * Return: pointer to the allocated memory or %NULL on error
3481 */
vzalloc(unsigned long size)3482 void *vzalloc(unsigned long size)
3483 {
3484 return __vmalloc_node(size, 1, GFP_KERNEL | __GFP_ZERO, NUMA_NO_NODE,
3485 __builtin_return_address(0));
3486 }
3487 EXPORT_SYMBOL(vzalloc);
3488
3489 /**
3490 * vmalloc_user - allocate zeroed virtually contiguous memory for userspace
3491 * @size: allocation size
3492 *
3493 * The resulting memory area is zeroed so it can be mapped to userspace
3494 * without leaking data.
3495 *
3496 * Return: pointer to the allocated memory or %NULL on error
3497 */
vmalloc_user(unsigned long size)3498 void *vmalloc_user(unsigned long size)
3499 {
3500 return __vmalloc_node_range(size, SHMLBA, VMALLOC_START, VMALLOC_END,
3501 GFP_KERNEL | __GFP_ZERO, PAGE_KERNEL,
3502 VM_USERMAP, NUMA_NO_NODE,
3503 __builtin_return_address(0));
3504 }
3505 EXPORT_SYMBOL(vmalloc_user);
3506
3507 /**
3508 * vmalloc_node - allocate memory on a specific node
3509 * @size: allocation size
3510 * @node: numa node
3511 *
3512 * Allocate enough pages to cover @size from the page level
3513 * allocator and map them into contiguous kernel virtual space.
3514 *
3515 * For tight control over page level allocator and protection flags
3516 * use __vmalloc() instead.
3517 *
3518 * Return: pointer to the allocated memory or %NULL on error
3519 */
vmalloc_node(unsigned long size,int node)3520 void *vmalloc_node(unsigned long size, int node)
3521 {
3522 return __vmalloc_node(size, 1, GFP_KERNEL, node,
3523 __builtin_return_address(0));
3524 }
3525 EXPORT_SYMBOL(vmalloc_node);
3526
3527 /**
3528 * vzalloc_node - allocate memory on a specific node with zero fill
3529 * @size: allocation size
3530 * @node: numa node
3531 *
3532 * Allocate enough pages to cover @size from the page level
3533 * allocator and map them into contiguous kernel virtual space.
3534 * The memory allocated is set to zero.
3535 *
3536 * Return: pointer to the allocated memory or %NULL on error
3537 */
vzalloc_node(unsigned long size,int node)3538 void *vzalloc_node(unsigned long size, int node)
3539 {
3540 return __vmalloc_node(size, 1, GFP_KERNEL | __GFP_ZERO, node,
3541 __builtin_return_address(0));
3542 }
3543 EXPORT_SYMBOL(vzalloc_node);
3544
3545 #if defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA32)
3546 #define GFP_VMALLOC32 (GFP_DMA32 | GFP_KERNEL)
3547 #elif defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA)
3548 #define GFP_VMALLOC32 (GFP_DMA | GFP_KERNEL)
3549 #else
3550 /*
3551 * 64b systems should always have either DMA or DMA32 zones. For others
3552 * GFP_DMA32 should do the right thing and use the normal zone.
3553 */
3554 #define GFP_VMALLOC32 (GFP_DMA32 | GFP_KERNEL)
3555 #endif
3556
3557 /**
3558 * vmalloc_32 - allocate virtually contiguous memory (32bit addressable)
3559 * @size: allocation size
3560 *
3561 * Allocate enough 32bit PA addressable pages to cover @size from the
3562 * page level allocator and map them into contiguous kernel virtual space.
3563 *
3564 * Return: pointer to the allocated memory or %NULL on error
3565 */
vmalloc_32(unsigned long size)3566 void *vmalloc_32(unsigned long size)
3567 {
3568 return __vmalloc_node(size, 1, GFP_VMALLOC32, NUMA_NO_NODE,
3569 __builtin_return_address(0));
3570 }
3571 EXPORT_SYMBOL(vmalloc_32);
3572
3573 /**
3574 * vmalloc_32_user - allocate zeroed virtually contiguous 32bit memory
3575 * @size: allocation size
3576 *
3577 * The resulting memory area is 32bit addressable and zeroed so it can be
3578 * mapped to userspace without leaking data.
3579 *
3580 * Return: pointer to the allocated memory or %NULL on error
3581 */
vmalloc_32_user(unsigned long size)3582 void *vmalloc_32_user(unsigned long size)
3583 {
3584 return __vmalloc_node_range(size, SHMLBA, VMALLOC_START, VMALLOC_END,
3585 GFP_VMALLOC32 | __GFP_ZERO, PAGE_KERNEL,
3586 VM_USERMAP, NUMA_NO_NODE,
3587 __builtin_return_address(0));
3588 }
3589 EXPORT_SYMBOL(vmalloc_32_user);
3590
3591 /*
3592 * Atomically zero bytes in the iterator.
3593 *
3594 * Returns the number of zeroed bytes.
3595 */
zero_iter(struct iov_iter * iter,size_t count)3596 static size_t zero_iter(struct iov_iter *iter, size_t count)
3597 {
3598 size_t remains = count;
3599
3600 while (remains > 0) {
3601 size_t num, copied;
3602
3603 num = min_t(size_t, remains, PAGE_SIZE);
3604 copied = copy_page_to_iter_nofault(ZERO_PAGE(0), 0, num, iter);
3605 remains -= copied;
3606
3607 if (copied < num)
3608 break;
3609 }
3610
3611 return count - remains;
3612 }
3613
3614 /*
3615 * small helper routine, copy contents to iter from addr.
3616 * If the page is not present, fill zero.
3617 *
3618 * Returns the number of copied bytes.
3619 */
aligned_vread_iter(struct iov_iter * iter,const char * addr,size_t count)3620 static size_t aligned_vread_iter(struct iov_iter *iter,
3621 const char *addr, size_t count)
3622 {
3623 size_t remains = count;
3624 struct page *page;
3625
3626 while (remains > 0) {
3627 unsigned long offset, length;
3628 size_t copied = 0;
3629
3630 offset = offset_in_page(addr);
3631 length = PAGE_SIZE - offset;
3632 if (length > remains)
3633 length = remains;
3634 page = vmalloc_to_page(addr);
3635 /*
3636 * To do safe access to this _mapped_ area, we need lock. But
3637 * adding lock here means that we need to add overhead of
3638 * vmalloc()/vfree() calls for this _debug_ interface, rarely
3639 * used. Instead of that, we'll use an local mapping via
3640 * copy_page_to_iter_nofault() and accept a small overhead in
3641 * this access function.
3642 */
3643 if (page)
3644 copied = copy_page_to_iter_nofault(page, offset,
3645 length, iter);
3646 else
3647 copied = zero_iter(iter, length);
3648
3649 addr += copied;
3650 remains -= copied;
3651
3652 if (copied != length)
3653 break;
3654 }
3655
3656 return count - remains;
3657 }
3658
3659 /*
3660 * Read from a vm_map_ram region of memory.
3661 *
3662 * Returns the number of copied bytes.
3663 */
vmap_ram_vread_iter(struct iov_iter * iter,const char * addr,size_t count,unsigned long flags)3664 static size_t vmap_ram_vread_iter(struct iov_iter *iter, const char *addr,
3665 size_t count, unsigned long flags)
3666 {
3667 char *start;
3668 struct vmap_block *vb;
3669 struct xarray *xa;
3670 unsigned long offset;
3671 unsigned int rs, re;
3672 size_t remains, n;
3673
3674 /*
3675 * If it's area created by vm_map_ram() interface directly, but
3676 * not further subdividing and delegating management to vmap_block,
3677 * handle it here.
3678 */
3679 if (!(flags & VMAP_BLOCK))
3680 return aligned_vread_iter(iter, addr, count);
3681
3682 remains = count;
3683
3684 /*
3685 * Area is split into regions and tracked with vmap_block, read out
3686 * each region and zero fill the hole between regions.
3687 */
3688 xa = addr_to_vb_xa((unsigned long) addr);
3689 vb = xa_load(xa, addr_to_vb_idx((unsigned long)addr));
3690 if (!vb)
3691 goto finished_zero;
3692
3693 spin_lock(&vb->lock);
3694 if (bitmap_empty(vb->used_map, VMAP_BBMAP_BITS)) {
3695 spin_unlock(&vb->lock);
3696 goto finished_zero;
3697 }
3698
3699 for_each_set_bitrange(rs, re, vb->used_map, VMAP_BBMAP_BITS) {
3700 size_t copied;
3701
3702 if (remains == 0)
3703 goto finished;
3704
3705 start = vmap_block_vaddr(vb->va->va_start, rs);
3706
3707 if (addr < start) {
3708 size_t to_zero = min_t(size_t, start - addr, remains);
3709 size_t zeroed = zero_iter(iter, to_zero);
3710
3711 addr += zeroed;
3712 remains -= zeroed;
3713
3714 if (remains == 0 || zeroed != to_zero)
3715 goto finished;
3716 }
3717
3718 /*it could start reading from the middle of used region*/
3719 offset = offset_in_page(addr);
3720 n = ((re - rs + 1) << PAGE_SHIFT) - offset;
3721 if (n > remains)
3722 n = remains;
3723
3724 copied = aligned_vread_iter(iter, start + offset, n);
3725
3726 addr += copied;
3727 remains -= copied;
3728
3729 if (copied != n)
3730 goto finished;
3731 }
3732
3733 spin_unlock(&vb->lock);
3734
3735 finished_zero:
3736 /* zero-fill the left dirty or free regions */
3737 return count - remains + zero_iter(iter, remains);
3738 finished:
3739 /* We couldn't copy/zero everything */
3740 spin_unlock(&vb->lock);
3741 return count - remains;
3742 }
3743
3744 /**
3745 * vread_iter() - read vmalloc area in a safe way to an iterator.
3746 * @iter: the iterator to which data should be written.
3747 * @addr: vm address.
3748 * @count: number of bytes to be read.
3749 *
3750 * This function checks that addr is a valid vmalloc'ed area, and
3751 * copy data from that area to a given buffer. If the given memory range
3752 * of [addr...addr+count) includes some valid address, data is copied to
3753 * proper area of @buf. If there are memory holes, they'll be zero-filled.
3754 * IOREMAP area is treated as memory hole and no copy is done.
3755 *
3756 * If [addr...addr+count) doesn't includes any intersects with alive
3757 * vm_struct area, returns 0. @buf should be kernel's buffer.
3758 *
3759 * Note: In usual ops, vread() is never necessary because the caller
3760 * should know vmalloc() area is valid and can use memcpy().
3761 * This is for routines which have to access vmalloc area without
3762 * any information, as /proc/kcore.
3763 *
3764 * Return: number of bytes for which addr and buf should be increased
3765 * (same number as @count) or %0 if [addr...addr+count) doesn't
3766 * include any intersection with valid vmalloc area
3767 */
vread_iter(struct iov_iter * iter,const char * addr,size_t count)3768 long vread_iter(struct iov_iter *iter, const char *addr, size_t count)
3769 {
3770 struct vmap_area *va;
3771 struct vm_struct *vm;
3772 char *vaddr;
3773 size_t n, size, flags, remains;
3774
3775 addr = kasan_reset_tag(addr);
3776
3777 /* Don't allow overflow */
3778 if ((unsigned long) addr + count < count)
3779 count = -(unsigned long) addr;
3780
3781 remains = count;
3782
3783 spin_lock(&vmap_area_lock);
3784 va = find_vmap_area_exceed_addr((unsigned long)addr);
3785 if (!va)
3786 goto finished_zero;
3787
3788 /* no intersects with alive vmap_area */
3789 if ((unsigned long)addr + remains <= va->va_start)
3790 goto finished_zero;
3791
3792 list_for_each_entry_from(va, &vmap_area_list, list) {
3793 size_t copied;
3794
3795 if (remains == 0)
3796 goto finished;
3797
3798 vm = va->vm;
3799 flags = va->flags & VMAP_FLAGS_MASK;
3800 /*
3801 * VMAP_BLOCK indicates a sub-type of vm_map_ram area, need
3802 * be set together with VMAP_RAM.
3803 */
3804 WARN_ON(flags == VMAP_BLOCK);
3805
3806 if (!vm && !flags)
3807 continue;
3808
3809 if (vm && (vm->flags & VM_UNINITIALIZED))
3810 continue;
3811
3812 /* Pair with smp_wmb() in clear_vm_uninitialized_flag() */
3813 smp_rmb();
3814
3815 vaddr = (char *) va->va_start;
3816 size = vm ? get_vm_area_size(vm) : va_size(va);
3817
3818 if (addr >= vaddr + size)
3819 continue;
3820
3821 if (addr < vaddr) {
3822 size_t to_zero = min_t(size_t, vaddr - addr, remains);
3823 size_t zeroed = zero_iter(iter, to_zero);
3824
3825 addr += zeroed;
3826 remains -= zeroed;
3827
3828 if (remains == 0 || zeroed != to_zero)
3829 goto finished;
3830 }
3831
3832 n = vaddr + size - addr;
3833 if (n > remains)
3834 n = remains;
3835
3836 if (flags & VMAP_RAM)
3837 copied = vmap_ram_vread_iter(iter, addr, n, flags);
3838 else if (!(vm->flags & VM_IOREMAP))
3839 copied = aligned_vread_iter(iter, addr, n);
3840 else /* IOREMAP area is treated as memory hole */
3841 copied = zero_iter(iter, n);
3842
3843 addr += copied;
3844 remains -= copied;
3845
3846 if (copied != n)
3847 goto finished;
3848 }
3849
3850 finished_zero:
3851 spin_unlock(&vmap_area_lock);
3852 /* zero-fill memory holes */
3853 return count - remains + zero_iter(iter, remains);
3854 finished:
3855 /* Nothing remains, or We couldn't copy/zero everything. */
3856 spin_unlock(&vmap_area_lock);
3857
3858 return count - remains;
3859 }
3860
3861 /**
3862 * remap_vmalloc_range_partial - map vmalloc pages to userspace
3863 * @vma: vma to cover
3864 * @uaddr: target user address to start at
3865 * @kaddr: virtual address of vmalloc kernel memory
3866 * @pgoff: offset from @kaddr to start at
3867 * @size: size of map area
3868 *
3869 * Returns: 0 for success, -Exxx on failure
3870 *
3871 * This function checks that @kaddr is a valid vmalloc'ed area,
3872 * and that it is big enough to cover the range starting at
3873 * @uaddr in @vma. Will return failure if that criteria isn't
3874 * met.
3875 *
3876 * Similar to remap_pfn_range() (see mm/memory.c)
3877 */
remap_vmalloc_range_partial(struct vm_area_struct * vma,unsigned long uaddr,void * kaddr,unsigned long pgoff,unsigned long size)3878 int remap_vmalloc_range_partial(struct vm_area_struct *vma, unsigned long uaddr,
3879 void *kaddr, unsigned long pgoff,
3880 unsigned long size)
3881 {
3882 struct vm_struct *area;
3883 unsigned long off;
3884 unsigned long end_index;
3885
3886 if (check_shl_overflow(pgoff, PAGE_SHIFT, &off))
3887 return -EINVAL;
3888
3889 size = PAGE_ALIGN(size);
3890
3891 if (!PAGE_ALIGNED(uaddr) || !PAGE_ALIGNED(kaddr))
3892 return -EINVAL;
3893
3894 area = find_vm_area(kaddr);
3895 if (!area)
3896 return -EINVAL;
3897
3898 if (!(area->flags & (VM_USERMAP | VM_DMA_COHERENT)))
3899 return -EINVAL;
3900
3901 if (check_add_overflow(size, off, &end_index) ||
3902 end_index > get_vm_area_size(area))
3903 return -EINVAL;
3904 kaddr += off;
3905
3906 do {
3907 struct page *page = vmalloc_to_page(kaddr);
3908 int ret;
3909
3910 ret = vm_insert_page(vma, uaddr, page);
3911 if (ret)
3912 return ret;
3913
3914 uaddr += PAGE_SIZE;
3915 kaddr += PAGE_SIZE;
3916 size -= PAGE_SIZE;
3917 } while (size > 0);
3918
3919 vm_flags_set(vma, VM_DONTEXPAND | VM_DONTDUMP);
3920
3921 return 0;
3922 }
3923
3924 /**
3925 * remap_vmalloc_range - map vmalloc pages to userspace
3926 * @vma: vma to cover (map full range of vma)
3927 * @addr: vmalloc memory
3928 * @pgoff: number of pages into addr before first page to map
3929 *
3930 * Returns: 0 for success, -Exxx on failure
3931 *
3932 * This function checks that addr is a valid vmalloc'ed area, and
3933 * that it is big enough to cover the vma. Will return failure if
3934 * that criteria isn't met.
3935 *
3936 * Similar to remap_pfn_range() (see mm/memory.c)
3937 */
remap_vmalloc_range(struct vm_area_struct * vma,void * addr,unsigned long pgoff)3938 int remap_vmalloc_range(struct vm_area_struct *vma, void *addr,
3939 unsigned long pgoff)
3940 {
3941 return remap_vmalloc_range_partial(vma, vma->vm_start,
3942 addr, pgoff,
3943 vma->vm_end - vma->vm_start);
3944 }
3945 EXPORT_SYMBOL(remap_vmalloc_range);
3946
free_vm_area(struct vm_struct * area)3947 void free_vm_area(struct vm_struct *area)
3948 {
3949 struct vm_struct *ret;
3950 ret = remove_vm_area(area->addr);
3951 BUG_ON(ret != area);
3952 kfree(area);
3953 }
3954 EXPORT_SYMBOL_GPL(free_vm_area);
3955
3956 #ifdef CONFIG_SMP
node_to_va(struct rb_node * n)3957 static struct vmap_area *node_to_va(struct rb_node *n)
3958 {
3959 return rb_entry_safe(n, struct vmap_area, rb_node);
3960 }
3961
3962 /**
3963 * pvm_find_va_enclose_addr - find the vmap_area @addr belongs to
3964 * @addr: target address
3965 *
3966 * Returns: vmap_area if it is found. If there is no such area
3967 * the first highest(reverse order) vmap_area is returned
3968 * i.e. va->va_start < addr && va->va_end < addr or NULL
3969 * if there are no any areas before @addr.
3970 */
3971 static struct vmap_area *
pvm_find_va_enclose_addr(unsigned long addr)3972 pvm_find_va_enclose_addr(unsigned long addr)
3973 {
3974 struct vmap_area *va, *tmp;
3975 struct rb_node *n;
3976
3977 n = free_vmap_area_root.rb_node;
3978 va = NULL;
3979
3980 while (n) {
3981 tmp = rb_entry(n, struct vmap_area, rb_node);
3982 if (tmp->va_start <= addr) {
3983 va = tmp;
3984 if (tmp->va_end >= addr)
3985 break;
3986
3987 n = n->rb_right;
3988 } else {
3989 n = n->rb_left;
3990 }
3991 }
3992
3993 return va;
3994 }
3995
3996 /**
3997 * pvm_determine_end_from_reverse - find the highest aligned address
3998 * of free block below VMALLOC_END
3999 * @va:
4000 * in - the VA we start the search(reverse order);
4001 * out - the VA with the highest aligned end address.
4002 * @align: alignment for required highest address
4003 *
4004 * Returns: determined end address within vmap_area
4005 */
4006 static unsigned long
pvm_determine_end_from_reverse(struct vmap_area ** va,unsigned long align)4007 pvm_determine_end_from_reverse(struct vmap_area **va, unsigned long align)
4008 {
4009 unsigned long vmalloc_end = VMALLOC_END & ~(align - 1);
4010 unsigned long addr;
4011
4012 if (likely(*va)) {
4013 list_for_each_entry_from_reverse((*va),
4014 &free_vmap_area_list, list) {
4015 addr = min((*va)->va_end & ~(align - 1), vmalloc_end);
4016 if ((*va)->va_start < addr)
4017 return addr;
4018 }
4019 }
4020
4021 return 0;
4022 }
4023
4024 /**
4025 * pcpu_get_vm_areas - allocate vmalloc areas for percpu allocator
4026 * @offsets: array containing offset of each area
4027 * @sizes: array containing size of each area
4028 * @nr_vms: the number of areas to allocate
4029 * @align: alignment, all entries in @offsets and @sizes must be aligned to this
4030 *
4031 * Returns: kmalloc'd vm_struct pointer array pointing to allocated
4032 * vm_structs on success, %NULL on failure
4033 *
4034 * Percpu allocator wants to use congruent vm areas so that it can
4035 * maintain the offsets among percpu areas. This function allocates
4036 * congruent vmalloc areas for it with GFP_KERNEL. These areas tend to
4037 * be scattered pretty far, distance between two areas easily going up
4038 * to gigabytes. To avoid interacting with regular vmallocs, these
4039 * areas are allocated from top.
4040 *
4041 * Despite its complicated look, this allocator is rather simple. It
4042 * does everything top-down and scans free blocks from the end looking
4043 * for matching base. While scanning, if any of the areas do not fit the
4044 * base address is pulled down to fit the area. Scanning is repeated till
4045 * all the areas fit and then all necessary data structures are inserted
4046 * and the result is returned.
4047 */
pcpu_get_vm_areas(const unsigned long * offsets,const size_t * sizes,int nr_vms,size_t align)4048 struct vm_struct **pcpu_get_vm_areas(const unsigned long *offsets,
4049 const size_t *sizes, int nr_vms,
4050 size_t align)
4051 {
4052 const unsigned long vmalloc_start = ALIGN(VMALLOC_START, align);
4053 const unsigned long vmalloc_end = VMALLOC_END & ~(align - 1);
4054 struct vmap_area **vas, *va;
4055 struct vm_struct **vms;
4056 int area, area2, last_area, term_area;
4057 unsigned long base, start, size, end, last_end, orig_start, orig_end;
4058 bool purged = false;
4059
4060 /* verify parameters and allocate data structures */
4061 BUG_ON(offset_in_page(align) || !is_power_of_2(align));
4062 for (last_area = 0, area = 0; area < nr_vms; area++) {
4063 start = offsets[area];
4064 end = start + sizes[area];
4065
4066 /* is everything aligned properly? */
4067 BUG_ON(!IS_ALIGNED(offsets[area], align));
4068 BUG_ON(!IS_ALIGNED(sizes[area], align));
4069
4070 /* detect the area with the highest address */
4071 if (start > offsets[last_area])
4072 last_area = area;
4073
4074 for (area2 = area + 1; area2 < nr_vms; area2++) {
4075 unsigned long start2 = offsets[area2];
4076 unsigned long end2 = start2 + sizes[area2];
4077
4078 BUG_ON(start2 < end && start < end2);
4079 }
4080 }
4081 last_end = offsets[last_area] + sizes[last_area];
4082
4083 if (vmalloc_end - vmalloc_start < last_end) {
4084 WARN_ON(true);
4085 return NULL;
4086 }
4087
4088 vms = kcalloc(nr_vms, sizeof(vms[0]), GFP_KERNEL);
4089 vas = kcalloc(nr_vms, sizeof(vas[0]), GFP_KERNEL);
4090 if (!vas || !vms)
4091 goto err_free2;
4092
4093 for (area = 0; area < nr_vms; area++) {
4094 vas[area] = kmem_cache_zalloc(vmap_area_cachep, GFP_KERNEL);
4095 vms[area] = kzalloc(sizeof(struct vm_struct), GFP_KERNEL);
4096 if (!vas[area] || !vms[area])
4097 goto err_free;
4098 }
4099 retry:
4100 spin_lock(&free_vmap_area_lock);
4101
4102 /* start scanning - we scan from the top, begin with the last area */
4103 area = term_area = last_area;
4104 start = offsets[area];
4105 end = start + sizes[area];
4106
4107 va = pvm_find_va_enclose_addr(vmalloc_end);
4108 base = pvm_determine_end_from_reverse(&va, align) - end;
4109
4110 while (true) {
4111 /*
4112 * base might have underflowed, add last_end before
4113 * comparing.
4114 */
4115 if (base + last_end < vmalloc_start + last_end)
4116 goto overflow;
4117
4118 /*
4119 * Fitting base has not been found.
4120 */
4121 if (va == NULL)
4122 goto overflow;
4123
4124 /*
4125 * If required width exceeds current VA block, move
4126 * base downwards and then recheck.
4127 */
4128 if (base + end > va->va_end) {
4129 base = pvm_determine_end_from_reverse(&va, align) - end;
4130 term_area = area;
4131 continue;
4132 }
4133
4134 /*
4135 * If this VA does not fit, move base downwards and recheck.
4136 */
4137 if (base + start < va->va_start) {
4138 va = node_to_va(rb_prev(&va->rb_node));
4139 base = pvm_determine_end_from_reverse(&va, align) - end;
4140 term_area = area;
4141 continue;
4142 }
4143
4144 /*
4145 * This area fits, move on to the previous one. If
4146 * the previous one is the terminal one, we're done.
4147 */
4148 area = (area + nr_vms - 1) % nr_vms;
4149 if (area == term_area)
4150 break;
4151
4152 start = offsets[area];
4153 end = start + sizes[area];
4154 va = pvm_find_va_enclose_addr(base + end);
4155 }
4156
4157 /* we've found a fitting base, insert all va's */
4158 for (area = 0; area < nr_vms; area++) {
4159 int ret;
4160
4161 start = base + offsets[area];
4162 size = sizes[area];
4163
4164 va = pvm_find_va_enclose_addr(start);
4165 if (WARN_ON_ONCE(va == NULL))
4166 /* It is a BUG(), but trigger recovery instead. */
4167 goto recovery;
4168
4169 ret = adjust_va_to_fit_type(&free_vmap_area_root,
4170 &free_vmap_area_list,
4171 va, start, size);
4172 if (WARN_ON_ONCE(unlikely(ret)))
4173 /* It is a BUG(), but trigger recovery instead. */
4174 goto recovery;
4175
4176 /* Allocated area. */
4177 va = vas[area];
4178 va->va_start = start;
4179 va->va_end = start + size;
4180 }
4181
4182 spin_unlock(&free_vmap_area_lock);
4183
4184 /* populate the kasan shadow space */
4185 for (area = 0; area < nr_vms; area++) {
4186 if (kasan_populate_vmalloc(vas[area]->va_start, sizes[area]))
4187 goto err_free_shadow;
4188 }
4189
4190 /* insert all vm's */
4191 spin_lock(&vmap_area_lock);
4192 for (area = 0; area < nr_vms; area++) {
4193 insert_vmap_area(vas[area], &vmap_area_root, &vmap_area_list);
4194
4195 setup_vmalloc_vm_locked(vms[area], vas[area], VM_ALLOC,
4196 pcpu_get_vm_areas);
4197 }
4198 spin_unlock(&vmap_area_lock);
4199
4200 /*
4201 * Mark allocated areas as accessible. Do it now as a best-effort
4202 * approach, as they can be mapped outside of vmalloc code.
4203 * With hardware tag-based KASAN, marking is skipped for
4204 * non-VM_ALLOC mappings, see __kasan_unpoison_vmalloc().
4205 */
4206 for (area = 0; area < nr_vms; area++)
4207 vms[area]->addr = kasan_unpoison_vmalloc(vms[area]->addr,
4208 vms[area]->size, KASAN_VMALLOC_PROT_NORMAL);
4209
4210 kfree(vas);
4211 return vms;
4212
4213 recovery:
4214 /*
4215 * Remove previously allocated areas. There is no
4216 * need in removing these areas from the busy tree,
4217 * because they are inserted only on the final step
4218 * and when pcpu_get_vm_areas() is success.
4219 */
4220 while (area--) {
4221 orig_start = vas[area]->va_start;
4222 orig_end = vas[area]->va_end;
4223 va = merge_or_add_vmap_area_augment(vas[area], &free_vmap_area_root,
4224 &free_vmap_area_list);
4225 if (va)
4226 kasan_release_vmalloc(orig_start, orig_end,
4227 va->va_start, va->va_end);
4228 vas[area] = NULL;
4229 }
4230
4231 overflow:
4232 spin_unlock(&free_vmap_area_lock);
4233 if (!purged) {
4234 reclaim_and_purge_vmap_areas();
4235 purged = true;
4236
4237 /* Before "retry", check if we recover. */
4238 for (area = 0; area < nr_vms; area++) {
4239 if (vas[area])
4240 continue;
4241
4242 vas[area] = kmem_cache_zalloc(
4243 vmap_area_cachep, GFP_KERNEL);
4244 if (!vas[area])
4245 goto err_free;
4246 }
4247
4248 goto retry;
4249 }
4250
4251 err_free:
4252 for (area = 0; area < nr_vms; area++) {
4253 if (vas[area])
4254 kmem_cache_free(vmap_area_cachep, vas[area]);
4255
4256 kfree(vms[area]);
4257 }
4258 err_free2:
4259 kfree(vas);
4260 kfree(vms);
4261 return NULL;
4262
4263 err_free_shadow:
4264 spin_lock(&free_vmap_area_lock);
4265 /*
4266 * We release all the vmalloc shadows, even the ones for regions that
4267 * hadn't been successfully added. This relies on kasan_release_vmalloc
4268 * being able to tolerate this case.
4269 */
4270 for (area = 0; area < nr_vms; area++) {
4271 orig_start = vas[area]->va_start;
4272 orig_end = vas[area]->va_end;
4273 va = merge_or_add_vmap_area_augment(vas[area], &free_vmap_area_root,
4274 &free_vmap_area_list);
4275 if (va)
4276 kasan_release_vmalloc(orig_start, orig_end,
4277 va->va_start, va->va_end);
4278 vas[area] = NULL;
4279 kfree(vms[area]);
4280 }
4281 spin_unlock(&free_vmap_area_lock);
4282 kfree(vas);
4283 kfree(vms);
4284 return NULL;
4285 }
4286
4287 /**
4288 * pcpu_free_vm_areas - free vmalloc areas for percpu allocator
4289 * @vms: vm_struct pointer array returned by pcpu_get_vm_areas()
4290 * @nr_vms: the number of allocated areas
4291 *
4292 * Free vm_structs and the array allocated by pcpu_get_vm_areas().
4293 */
pcpu_free_vm_areas(struct vm_struct ** vms,int nr_vms)4294 void pcpu_free_vm_areas(struct vm_struct **vms, int nr_vms)
4295 {
4296 int i;
4297
4298 for (i = 0; i < nr_vms; i++)
4299 free_vm_area(vms[i]);
4300 kfree(vms);
4301 }
4302 #endif /* CONFIG_SMP */
4303
4304 #ifdef CONFIG_PRINTK
vmalloc_dump_obj(void * object)4305 bool vmalloc_dump_obj(void *object)
4306 {
4307 void *objp = (void *)PAGE_ALIGN((unsigned long)object);
4308 const void *caller;
4309 struct vm_struct *vm;
4310 struct vmap_area *va;
4311 unsigned long addr;
4312 unsigned int nr_pages;
4313
4314 if (!spin_trylock(&vmap_area_lock))
4315 return false;
4316 va = __find_vmap_area((unsigned long)objp, &vmap_area_root);
4317 if (!va) {
4318 spin_unlock(&vmap_area_lock);
4319 return false;
4320 }
4321
4322 vm = va->vm;
4323 if (!vm) {
4324 spin_unlock(&vmap_area_lock);
4325 return false;
4326 }
4327 addr = (unsigned long)vm->addr;
4328 caller = vm->caller;
4329 nr_pages = vm->nr_pages;
4330 spin_unlock(&vmap_area_lock);
4331 pr_cont(" %u-page vmalloc region starting at %#lx allocated at %pS\n",
4332 nr_pages, addr, caller);
4333 return true;
4334 }
4335 #endif
4336
4337 #ifdef CONFIG_PROC_FS
s_start(struct seq_file * m,loff_t * pos)4338 static void *s_start(struct seq_file *m, loff_t *pos)
4339 __acquires(&vmap_purge_lock)
4340 __acquires(&vmap_area_lock)
4341 {
4342 mutex_lock(&vmap_purge_lock);
4343 spin_lock(&vmap_area_lock);
4344
4345 return seq_list_start(&vmap_area_list, *pos);
4346 }
4347
s_next(struct seq_file * m,void * p,loff_t * pos)4348 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
4349 {
4350 return seq_list_next(p, &vmap_area_list, pos);
4351 }
4352
s_stop(struct seq_file * m,void * p)4353 static void s_stop(struct seq_file *m, void *p)
4354 __releases(&vmap_area_lock)
4355 __releases(&vmap_purge_lock)
4356 {
4357 spin_unlock(&vmap_area_lock);
4358 mutex_unlock(&vmap_purge_lock);
4359 }
4360
show_numa_info(struct seq_file * m,struct vm_struct * v)4361 static void show_numa_info(struct seq_file *m, struct vm_struct *v)
4362 {
4363 if (IS_ENABLED(CONFIG_NUMA)) {
4364 unsigned int nr, *counters = m->private;
4365 unsigned int step = 1U << vm_area_page_order(v);
4366
4367 if (!counters)
4368 return;
4369
4370 if (v->flags & VM_UNINITIALIZED)
4371 return;
4372 /* Pair with smp_wmb() in clear_vm_uninitialized_flag() */
4373 smp_rmb();
4374
4375 memset(counters, 0, nr_node_ids * sizeof(unsigned int));
4376
4377 for (nr = 0; nr < v->nr_pages; nr += step)
4378 counters[page_to_nid(v->pages[nr])] += step;
4379 for_each_node_state(nr, N_HIGH_MEMORY)
4380 if (counters[nr])
4381 seq_printf(m, " N%u=%u", nr, counters[nr]);
4382 }
4383 }
4384
show_purge_info(struct seq_file * m)4385 static void show_purge_info(struct seq_file *m)
4386 {
4387 struct vmap_area *va;
4388
4389 spin_lock(&purge_vmap_area_lock);
4390 list_for_each_entry(va, &purge_vmap_area_list, list) {
4391 seq_printf(m, "0x%pK-0x%pK %7ld unpurged vm_area\n",
4392 (void *)va->va_start, (void *)va->va_end,
4393 va->va_end - va->va_start);
4394 }
4395 spin_unlock(&purge_vmap_area_lock);
4396 }
4397
s_show(struct seq_file * m,void * p)4398 static int s_show(struct seq_file *m, void *p)
4399 {
4400 struct vmap_area *va;
4401 struct vm_struct *v;
4402
4403 va = list_entry(p, struct vmap_area, list);
4404
4405 if (!va->vm) {
4406 if (va->flags & VMAP_RAM)
4407 seq_printf(m, "0x%pK-0x%pK %7ld vm_map_ram\n",
4408 (void *)va->va_start, (void *)va->va_end,
4409 va->va_end - va->va_start);
4410
4411 goto final;
4412 }
4413
4414 v = va->vm;
4415
4416 seq_printf(m, "0x%pK-0x%pK %7ld",
4417 v->addr, v->addr + v->size, v->size);
4418
4419 if (v->caller)
4420 seq_printf(m, " %pS", v->caller);
4421
4422 if (v->nr_pages)
4423 seq_printf(m, " pages=%d", v->nr_pages);
4424
4425 if (v->phys_addr)
4426 seq_printf(m, " phys=%pa", &v->phys_addr);
4427
4428 if (v->flags & VM_IOREMAP)
4429 seq_puts(m, " ioremap");
4430
4431 if (v->flags & VM_ALLOC)
4432 seq_puts(m, " vmalloc");
4433
4434 if (v->flags & VM_MAP)
4435 seq_puts(m, " vmap");
4436
4437 if (v->flags & VM_USERMAP)
4438 seq_puts(m, " user");
4439
4440 if (v->flags & VM_DMA_COHERENT)
4441 seq_puts(m, " dma-coherent");
4442
4443 if (is_vmalloc_addr(v->pages))
4444 seq_puts(m, " vpages");
4445
4446 show_numa_info(m, v);
4447 trace_android_vh_show_stack_hash(m, v);
4448 seq_putc(m, '\n');
4449
4450 /*
4451 * As a final step, dump "unpurged" areas.
4452 */
4453 final:
4454 if (list_is_last(&va->list, &vmap_area_list))
4455 show_purge_info(m);
4456
4457 return 0;
4458 }
4459
4460 static const struct seq_operations vmalloc_op = {
4461 .start = s_start,
4462 .next = s_next,
4463 .stop = s_stop,
4464 .show = s_show,
4465 };
4466
proc_vmalloc_init(void)4467 static int __init proc_vmalloc_init(void)
4468 {
4469 if (IS_ENABLED(CONFIG_NUMA))
4470 proc_create_seq_private("vmallocinfo", 0400, NULL,
4471 &vmalloc_op,
4472 nr_node_ids * sizeof(unsigned int), NULL);
4473 else
4474 proc_create_seq("vmallocinfo", 0400, NULL, &vmalloc_op);
4475 return 0;
4476 }
4477 module_init(proc_vmalloc_init);
4478
4479 #endif
4480
vmalloc_init(void)4481 void __init vmalloc_init(void)
4482 {
4483 struct vmap_area *va;
4484 struct vm_struct *tmp;
4485 int i;
4486
4487 /*
4488 * Create the cache for vmap_area objects.
4489 */
4490 vmap_area_cachep = KMEM_CACHE(vmap_area, SLAB_PANIC);
4491
4492 for_each_possible_cpu(i) {
4493 struct vmap_block_queue *vbq;
4494 struct vfree_deferred *p;
4495
4496 vbq = &per_cpu(vmap_block_queue, i);
4497 spin_lock_init(&vbq->lock);
4498 INIT_LIST_HEAD(&vbq->free);
4499 p = &per_cpu(vfree_deferred, i);
4500 init_llist_head(&p->list);
4501 INIT_WORK(&p->wq, delayed_vfree_work);
4502 xa_init(&vbq->vmap_blocks);
4503 }
4504
4505 /* Import existing vmlist entries. */
4506 for (tmp = vmlist; tmp; tmp = tmp->next) {
4507 va = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
4508 if (WARN_ON_ONCE(!va))
4509 continue;
4510
4511 va->va_start = (unsigned long)tmp->addr;
4512 va->va_end = va->va_start + tmp->size;
4513 va->vm = tmp;
4514 insert_vmap_area(va, &vmap_area_root, &vmap_area_list);
4515 }
4516
4517 /*
4518 * Now we can initialize a free vmap space.
4519 */
4520 vmap_init_free_space();
4521 vmap_initialized = true;
4522 }
4523