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