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