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