xref: /linux/mm/vmalloc.c (revision 3e9a9e256b1e1e6e8f19faf76fa9c37578ae35ee)
1457c8996SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  *  linux/mm/vmalloc.c
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  *  Copyright (C) 1993  Linus Torvalds
61da177e4SLinus Torvalds  *  Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
71da177e4SLinus Torvalds  *  SMP-safe vmalloc/vfree/ioremap, Tigran Aivazian <tigran@veritas.com>, May 2000
81da177e4SLinus Torvalds  *  Major rework to support vmap/vunmap, Christoph Hellwig, SGI, August 2002
9930fc45aSChristoph Lameter  *  Numa awareness, Christoph Lameter, SGI, June 2005
10d758ffe6SUladzislau Rezki (Sony)  *  Improving global KVA allocator, Uladzislau Rezki, Sony, May 2019
111da177e4SLinus Torvalds  */
121da177e4SLinus Torvalds 
13db64fe02SNick Piggin #include <linux/vmalloc.h>
141da177e4SLinus Torvalds #include <linux/mm.h>
151da177e4SLinus Torvalds #include <linux/module.h>
161da177e4SLinus Torvalds #include <linux/highmem.h>
17c3edc401SIngo Molnar #include <linux/sched/signal.h>
181da177e4SLinus Torvalds #include <linux/slab.h>
191da177e4SLinus Torvalds #include <linux/spinlock.h>
201da177e4SLinus Torvalds #include <linux/interrupt.h>
215f6a6a9cSAlexey Dobriyan #include <linux/proc_fs.h>
22a10aa579SChristoph Lameter #include <linux/seq_file.h>
23868b104dSRick Edgecombe #include <linux/set_memory.h>
243ac7fe5aSThomas Gleixner #include <linux/debugobjects.h>
2523016969SChristoph Lameter #include <linux/kallsyms.h>
26db64fe02SNick Piggin #include <linux/list.h>
274da56b99SChris Wilson #include <linux/notifier.h>
28db64fe02SNick Piggin #include <linux/rbtree.h>
290f14599cSMatthew Wilcox (Oracle) #include <linux/xarray.h>
30db64fe02SNick Piggin #include <linux/rcupdate.h>
31f0aa6617STejun Heo #include <linux/pfn.h>
3289219d37SCatalin Marinas #include <linux/kmemleak.h>
3360063497SArun Sharma #include <linux/atomic.h>
343b32123dSGideon Israel Dsouza #include <linux/compiler.h>
3532fcfd40SAl Viro #include <linux/llist.h>
360f616be1SToshi Kani #include <linux/bitops.h>
3768ad4a33SUladzislau Rezki (Sony) #include <linux/rbtree_augmented.h>
38bdebd6a2SJann Horn #include <linux/overflow.h>
393b32123dSGideon Israel Dsouza 
407c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
411da177e4SLinus Torvalds #include <asm/tlbflush.h>
422dca6999SDavid Miller #include <asm/shmparam.h>
431da177e4SLinus Torvalds 
44dd56b046SMel Gorman #include "internal.h"
452a681cfaSJoerg Roedel #include "pgalloc-track.h"
46dd56b046SMel Gorman 
47186525bdSIngo Molnar bool is_vmalloc_addr(const void *x)
48186525bdSIngo Molnar {
49186525bdSIngo Molnar 	unsigned long addr = (unsigned long)x;
50186525bdSIngo Molnar 
51186525bdSIngo Molnar 	return addr >= VMALLOC_START && addr < VMALLOC_END;
52186525bdSIngo Molnar }
53186525bdSIngo Molnar EXPORT_SYMBOL(is_vmalloc_addr);
54186525bdSIngo Molnar 
5532fcfd40SAl Viro struct vfree_deferred {
5632fcfd40SAl Viro 	struct llist_head list;
5732fcfd40SAl Viro 	struct work_struct wq;
5832fcfd40SAl Viro };
5932fcfd40SAl Viro static DEFINE_PER_CPU(struct vfree_deferred, vfree_deferred);
6032fcfd40SAl Viro 
6132fcfd40SAl Viro static void __vunmap(const void *, int);
6232fcfd40SAl Viro 
6332fcfd40SAl Viro static void free_work(struct work_struct *w)
6432fcfd40SAl Viro {
6532fcfd40SAl Viro 	struct vfree_deferred *p = container_of(w, struct vfree_deferred, wq);
66894e58c1SByungchul Park 	struct llist_node *t, *llnode;
67894e58c1SByungchul Park 
68894e58c1SByungchul Park 	llist_for_each_safe(llnode, t, llist_del_all(&p->list))
69894e58c1SByungchul Park 		__vunmap((void *)llnode, 1);
7032fcfd40SAl Viro }
7132fcfd40SAl Viro 
72db64fe02SNick Piggin /*** Page table manipulation functions ***/
73b221385bSAdrian Bunk 
742ba3e694SJoerg Roedel static void vunmap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
752ba3e694SJoerg Roedel 			     pgtbl_mod_mask *mask)
761da177e4SLinus Torvalds {
771da177e4SLinus Torvalds 	pte_t *pte;
781da177e4SLinus Torvalds 
791da177e4SLinus Torvalds 	pte = pte_offset_kernel(pmd, addr);
801da177e4SLinus Torvalds 	do {
811da177e4SLinus Torvalds 		pte_t ptent = ptep_get_and_clear(&init_mm, addr, pte);
821da177e4SLinus Torvalds 		WARN_ON(!pte_none(ptent) && !pte_present(ptent));
831da177e4SLinus Torvalds 	} while (pte++, addr += PAGE_SIZE, addr != end);
842ba3e694SJoerg Roedel 	*mask |= PGTBL_PTE_MODIFIED;
851da177e4SLinus Torvalds }
861da177e4SLinus Torvalds 
872ba3e694SJoerg Roedel static void vunmap_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,
882ba3e694SJoerg Roedel 			     pgtbl_mod_mask *mask)
891da177e4SLinus Torvalds {
901da177e4SLinus Torvalds 	pmd_t *pmd;
911da177e4SLinus Torvalds 	unsigned long next;
922ba3e694SJoerg Roedel 	int cleared;
931da177e4SLinus Torvalds 
941da177e4SLinus Torvalds 	pmd = pmd_offset(pud, addr);
951da177e4SLinus Torvalds 	do {
961da177e4SLinus Torvalds 		next = pmd_addr_end(addr, end);
972ba3e694SJoerg Roedel 
982ba3e694SJoerg Roedel 		cleared = pmd_clear_huge(pmd);
992ba3e694SJoerg Roedel 		if (cleared || pmd_bad(*pmd))
1002ba3e694SJoerg Roedel 			*mask |= PGTBL_PMD_MODIFIED;
1012ba3e694SJoerg Roedel 
1022ba3e694SJoerg Roedel 		if (cleared)
103b9820d8fSToshi Kani 			continue;
1041da177e4SLinus Torvalds 		if (pmd_none_or_clear_bad(pmd))
1051da177e4SLinus Torvalds 			continue;
1062ba3e694SJoerg Roedel 		vunmap_pte_range(pmd, addr, next, mask);
107e47110e9SAneesh Kumar K.V 
108e47110e9SAneesh Kumar K.V 		cond_resched();
1091da177e4SLinus Torvalds 	} while (pmd++, addr = next, addr != end);
1101da177e4SLinus Torvalds }
1111da177e4SLinus Torvalds 
1122ba3e694SJoerg Roedel static void vunmap_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end,
1132ba3e694SJoerg Roedel 			     pgtbl_mod_mask *mask)
1141da177e4SLinus Torvalds {
1151da177e4SLinus Torvalds 	pud_t *pud;
1161da177e4SLinus Torvalds 	unsigned long next;
1172ba3e694SJoerg Roedel 	int cleared;
1181da177e4SLinus Torvalds 
119c2febafcSKirill A. Shutemov 	pud = pud_offset(p4d, addr);
1201da177e4SLinus Torvalds 	do {
1211da177e4SLinus Torvalds 		next = pud_addr_end(addr, end);
1222ba3e694SJoerg Roedel 
1232ba3e694SJoerg Roedel 		cleared = pud_clear_huge(pud);
1242ba3e694SJoerg Roedel 		if (cleared || pud_bad(*pud))
1252ba3e694SJoerg Roedel 			*mask |= PGTBL_PUD_MODIFIED;
1262ba3e694SJoerg Roedel 
1272ba3e694SJoerg Roedel 		if (cleared)
128b9820d8fSToshi Kani 			continue;
1291da177e4SLinus Torvalds 		if (pud_none_or_clear_bad(pud))
1301da177e4SLinus Torvalds 			continue;
1312ba3e694SJoerg Roedel 		vunmap_pmd_range(pud, addr, next, mask);
1321da177e4SLinus Torvalds 	} while (pud++, addr = next, addr != end);
1331da177e4SLinus Torvalds }
1341da177e4SLinus Torvalds 
1352ba3e694SJoerg Roedel static void vunmap_p4d_range(pgd_t *pgd, unsigned long addr, unsigned long end,
1362ba3e694SJoerg Roedel 			     pgtbl_mod_mask *mask)
137c2febafcSKirill A. Shutemov {
138c2febafcSKirill A. Shutemov 	p4d_t *p4d;
139c2febafcSKirill A. Shutemov 	unsigned long next;
1402ba3e694SJoerg Roedel 	int cleared;
141c2febafcSKirill A. Shutemov 
142c2febafcSKirill A. Shutemov 	p4d = p4d_offset(pgd, addr);
143c2febafcSKirill A. Shutemov 	do {
144c2febafcSKirill A. Shutemov 		next = p4d_addr_end(addr, end);
1452ba3e694SJoerg Roedel 
1462ba3e694SJoerg Roedel 		cleared = p4d_clear_huge(p4d);
1472ba3e694SJoerg Roedel 		if (cleared || p4d_bad(*p4d))
1482ba3e694SJoerg Roedel 			*mask |= PGTBL_P4D_MODIFIED;
1492ba3e694SJoerg Roedel 
1502ba3e694SJoerg Roedel 		if (cleared)
151c2febafcSKirill A. Shutemov 			continue;
152c2febafcSKirill A. Shutemov 		if (p4d_none_or_clear_bad(p4d))
153c2febafcSKirill A. Shutemov 			continue;
1542ba3e694SJoerg Roedel 		vunmap_pud_range(p4d, addr, next, mask);
155c2febafcSKirill A. Shutemov 	} while (p4d++, addr = next, addr != end);
156c2febafcSKirill A. Shutemov }
157c2febafcSKirill A. Shutemov 
158b521c43fSChristoph Hellwig /**
159b521c43fSChristoph Hellwig  * unmap_kernel_range_noflush - unmap kernel VM area
1602ba3e694SJoerg Roedel  * @start: start of the VM area to unmap
161b521c43fSChristoph Hellwig  * @size: size of the VM area to unmap
162b521c43fSChristoph Hellwig  *
163b521c43fSChristoph Hellwig  * Unmap PFN_UP(@size) pages at @addr.  The VM area @addr and @size specify
164b521c43fSChristoph Hellwig  * should have been allocated using get_vm_area() and its friends.
165b521c43fSChristoph Hellwig  *
166b521c43fSChristoph Hellwig  * NOTE:
167b521c43fSChristoph Hellwig  * This function does NOT do any cache flushing.  The caller is responsible
168b521c43fSChristoph Hellwig  * for calling flush_cache_vunmap() on to-be-mapped areas before calling this
169b521c43fSChristoph Hellwig  * function and flush_tlb_kernel_range() after.
170b521c43fSChristoph Hellwig  */
1712ba3e694SJoerg Roedel void unmap_kernel_range_noflush(unsigned long start, unsigned long size)
1721da177e4SLinus Torvalds {
1732ba3e694SJoerg Roedel 	unsigned long end = start + size;
1741da177e4SLinus Torvalds 	unsigned long next;
175b521c43fSChristoph Hellwig 	pgd_t *pgd;
1762ba3e694SJoerg Roedel 	unsigned long addr = start;
1772ba3e694SJoerg Roedel 	pgtbl_mod_mask mask = 0;
1781da177e4SLinus Torvalds 
1791da177e4SLinus Torvalds 	BUG_ON(addr >= end);
1801da177e4SLinus Torvalds 	pgd = pgd_offset_k(addr);
1811da177e4SLinus Torvalds 	do {
1821da177e4SLinus Torvalds 		next = pgd_addr_end(addr, end);
1832ba3e694SJoerg Roedel 		if (pgd_bad(*pgd))
1842ba3e694SJoerg Roedel 			mask |= PGTBL_PGD_MODIFIED;
1851da177e4SLinus Torvalds 		if (pgd_none_or_clear_bad(pgd))
1861da177e4SLinus Torvalds 			continue;
1872ba3e694SJoerg Roedel 		vunmap_p4d_range(pgd, addr, next, &mask);
1881da177e4SLinus Torvalds 	} while (pgd++, addr = next, addr != end);
1892ba3e694SJoerg Roedel 
1902ba3e694SJoerg Roedel 	if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
1912ba3e694SJoerg Roedel 		arch_sync_kernel_mappings(start, end);
1921da177e4SLinus Torvalds }
1931da177e4SLinus Torvalds 
1941da177e4SLinus Torvalds static int vmap_pte_range(pmd_t *pmd, unsigned long addr,
1952ba3e694SJoerg Roedel 		unsigned long end, pgprot_t prot, struct page **pages, int *nr,
1962ba3e694SJoerg Roedel 		pgtbl_mod_mask *mask)
1971da177e4SLinus Torvalds {
1981da177e4SLinus Torvalds 	pte_t *pte;
1991da177e4SLinus Torvalds 
200db64fe02SNick Piggin 	/*
201db64fe02SNick Piggin 	 * nr is a running index into the array which helps higher level
202db64fe02SNick Piggin 	 * callers keep track of where we're up to.
203db64fe02SNick Piggin 	 */
204db64fe02SNick Piggin 
2052ba3e694SJoerg Roedel 	pte = pte_alloc_kernel_track(pmd, addr, mask);
2061da177e4SLinus Torvalds 	if (!pte)
2071da177e4SLinus Torvalds 		return -ENOMEM;
2081da177e4SLinus Torvalds 	do {
209db64fe02SNick Piggin 		struct page *page = pages[*nr];
210db64fe02SNick Piggin 
211db64fe02SNick Piggin 		if (WARN_ON(!pte_none(*pte)))
212db64fe02SNick Piggin 			return -EBUSY;
213db64fe02SNick Piggin 		if (WARN_ON(!page))
2141da177e4SLinus Torvalds 			return -ENOMEM;
2151da177e4SLinus Torvalds 		set_pte_at(&init_mm, addr, pte, mk_pte(page, prot));
216db64fe02SNick Piggin 		(*nr)++;
2171da177e4SLinus Torvalds 	} while (pte++, addr += PAGE_SIZE, addr != end);
2182ba3e694SJoerg Roedel 	*mask |= PGTBL_PTE_MODIFIED;
2191da177e4SLinus Torvalds 	return 0;
2201da177e4SLinus Torvalds }
2211da177e4SLinus Torvalds 
222db64fe02SNick Piggin static int vmap_pmd_range(pud_t *pud, unsigned long addr,
2232ba3e694SJoerg Roedel 		unsigned long end, pgprot_t prot, struct page **pages, int *nr,
2242ba3e694SJoerg Roedel 		pgtbl_mod_mask *mask)
2251da177e4SLinus Torvalds {
2261da177e4SLinus Torvalds 	pmd_t *pmd;
2271da177e4SLinus Torvalds 	unsigned long next;
2281da177e4SLinus Torvalds 
2292ba3e694SJoerg Roedel 	pmd = pmd_alloc_track(&init_mm, pud, addr, mask);
2301da177e4SLinus Torvalds 	if (!pmd)
2311da177e4SLinus Torvalds 		return -ENOMEM;
2321da177e4SLinus Torvalds 	do {
2331da177e4SLinus Torvalds 		next = pmd_addr_end(addr, end);
2342ba3e694SJoerg Roedel 		if (vmap_pte_range(pmd, addr, next, prot, pages, nr, mask))
2351da177e4SLinus Torvalds 			return -ENOMEM;
2361da177e4SLinus Torvalds 	} while (pmd++, addr = next, addr != end);
2371da177e4SLinus Torvalds 	return 0;
2381da177e4SLinus Torvalds }
2391da177e4SLinus Torvalds 
240c2febafcSKirill A. Shutemov static int vmap_pud_range(p4d_t *p4d, unsigned long addr,
2412ba3e694SJoerg Roedel 		unsigned long end, pgprot_t prot, struct page **pages, int *nr,
2422ba3e694SJoerg Roedel 		pgtbl_mod_mask *mask)
2431da177e4SLinus Torvalds {
2441da177e4SLinus Torvalds 	pud_t *pud;
2451da177e4SLinus Torvalds 	unsigned long next;
2461da177e4SLinus Torvalds 
2472ba3e694SJoerg Roedel 	pud = pud_alloc_track(&init_mm, p4d, addr, mask);
2481da177e4SLinus Torvalds 	if (!pud)
2491da177e4SLinus Torvalds 		return -ENOMEM;
2501da177e4SLinus Torvalds 	do {
2511da177e4SLinus Torvalds 		next = pud_addr_end(addr, end);
2522ba3e694SJoerg Roedel 		if (vmap_pmd_range(pud, addr, next, prot, pages, nr, mask))
2531da177e4SLinus Torvalds 			return -ENOMEM;
2541da177e4SLinus Torvalds 	} while (pud++, addr = next, addr != end);
2551da177e4SLinus Torvalds 	return 0;
2561da177e4SLinus Torvalds }
2571da177e4SLinus Torvalds 
258c2febafcSKirill A. Shutemov static int vmap_p4d_range(pgd_t *pgd, unsigned long addr,
2592ba3e694SJoerg Roedel 		unsigned long end, pgprot_t prot, struct page **pages, int *nr,
2602ba3e694SJoerg Roedel 		pgtbl_mod_mask *mask)
261c2febafcSKirill A. Shutemov {
262c2febafcSKirill A. Shutemov 	p4d_t *p4d;
263c2febafcSKirill A. Shutemov 	unsigned long next;
264c2febafcSKirill A. Shutemov 
2652ba3e694SJoerg Roedel 	p4d = p4d_alloc_track(&init_mm, pgd, addr, mask);
266c2febafcSKirill A. Shutemov 	if (!p4d)
267c2febafcSKirill A. Shutemov 		return -ENOMEM;
268c2febafcSKirill A. Shutemov 	do {
269c2febafcSKirill A. Shutemov 		next = p4d_addr_end(addr, end);
2702ba3e694SJoerg Roedel 		if (vmap_pud_range(p4d, addr, next, prot, pages, nr, mask))
271c2febafcSKirill A. Shutemov 			return -ENOMEM;
272c2febafcSKirill A. Shutemov 	} while (p4d++, addr = next, addr != end);
273c2febafcSKirill A. Shutemov 	return 0;
274c2febafcSKirill A. Shutemov }
275c2febafcSKirill A. Shutemov 
276b521c43fSChristoph Hellwig /**
277b521c43fSChristoph Hellwig  * map_kernel_range_noflush - map kernel VM area with the specified pages
278b521c43fSChristoph Hellwig  * @addr: start of the VM area to map
279b521c43fSChristoph Hellwig  * @size: size of the VM area to map
280b521c43fSChristoph Hellwig  * @prot: page protection flags to use
281b521c43fSChristoph Hellwig  * @pages: pages to map
282db64fe02SNick Piggin  *
283b521c43fSChristoph Hellwig  * Map PFN_UP(@size) pages at @addr.  The VM area @addr and @size specify should
284b521c43fSChristoph Hellwig  * have been allocated using get_vm_area() and its friends.
285b521c43fSChristoph Hellwig  *
286b521c43fSChristoph Hellwig  * NOTE:
287b521c43fSChristoph Hellwig  * This function does NOT do any cache flushing.  The caller is responsible for
288b521c43fSChristoph Hellwig  * calling flush_cache_vmap() on to-be-mapped areas before calling this
289b521c43fSChristoph Hellwig  * function.
290b521c43fSChristoph Hellwig  *
291b521c43fSChristoph Hellwig  * RETURNS:
29260bb4465SChristoph Hellwig  * 0 on success, -errno on failure.
293db64fe02SNick Piggin  */
294b521c43fSChristoph Hellwig int map_kernel_range_noflush(unsigned long addr, unsigned long size,
295db64fe02SNick Piggin 			     pgprot_t prot, struct page **pages)
2961da177e4SLinus Torvalds {
2972ba3e694SJoerg Roedel 	unsigned long start = addr;
298b521c43fSChristoph Hellwig 	unsigned long end = addr + size;
2991da177e4SLinus Torvalds 	unsigned long next;
300b521c43fSChristoph Hellwig 	pgd_t *pgd;
301db64fe02SNick Piggin 	int err = 0;
302db64fe02SNick Piggin 	int nr = 0;
3032ba3e694SJoerg Roedel 	pgtbl_mod_mask mask = 0;
3041da177e4SLinus Torvalds 
3051da177e4SLinus Torvalds 	BUG_ON(addr >= end);
3061da177e4SLinus Torvalds 	pgd = pgd_offset_k(addr);
3071da177e4SLinus Torvalds 	do {
3081da177e4SLinus Torvalds 		next = pgd_addr_end(addr, end);
3092ba3e694SJoerg Roedel 		if (pgd_bad(*pgd))
3102ba3e694SJoerg Roedel 			mask |= PGTBL_PGD_MODIFIED;
3112ba3e694SJoerg Roedel 		err = vmap_p4d_range(pgd, addr, next, prot, pages, &nr, &mask);
3121da177e4SLinus Torvalds 		if (err)
313bf88c8c8SFigo.zhang 			return err;
3141da177e4SLinus Torvalds 	} while (pgd++, addr = next, addr != end);
315db64fe02SNick Piggin 
3162ba3e694SJoerg Roedel 	if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
3172ba3e694SJoerg Roedel 		arch_sync_kernel_mappings(start, end);
3182ba3e694SJoerg Roedel 
31960bb4465SChristoph Hellwig 	return 0;
3201da177e4SLinus Torvalds }
3211da177e4SLinus Torvalds 
322ed1f324cSChristoph Hellwig int map_kernel_range(unsigned long start, unsigned long size, pgprot_t prot,
323ed1f324cSChristoph Hellwig 		struct page **pages)
3248fc48985STejun Heo {
3258fc48985STejun Heo 	int ret;
3268fc48985STejun Heo 
327a29adb62SChristoph Hellwig 	ret = map_kernel_range_noflush(start, size, prot, pages);
328a29adb62SChristoph Hellwig 	flush_cache_vmap(start, start + size);
3298fc48985STejun Heo 	return ret;
3308fc48985STejun Heo }
3318fc48985STejun Heo 
33281ac3ad9SKAMEZAWA Hiroyuki int is_vmalloc_or_module_addr(const void *x)
33373bdf0a6SLinus Torvalds {
33473bdf0a6SLinus Torvalds 	/*
335ab4f2ee1SRussell King 	 * ARM, x86-64 and sparc64 put modules in a special place,
33673bdf0a6SLinus Torvalds 	 * and fall back on vmalloc() if that fails. Others
33773bdf0a6SLinus Torvalds 	 * just put it in the vmalloc space.
33873bdf0a6SLinus Torvalds 	 */
33973bdf0a6SLinus Torvalds #if defined(CONFIG_MODULES) && defined(MODULES_VADDR)
34073bdf0a6SLinus Torvalds 	unsigned long addr = (unsigned long)x;
34173bdf0a6SLinus Torvalds 	if (addr >= MODULES_VADDR && addr < MODULES_END)
34273bdf0a6SLinus Torvalds 		return 1;
34373bdf0a6SLinus Torvalds #endif
34473bdf0a6SLinus Torvalds 	return is_vmalloc_addr(x);
34573bdf0a6SLinus Torvalds }
34673bdf0a6SLinus Torvalds 
34748667e7aSChristoph Lameter /*
348add688fbSmalc  * Walk a vmap address to the struct page it maps.
34948667e7aSChristoph Lameter  */
350add688fbSmalc struct page *vmalloc_to_page(const void *vmalloc_addr)
35148667e7aSChristoph Lameter {
35248667e7aSChristoph Lameter 	unsigned long addr = (unsigned long) vmalloc_addr;
353add688fbSmalc 	struct page *page = NULL;
35448667e7aSChristoph Lameter 	pgd_t *pgd = pgd_offset_k(addr);
355c2febafcSKirill A. Shutemov 	p4d_t *p4d;
356c2febafcSKirill A. Shutemov 	pud_t *pud;
357c2febafcSKirill A. Shutemov 	pmd_t *pmd;
358c2febafcSKirill A. Shutemov 	pte_t *ptep, pte;
35948667e7aSChristoph Lameter 
3607aa413deSIngo Molnar 	/*
3617aa413deSIngo Molnar 	 * XXX we might need to change this if we add VIRTUAL_BUG_ON for
3627aa413deSIngo Molnar 	 * architectures that do not vmalloc module space
3637aa413deSIngo Molnar 	 */
36473bdf0a6SLinus Torvalds 	VIRTUAL_BUG_ON(!is_vmalloc_or_module_addr(vmalloc_addr));
36559ea7463SJiri Slaby 
366c2febafcSKirill A. Shutemov 	if (pgd_none(*pgd))
367c2febafcSKirill A. Shutemov 		return NULL;
368c2febafcSKirill A. Shutemov 	p4d = p4d_offset(pgd, addr);
369c2febafcSKirill A. Shutemov 	if (p4d_none(*p4d))
370c2febafcSKirill A. Shutemov 		return NULL;
371c2febafcSKirill A. Shutemov 	pud = pud_offset(p4d, addr);
372029c54b0SArd Biesheuvel 
373029c54b0SArd Biesheuvel 	/*
374029c54b0SArd Biesheuvel 	 * Don't dereference bad PUD or PMD (below) entries. This will also
375029c54b0SArd Biesheuvel 	 * identify huge mappings, which we may encounter on architectures
376029c54b0SArd Biesheuvel 	 * that define CONFIG_HAVE_ARCH_HUGE_VMAP=y. Such regions will be
377029c54b0SArd Biesheuvel 	 * identified as vmalloc addresses by is_vmalloc_addr(), but are
378029c54b0SArd Biesheuvel 	 * not [unambiguously] associated with a struct page, so there is
379029c54b0SArd Biesheuvel 	 * no correct value to return for them.
380029c54b0SArd Biesheuvel 	 */
381029c54b0SArd Biesheuvel 	WARN_ON_ONCE(pud_bad(*pud));
382029c54b0SArd Biesheuvel 	if (pud_none(*pud) || pud_bad(*pud))
383c2febafcSKirill A. Shutemov 		return NULL;
384c2febafcSKirill A. Shutemov 	pmd = pmd_offset(pud, addr);
385029c54b0SArd Biesheuvel 	WARN_ON_ONCE(pmd_bad(*pmd));
386029c54b0SArd Biesheuvel 	if (pmd_none(*pmd) || pmd_bad(*pmd))
387c2febafcSKirill A. Shutemov 		return NULL;
388db64fe02SNick Piggin 
38948667e7aSChristoph Lameter 	ptep = pte_offset_map(pmd, addr);
39048667e7aSChristoph Lameter 	pte = *ptep;
39148667e7aSChristoph Lameter 	if (pte_present(pte))
392add688fbSmalc 		page = pte_page(pte);
39348667e7aSChristoph Lameter 	pte_unmap(ptep);
394add688fbSmalc 	return page;
395ece86e22SJianyu Zhan }
396ece86e22SJianyu Zhan EXPORT_SYMBOL(vmalloc_to_page);
397ece86e22SJianyu Zhan 
398add688fbSmalc /*
399add688fbSmalc  * Map a vmalloc()-space virtual address to the physical page frame number.
400add688fbSmalc  */
401add688fbSmalc unsigned long vmalloc_to_pfn(const void *vmalloc_addr)
402add688fbSmalc {
403add688fbSmalc 	return page_to_pfn(vmalloc_to_page(vmalloc_addr));
404add688fbSmalc }
405add688fbSmalc EXPORT_SYMBOL(vmalloc_to_pfn);
406add688fbSmalc 
407db64fe02SNick Piggin 
408db64fe02SNick Piggin /*** Global kva allocator ***/
409db64fe02SNick Piggin 
410bb850f4dSUladzislau Rezki (Sony) #define DEBUG_AUGMENT_PROPAGATE_CHECK 0
411a6cf4e0fSUladzislau Rezki (Sony) #define DEBUG_AUGMENT_LOWEST_MATCH_CHECK 0
412bb850f4dSUladzislau Rezki (Sony) 
413db64fe02SNick Piggin 
414db64fe02SNick Piggin static DEFINE_SPINLOCK(vmap_area_lock);
415e36176beSUladzislau Rezki (Sony) static DEFINE_SPINLOCK(free_vmap_area_lock);
416f1c4069eSJoonsoo Kim /* Export for kexec only */
417f1c4069eSJoonsoo Kim LIST_HEAD(vmap_area_list);
41880c4bd7aSChris Wilson static LLIST_HEAD(vmap_purge_list);
41989699605SNick Piggin static struct rb_root vmap_area_root = RB_ROOT;
42068ad4a33SUladzislau Rezki (Sony) static bool vmap_initialized __read_mostly;
42189699605SNick Piggin 
42268ad4a33SUladzislau Rezki (Sony) /*
42368ad4a33SUladzislau Rezki (Sony)  * This kmem_cache is used for vmap_area objects. Instead of
42468ad4a33SUladzislau Rezki (Sony)  * allocating from slab we reuse an object from this cache to
42568ad4a33SUladzislau Rezki (Sony)  * make things faster. Especially in "no edge" splitting of
42668ad4a33SUladzislau Rezki (Sony)  * free block.
42768ad4a33SUladzislau Rezki (Sony)  */
42868ad4a33SUladzislau Rezki (Sony) static struct kmem_cache *vmap_area_cachep;
42989699605SNick Piggin 
43068ad4a33SUladzislau Rezki (Sony) /*
43168ad4a33SUladzislau Rezki (Sony)  * This linked list is used in pair with free_vmap_area_root.
43268ad4a33SUladzislau Rezki (Sony)  * It gives O(1) access to prev/next to perform fast coalescing.
43368ad4a33SUladzislau Rezki (Sony)  */
43468ad4a33SUladzislau Rezki (Sony) static LIST_HEAD(free_vmap_area_list);
43568ad4a33SUladzislau Rezki (Sony) 
43668ad4a33SUladzislau Rezki (Sony) /*
43768ad4a33SUladzislau Rezki (Sony)  * This augment red-black tree represents the free vmap space.
43868ad4a33SUladzislau Rezki (Sony)  * All vmap_area objects in this tree are sorted by va->va_start
43968ad4a33SUladzislau Rezki (Sony)  * address. It is used for allocation and merging when a vmap
44068ad4a33SUladzislau Rezki (Sony)  * object is released.
44168ad4a33SUladzislau Rezki (Sony)  *
44268ad4a33SUladzislau Rezki (Sony)  * Each vmap_area node contains a maximum available free block
44368ad4a33SUladzislau Rezki (Sony)  * of its sub-tree, right or left. Therefore it is possible to
44468ad4a33SUladzislau Rezki (Sony)  * find a lowest match of free area.
44568ad4a33SUladzislau Rezki (Sony)  */
44668ad4a33SUladzislau Rezki (Sony) static struct rb_root free_vmap_area_root = RB_ROOT;
44768ad4a33SUladzislau Rezki (Sony) 
44882dd23e8SUladzislau Rezki (Sony) /*
44982dd23e8SUladzislau Rezki (Sony)  * Preload a CPU with one object for "no edge" split case. The
45082dd23e8SUladzislau Rezki (Sony)  * aim is to get rid of allocations from the atomic context, thus
45182dd23e8SUladzislau Rezki (Sony)  * to use more permissive allocation masks.
45282dd23e8SUladzislau Rezki (Sony)  */
45382dd23e8SUladzislau Rezki (Sony) static DEFINE_PER_CPU(struct vmap_area *, ne_fit_preload_node);
45482dd23e8SUladzislau Rezki (Sony) 
45568ad4a33SUladzislau Rezki (Sony) static __always_inline unsigned long
45668ad4a33SUladzislau Rezki (Sony) va_size(struct vmap_area *va)
45768ad4a33SUladzislau Rezki (Sony) {
45868ad4a33SUladzislau Rezki (Sony) 	return (va->va_end - va->va_start);
45968ad4a33SUladzislau Rezki (Sony) }
46068ad4a33SUladzislau Rezki (Sony) 
46168ad4a33SUladzislau Rezki (Sony) static __always_inline unsigned long
46268ad4a33SUladzislau Rezki (Sony) get_subtree_max_size(struct rb_node *node)
46368ad4a33SUladzislau Rezki (Sony) {
46468ad4a33SUladzislau Rezki (Sony) 	struct vmap_area *va;
46568ad4a33SUladzislau Rezki (Sony) 
46668ad4a33SUladzislau Rezki (Sony) 	va = rb_entry_safe(node, struct vmap_area, rb_node);
46768ad4a33SUladzislau Rezki (Sony) 	return va ? va->subtree_max_size : 0;
46868ad4a33SUladzislau Rezki (Sony) }
46968ad4a33SUladzislau Rezki (Sony) 
47068ad4a33SUladzislau Rezki (Sony) /*
47168ad4a33SUladzislau Rezki (Sony)  * Gets called when remove the node and rotate.
47268ad4a33SUladzislau Rezki (Sony)  */
47368ad4a33SUladzislau Rezki (Sony) static __always_inline unsigned long
47468ad4a33SUladzislau Rezki (Sony) compute_subtree_max_size(struct vmap_area *va)
47568ad4a33SUladzislau Rezki (Sony) {
47668ad4a33SUladzislau Rezki (Sony) 	return max3(va_size(va),
47768ad4a33SUladzislau Rezki (Sony) 		get_subtree_max_size(va->rb_node.rb_left),
47868ad4a33SUladzislau Rezki (Sony) 		get_subtree_max_size(va->rb_node.rb_right));
47968ad4a33SUladzislau Rezki (Sony) }
48068ad4a33SUladzislau Rezki (Sony) 
481315cc066SMichel Lespinasse RB_DECLARE_CALLBACKS_MAX(static, free_vmap_area_rb_augment_cb,
482315cc066SMichel Lespinasse 	struct vmap_area, rb_node, unsigned long, subtree_max_size, va_size)
48368ad4a33SUladzislau Rezki (Sony) 
48468ad4a33SUladzislau Rezki (Sony) static void purge_vmap_area_lazy(void);
48568ad4a33SUladzislau Rezki (Sony) static BLOCKING_NOTIFIER_HEAD(vmap_notify_list);
48668ad4a33SUladzislau Rezki (Sony) static unsigned long lazy_max_pages(void);
487db64fe02SNick Piggin 
48897105f0aSRoman Gushchin static atomic_long_t nr_vmalloc_pages;
48997105f0aSRoman Gushchin 
49097105f0aSRoman Gushchin unsigned long vmalloc_nr_pages(void)
49197105f0aSRoman Gushchin {
49297105f0aSRoman Gushchin 	return atomic_long_read(&nr_vmalloc_pages);
49397105f0aSRoman Gushchin }
49497105f0aSRoman Gushchin 
495db64fe02SNick Piggin static struct vmap_area *__find_vmap_area(unsigned long addr)
4961da177e4SLinus Torvalds {
497db64fe02SNick Piggin 	struct rb_node *n = vmap_area_root.rb_node;
498db64fe02SNick Piggin 
499db64fe02SNick Piggin 	while (n) {
500db64fe02SNick Piggin 		struct vmap_area *va;
501db64fe02SNick Piggin 
502db64fe02SNick Piggin 		va = rb_entry(n, struct vmap_area, rb_node);
503db64fe02SNick Piggin 		if (addr < va->va_start)
504db64fe02SNick Piggin 			n = n->rb_left;
505cef2ac3fSHATAYAMA Daisuke 		else if (addr >= va->va_end)
506db64fe02SNick Piggin 			n = n->rb_right;
507db64fe02SNick Piggin 		else
508db64fe02SNick Piggin 			return va;
509db64fe02SNick Piggin 	}
510db64fe02SNick Piggin 
511db64fe02SNick Piggin 	return NULL;
512db64fe02SNick Piggin }
513db64fe02SNick Piggin 
51468ad4a33SUladzislau Rezki (Sony) /*
51568ad4a33SUladzislau Rezki (Sony)  * This function returns back addresses of parent node
51668ad4a33SUladzislau Rezki (Sony)  * and its left or right link for further processing.
5179c801f61SUladzislau Rezki (Sony)  *
5189c801f61SUladzislau Rezki (Sony)  * Otherwise NULL is returned. In that case all further
5199c801f61SUladzislau Rezki (Sony)  * steps regarding inserting of conflicting overlap range
5209c801f61SUladzislau Rezki (Sony)  * have to be declined and actually considered as a bug.
52168ad4a33SUladzislau Rezki (Sony)  */
52268ad4a33SUladzislau Rezki (Sony) static __always_inline struct rb_node **
52368ad4a33SUladzislau Rezki (Sony) find_va_links(struct vmap_area *va,
52468ad4a33SUladzislau Rezki (Sony) 	struct rb_root *root, struct rb_node *from,
52568ad4a33SUladzislau Rezki (Sony) 	struct rb_node **parent)
526db64fe02SNick Piggin {
527170168d0SNamhyung Kim 	struct vmap_area *tmp_va;
52868ad4a33SUladzislau Rezki (Sony) 	struct rb_node **link;
529db64fe02SNick Piggin 
53068ad4a33SUladzislau Rezki (Sony) 	if (root) {
53168ad4a33SUladzislau Rezki (Sony) 		link = &root->rb_node;
53268ad4a33SUladzislau Rezki (Sony) 		if (unlikely(!*link)) {
53368ad4a33SUladzislau Rezki (Sony) 			*parent = NULL;
53468ad4a33SUladzislau Rezki (Sony) 			return link;
53568ad4a33SUladzislau Rezki (Sony) 		}
53668ad4a33SUladzislau Rezki (Sony) 	} else {
53768ad4a33SUladzislau Rezki (Sony) 		link = &from;
53868ad4a33SUladzislau Rezki (Sony) 	}
53968ad4a33SUladzislau Rezki (Sony) 
54068ad4a33SUladzislau Rezki (Sony) 	/*
54168ad4a33SUladzislau Rezki (Sony) 	 * Go to the bottom of the tree. When we hit the last point
54268ad4a33SUladzislau Rezki (Sony) 	 * we end up with parent rb_node and correct direction, i name
54368ad4a33SUladzislau Rezki (Sony) 	 * it link, where the new va->rb_node will be attached to.
54468ad4a33SUladzislau Rezki (Sony) 	 */
54568ad4a33SUladzislau Rezki (Sony) 	do {
54668ad4a33SUladzislau Rezki (Sony) 		tmp_va = rb_entry(*link, struct vmap_area, rb_node);
54768ad4a33SUladzislau Rezki (Sony) 
54868ad4a33SUladzislau Rezki (Sony) 		/*
54968ad4a33SUladzislau Rezki (Sony) 		 * During the traversal we also do some sanity check.
55068ad4a33SUladzislau Rezki (Sony) 		 * Trigger the BUG() if there are sides(left/right)
55168ad4a33SUladzislau Rezki (Sony) 		 * or full overlaps.
55268ad4a33SUladzislau Rezki (Sony) 		 */
55368ad4a33SUladzislau Rezki (Sony) 		if (va->va_start < tmp_va->va_end &&
55468ad4a33SUladzislau Rezki (Sony) 				va->va_end <= tmp_va->va_start)
55568ad4a33SUladzislau Rezki (Sony) 			link = &(*link)->rb_left;
55668ad4a33SUladzislau Rezki (Sony) 		else if (va->va_end > tmp_va->va_start &&
55768ad4a33SUladzislau Rezki (Sony) 				va->va_start >= tmp_va->va_end)
55868ad4a33SUladzislau Rezki (Sony) 			link = &(*link)->rb_right;
5599c801f61SUladzislau Rezki (Sony) 		else {
5609c801f61SUladzislau Rezki (Sony) 			WARN(1, "vmalloc bug: 0x%lx-0x%lx overlaps with 0x%lx-0x%lx\n",
5619c801f61SUladzislau Rezki (Sony) 				va->va_start, va->va_end, tmp_va->va_start, tmp_va->va_end);
5629c801f61SUladzislau Rezki (Sony) 
5639c801f61SUladzislau Rezki (Sony) 			return NULL;
5649c801f61SUladzislau Rezki (Sony) 		}
56568ad4a33SUladzislau Rezki (Sony) 	} while (*link);
56668ad4a33SUladzislau Rezki (Sony) 
56768ad4a33SUladzislau Rezki (Sony) 	*parent = &tmp_va->rb_node;
56868ad4a33SUladzislau Rezki (Sony) 	return link;
569db64fe02SNick Piggin }
570db64fe02SNick Piggin 
57168ad4a33SUladzislau Rezki (Sony) static __always_inline struct list_head *
57268ad4a33SUladzislau Rezki (Sony) get_va_next_sibling(struct rb_node *parent, struct rb_node **link)
57368ad4a33SUladzislau Rezki (Sony) {
57468ad4a33SUladzislau Rezki (Sony) 	struct list_head *list;
575db64fe02SNick Piggin 
57668ad4a33SUladzislau Rezki (Sony) 	if (unlikely(!parent))
57768ad4a33SUladzislau Rezki (Sony) 		/*
57868ad4a33SUladzislau Rezki (Sony) 		 * The red-black tree where we try to find VA neighbors
57968ad4a33SUladzislau Rezki (Sony) 		 * before merging or inserting is empty, i.e. it means
58068ad4a33SUladzislau Rezki (Sony) 		 * there is no free vmap space. Normally it does not
58168ad4a33SUladzislau Rezki (Sony) 		 * happen but we handle this case anyway.
58268ad4a33SUladzislau Rezki (Sony) 		 */
58368ad4a33SUladzislau Rezki (Sony) 		return NULL;
58468ad4a33SUladzislau Rezki (Sony) 
58568ad4a33SUladzislau Rezki (Sony) 	list = &rb_entry(parent, struct vmap_area, rb_node)->list;
58668ad4a33SUladzislau Rezki (Sony) 	return (&parent->rb_right == link ? list->next : list);
587db64fe02SNick Piggin }
588db64fe02SNick Piggin 
58968ad4a33SUladzislau Rezki (Sony) static __always_inline void
59068ad4a33SUladzislau Rezki (Sony) link_va(struct vmap_area *va, struct rb_root *root,
59168ad4a33SUladzislau Rezki (Sony) 	struct rb_node *parent, struct rb_node **link, struct list_head *head)
59268ad4a33SUladzislau Rezki (Sony) {
59368ad4a33SUladzislau Rezki (Sony) 	/*
59468ad4a33SUladzislau Rezki (Sony) 	 * VA is still not in the list, but we can
59568ad4a33SUladzislau Rezki (Sony) 	 * identify its future previous list_head node.
59668ad4a33SUladzislau Rezki (Sony) 	 */
59768ad4a33SUladzislau Rezki (Sony) 	if (likely(parent)) {
59868ad4a33SUladzislau Rezki (Sony) 		head = &rb_entry(parent, struct vmap_area, rb_node)->list;
59968ad4a33SUladzislau Rezki (Sony) 		if (&parent->rb_right != link)
60068ad4a33SUladzislau Rezki (Sony) 			head = head->prev;
60168ad4a33SUladzislau Rezki (Sony) 	}
602db64fe02SNick Piggin 
60368ad4a33SUladzislau Rezki (Sony) 	/* Insert to the rb-tree */
60468ad4a33SUladzislau Rezki (Sony) 	rb_link_node(&va->rb_node, parent, link);
60568ad4a33SUladzislau Rezki (Sony) 	if (root == &free_vmap_area_root) {
60668ad4a33SUladzislau Rezki (Sony) 		/*
60768ad4a33SUladzislau Rezki (Sony) 		 * Some explanation here. Just perform simple insertion
60868ad4a33SUladzislau Rezki (Sony) 		 * to the tree. We do not set va->subtree_max_size to
60968ad4a33SUladzislau Rezki (Sony) 		 * its current size before calling rb_insert_augmented().
61068ad4a33SUladzislau Rezki (Sony) 		 * It is because of we populate the tree from the bottom
61168ad4a33SUladzislau Rezki (Sony) 		 * to parent levels when the node _is_ in the tree.
61268ad4a33SUladzislau Rezki (Sony) 		 *
61368ad4a33SUladzislau Rezki (Sony) 		 * Therefore we set subtree_max_size to zero after insertion,
61468ad4a33SUladzislau Rezki (Sony) 		 * to let __augment_tree_propagate_from() puts everything to
61568ad4a33SUladzislau Rezki (Sony) 		 * the correct order later on.
61668ad4a33SUladzislau Rezki (Sony) 		 */
61768ad4a33SUladzislau Rezki (Sony) 		rb_insert_augmented(&va->rb_node,
61868ad4a33SUladzislau Rezki (Sony) 			root, &free_vmap_area_rb_augment_cb);
61968ad4a33SUladzislau Rezki (Sony) 		va->subtree_max_size = 0;
62068ad4a33SUladzislau Rezki (Sony) 	} else {
62168ad4a33SUladzislau Rezki (Sony) 		rb_insert_color(&va->rb_node, root);
62268ad4a33SUladzislau Rezki (Sony) 	}
62368ad4a33SUladzislau Rezki (Sony) 
62468ad4a33SUladzislau Rezki (Sony) 	/* Address-sort this list */
62568ad4a33SUladzislau Rezki (Sony) 	list_add(&va->list, head);
62668ad4a33SUladzislau Rezki (Sony) }
62768ad4a33SUladzislau Rezki (Sony) 
62868ad4a33SUladzislau Rezki (Sony) static __always_inline void
62968ad4a33SUladzislau Rezki (Sony) unlink_va(struct vmap_area *va, struct rb_root *root)
63068ad4a33SUladzislau Rezki (Sony) {
631460e42d1SUladzislau Rezki (Sony) 	if (WARN_ON(RB_EMPTY_NODE(&va->rb_node)))
632460e42d1SUladzislau Rezki (Sony) 		return;
633460e42d1SUladzislau Rezki (Sony) 
63468ad4a33SUladzislau Rezki (Sony) 	if (root == &free_vmap_area_root)
63568ad4a33SUladzislau Rezki (Sony) 		rb_erase_augmented(&va->rb_node,
63668ad4a33SUladzislau Rezki (Sony) 			root, &free_vmap_area_rb_augment_cb);
63768ad4a33SUladzislau Rezki (Sony) 	else
63868ad4a33SUladzislau Rezki (Sony) 		rb_erase(&va->rb_node, root);
63968ad4a33SUladzislau Rezki (Sony) 
64068ad4a33SUladzislau Rezki (Sony) 	list_del(&va->list);
64168ad4a33SUladzislau Rezki (Sony) 	RB_CLEAR_NODE(&va->rb_node);
64268ad4a33SUladzislau Rezki (Sony) }
64368ad4a33SUladzislau Rezki (Sony) 
644bb850f4dSUladzislau Rezki (Sony) #if DEBUG_AUGMENT_PROPAGATE_CHECK
645bb850f4dSUladzislau Rezki (Sony) static void
646da27c9edSUladzislau Rezki (Sony) augment_tree_propagate_check(void)
647bb850f4dSUladzislau Rezki (Sony) {
648bb850f4dSUladzislau Rezki (Sony) 	struct vmap_area *va;
649da27c9edSUladzislau Rezki (Sony) 	unsigned long computed_size;
650bb850f4dSUladzislau Rezki (Sony) 
651da27c9edSUladzislau Rezki (Sony) 	list_for_each_entry(va, &free_vmap_area_list, list) {
652da27c9edSUladzislau Rezki (Sony) 		computed_size = compute_subtree_max_size(va);
653da27c9edSUladzislau Rezki (Sony) 		if (computed_size != va->subtree_max_size)
654bb850f4dSUladzislau Rezki (Sony) 			pr_emerg("tree is corrupted: %lu, %lu\n",
655bb850f4dSUladzislau Rezki (Sony) 				va_size(va), va->subtree_max_size);
656bb850f4dSUladzislau Rezki (Sony) 	}
657bb850f4dSUladzislau Rezki (Sony) }
658bb850f4dSUladzislau Rezki (Sony) #endif
659bb850f4dSUladzislau Rezki (Sony) 
66068ad4a33SUladzislau Rezki (Sony) /*
66168ad4a33SUladzislau Rezki (Sony)  * This function populates subtree_max_size from bottom to upper
66268ad4a33SUladzislau Rezki (Sony)  * levels starting from VA point. The propagation must be done
66368ad4a33SUladzislau Rezki (Sony)  * when VA size is modified by changing its va_start/va_end. Or
66468ad4a33SUladzislau Rezki (Sony)  * in case of newly inserting of VA to the tree.
66568ad4a33SUladzislau Rezki (Sony)  *
66668ad4a33SUladzislau Rezki (Sony)  * It means that __augment_tree_propagate_from() must be called:
66768ad4a33SUladzislau Rezki (Sony)  * - After VA has been inserted to the tree(free path);
66868ad4a33SUladzislau Rezki (Sony)  * - After VA has been shrunk(allocation path);
66968ad4a33SUladzislau Rezki (Sony)  * - After VA has been increased(merging path).
67068ad4a33SUladzislau Rezki (Sony)  *
67168ad4a33SUladzislau Rezki (Sony)  * Please note that, it does not mean that upper parent nodes
67268ad4a33SUladzislau Rezki (Sony)  * and their subtree_max_size are recalculated all the time up
67368ad4a33SUladzislau Rezki (Sony)  * to the root node.
67468ad4a33SUladzislau Rezki (Sony)  *
67568ad4a33SUladzislau Rezki (Sony)  *       4--8
67668ad4a33SUladzislau Rezki (Sony)  *        /\
67768ad4a33SUladzislau Rezki (Sony)  *       /  \
67868ad4a33SUladzislau Rezki (Sony)  *      /    \
67968ad4a33SUladzislau Rezki (Sony)  *    2--2  8--8
68068ad4a33SUladzislau Rezki (Sony)  *
68168ad4a33SUladzislau Rezki (Sony)  * For example if we modify the node 4, shrinking it to 2, then
68268ad4a33SUladzislau Rezki (Sony)  * no any modification is required. If we shrink the node 2 to 1
68368ad4a33SUladzislau Rezki (Sony)  * its subtree_max_size is updated only, and set to 1. If we shrink
68468ad4a33SUladzislau Rezki (Sony)  * the node 8 to 6, then its subtree_max_size is set to 6 and parent
68568ad4a33SUladzislau Rezki (Sony)  * node becomes 4--6.
68668ad4a33SUladzislau Rezki (Sony)  */
68768ad4a33SUladzislau Rezki (Sony) static __always_inline void
68868ad4a33SUladzislau Rezki (Sony) augment_tree_propagate_from(struct vmap_area *va)
68968ad4a33SUladzislau Rezki (Sony) {
69068ad4a33SUladzislau Rezki (Sony) 	/*
69115ae144fSUladzislau Rezki (Sony) 	 * Populate the tree from bottom towards the root until
69215ae144fSUladzislau Rezki (Sony) 	 * the calculated maximum available size of checked node
69315ae144fSUladzislau Rezki (Sony) 	 * is equal to its current one.
69468ad4a33SUladzislau Rezki (Sony) 	 */
69515ae144fSUladzislau Rezki (Sony) 	free_vmap_area_rb_augment_cb_propagate(&va->rb_node, NULL);
696bb850f4dSUladzislau Rezki (Sony) 
697bb850f4dSUladzislau Rezki (Sony) #if DEBUG_AUGMENT_PROPAGATE_CHECK
698da27c9edSUladzislau Rezki (Sony) 	augment_tree_propagate_check();
699bb850f4dSUladzislau Rezki (Sony) #endif
70068ad4a33SUladzislau Rezki (Sony) }
70168ad4a33SUladzislau Rezki (Sony) 
70268ad4a33SUladzislau Rezki (Sony) static void
70368ad4a33SUladzislau Rezki (Sony) insert_vmap_area(struct vmap_area *va,
70468ad4a33SUladzislau Rezki (Sony) 	struct rb_root *root, struct list_head *head)
70568ad4a33SUladzislau Rezki (Sony) {
70668ad4a33SUladzislau Rezki (Sony) 	struct rb_node **link;
70768ad4a33SUladzislau Rezki (Sony) 	struct rb_node *parent;
70868ad4a33SUladzislau Rezki (Sony) 
70968ad4a33SUladzislau Rezki (Sony) 	link = find_va_links(va, root, NULL, &parent);
7109c801f61SUladzislau Rezki (Sony) 	if (link)
71168ad4a33SUladzislau Rezki (Sony) 		link_va(va, root, parent, link, head);
71268ad4a33SUladzislau Rezki (Sony) }
71368ad4a33SUladzislau Rezki (Sony) 
71468ad4a33SUladzislau Rezki (Sony) static void
71568ad4a33SUladzislau Rezki (Sony) insert_vmap_area_augment(struct vmap_area *va,
71668ad4a33SUladzislau Rezki (Sony) 	struct rb_node *from, struct rb_root *root,
71768ad4a33SUladzislau Rezki (Sony) 	struct list_head *head)
71868ad4a33SUladzislau Rezki (Sony) {
71968ad4a33SUladzislau Rezki (Sony) 	struct rb_node **link;
72068ad4a33SUladzislau Rezki (Sony) 	struct rb_node *parent;
72168ad4a33SUladzislau Rezki (Sony) 
72268ad4a33SUladzislau Rezki (Sony) 	if (from)
72368ad4a33SUladzislau Rezki (Sony) 		link = find_va_links(va, NULL, from, &parent);
72468ad4a33SUladzislau Rezki (Sony) 	else
72568ad4a33SUladzislau Rezki (Sony) 		link = find_va_links(va, root, NULL, &parent);
72668ad4a33SUladzislau Rezki (Sony) 
7279c801f61SUladzislau Rezki (Sony) 	if (link) {
72868ad4a33SUladzislau Rezki (Sony) 		link_va(va, root, parent, link, head);
72968ad4a33SUladzislau Rezki (Sony) 		augment_tree_propagate_from(va);
73068ad4a33SUladzislau Rezki (Sony) 	}
7319c801f61SUladzislau Rezki (Sony) }
73268ad4a33SUladzislau Rezki (Sony) 
73368ad4a33SUladzislau Rezki (Sony) /*
73468ad4a33SUladzislau Rezki (Sony)  * Merge de-allocated chunk of VA memory with previous
73568ad4a33SUladzislau Rezki (Sony)  * and next free blocks. If coalesce is not done a new
73668ad4a33SUladzislau Rezki (Sony)  * free area is inserted. If VA has been merged, it is
73768ad4a33SUladzislau Rezki (Sony)  * freed.
7389c801f61SUladzislau Rezki (Sony)  *
7399c801f61SUladzislau Rezki (Sony)  * Please note, it can return NULL in case of overlap
7409c801f61SUladzislau Rezki (Sony)  * ranges, followed by WARN() report. Despite it is a
7419c801f61SUladzislau Rezki (Sony)  * buggy behaviour, a system can be alive and keep
7429c801f61SUladzislau Rezki (Sony)  * ongoing.
74368ad4a33SUladzislau Rezki (Sony)  */
7443c5c3cfbSDaniel Axtens static __always_inline struct vmap_area *
74568ad4a33SUladzislau Rezki (Sony) merge_or_add_vmap_area(struct vmap_area *va,
74668ad4a33SUladzislau Rezki (Sony) 	struct rb_root *root, struct list_head *head)
74768ad4a33SUladzislau Rezki (Sony) {
74868ad4a33SUladzislau Rezki (Sony) 	struct vmap_area *sibling;
74968ad4a33SUladzislau Rezki (Sony) 	struct list_head *next;
75068ad4a33SUladzislau Rezki (Sony) 	struct rb_node **link;
75168ad4a33SUladzislau Rezki (Sony) 	struct rb_node *parent;
75268ad4a33SUladzislau Rezki (Sony) 	bool merged = false;
75368ad4a33SUladzislau Rezki (Sony) 
75468ad4a33SUladzislau Rezki (Sony) 	/*
75568ad4a33SUladzislau Rezki (Sony) 	 * Find a place in the tree where VA potentially will be
75668ad4a33SUladzislau Rezki (Sony) 	 * inserted, unless it is merged with its sibling/siblings.
75768ad4a33SUladzislau Rezki (Sony) 	 */
75868ad4a33SUladzislau Rezki (Sony) 	link = find_va_links(va, root, NULL, &parent);
7599c801f61SUladzislau Rezki (Sony) 	if (!link)
7609c801f61SUladzislau Rezki (Sony) 		return NULL;
76168ad4a33SUladzislau Rezki (Sony) 
76268ad4a33SUladzislau Rezki (Sony) 	/*
76368ad4a33SUladzislau Rezki (Sony) 	 * Get next node of VA to check if merging can be done.
76468ad4a33SUladzislau Rezki (Sony) 	 */
76568ad4a33SUladzislau Rezki (Sony) 	next = get_va_next_sibling(parent, link);
76668ad4a33SUladzislau Rezki (Sony) 	if (unlikely(next == NULL))
76768ad4a33SUladzislau Rezki (Sony) 		goto insert;
76868ad4a33SUladzislau Rezki (Sony) 
76968ad4a33SUladzislau Rezki (Sony) 	/*
77068ad4a33SUladzislau Rezki (Sony) 	 * start            end
77168ad4a33SUladzislau Rezki (Sony) 	 * |                |
77268ad4a33SUladzislau Rezki (Sony) 	 * |<------VA------>|<-----Next----->|
77368ad4a33SUladzislau Rezki (Sony) 	 *                  |                |
77468ad4a33SUladzislau Rezki (Sony) 	 *                  start            end
77568ad4a33SUladzislau Rezki (Sony) 	 */
77668ad4a33SUladzislau Rezki (Sony) 	if (next != head) {
77768ad4a33SUladzislau Rezki (Sony) 		sibling = list_entry(next, struct vmap_area, list);
77868ad4a33SUladzislau Rezki (Sony) 		if (sibling->va_start == va->va_end) {
77968ad4a33SUladzislau Rezki (Sony) 			sibling->va_start = va->va_start;
78068ad4a33SUladzislau Rezki (Sony) 
78168ad4a33SUladzislau Rezki (Sony) 			/* Free vmap_area object. */
78268ad4a33SUladzislau Rezki (Sony) 			kmem_cache_free(vmap_area_cachep, va);
78368ad4a33SUladzislau Rezki (Sony) 
78468ad4a33SUladzislau Rezki (Sony) 			/* Point to the new merged area. */
78568ad4a33SUladzislau Rezki (Sony) 			va = sibling;
78668ad4a33SUladzislau Rezki (Sony) 			merged = true;
78768ad4a33SUladzislau Rezki (Sony) 		}
78868ad4a33SUladzislau Rezki (Sony) 	}
78968ad4a33SUladzislau Rezki (Sony) 
79068ad4a33SUladzislau Rezki (Sony) 	/*
79168ad4a33SUladzislau Rezki (Sony) 	 * start            end
79268ad4a33SUladzislau Rezki (Sony) 	 * |                |
79368ad4a33SUladzislau Rezki (Sony) 	 * |<-----Prev----->|<------VA------>|
79468ad4a33SUladzislau Rezki (Sony) 	 *                  |                |
79568ad4a33SUladzislau Rezki (Sony) 	 *                  start            end
79668ad4a33SUladzislau Rezki (Sony) 	 */
79768ad4a33SUladzislau Rezki (Sony) 	if (next->prev != head) {
79868ad4a33SUladzislau Rezki (Sony) 		sibling = list_entry(next->prev, struct vmap_area, list);
79968ad4a33SUladzislau Rezki (Sony) 		if (sibling->va_end == va->va_start) {
8005dd78640SUladzislau Rezki (Sony) 			/*
8015dd78640SUladzislau Rezki (Sony) 			 * If both neighbors are coalesced, it is important
8025dd78640SUladzislau Rezki (Sony) 			 * to unlink the "next" node first, followed by merging
8035dd78640SUladzislau Rezki (Sony) 			 * with "previous" one. Otherwise the tree might not be
8045dd78640SUladzislau Rezki (Sony) 			 * fully populated if a sibling's augmented value is
8055dd78640SUladzislau Rezki (Sony) 			 * "normalized" because of rotation operations.
8065dd78640SUladzislau Rezki (Sony) 			 */
80754f63d9dSUladzislau Rezki (Sony) 			if (merged)
80868ad4a33SUladzislau Rezki (Sony) 				unlink_va(va, root);
80968ad4a33SUladzislau Rezki (Sony) 
8105dd78640SUladzislau Rezki (Sony) 			sibling->va_end = va->va_end;
8115dd78640SUladzislau Rezki (Sony) 
81268ad4a33SUladzislau Rezki (Sony) 			/* Free vmap_area object. */
81368ad4a33SUladzislau Rezki (Sony) 			kmem_cache_free(vmap_area_cachep, va);
8143c5c3cfbSDaniel Axtens 
8153c5c3cfbSDaniel Axtens 			/* Point to the new merged area. */
8163c5c3cfbSDaniel Axtens 			va = sibling;
8173c5c3cfbSDaniel Axtens 			merged = true;
81868ad4a33SUladzislau Rezki (Sony) 		}
81968ad4a33SUladzislau Rezki (Sony) 	}
82068ad4a33SUladzislau Rezki (Sony) 
82168ad4a33SUladzislau Rezki (Sony) insert:
8225dd78640SUladzislau Rezki (Sony) 	if (!merged)
82368ad4a33SUladzislau Rezki (Sony) 		link_va(va, root, parent, link, head);
8243c5c3cfbSDaniel Axtens 
8255dd78640SUladzislau Rezki (Sony) 	/*
8265dd78640SUladzislau Rezki (Sony) 	 * Last step is to check and update the tree.
8275dd78640SUladzislau Rezki (Sony) 	 */
8285dd78640SUladzislau Rezki (Sony) 	augment_tree_propagate_from(va);
8293c5c3cfbSDaniel Axtens 	return va;
83068ad4a33SUladzislau Rezki (Sony) }
83168ad4a33SUladzislau Rezki (Sony) 
83268ad4a33SUladzislau Rezki (Sony) static __always_inline bool
83368ad4a33SUladzislau Rezki (Sony) is_within_this_va(struct vmap_area *va, unsigned long size,
83468ad4a33SUladzislau Rezki (Sony) 	unsigned long align, unsigned long vstart)
83568ad4a33SUladzislau Rezki (Sony) {
83668ad4a33SUladzislau Rezki (Sony) 	unsigned long nva_start_addr;
83768ad4a33SUladzislau Rezki (Sony) 
83868ad4a33SUladzislau Rezki (Sony) 	if (va->va_start > vstart)
83968ad4a33SUladzislau Rezki (Sony) 		nva_start_addr = ALIGN(va->va_start, align);
84068ad4a33SUladzislau Rezki (Sony) 	else
84168ad4a33SUladzislau Rezki (Sony) 		nva_start_addr = ALIGN(vstart, align);
84268ad4a33SUladzislau Rezki (Sony) 
84368ad4a33SUladzislau Rezki (Sony) 	/* Can be overflowed due to big size or alignment. */
84468ad4a33SUladzislau Rezki (Sony) 	if (nva_start_addr + size < nva_start_addr ||
84568ad4a33SUladzislau Rezki (Sony) 			nva_start_addr < vstart)
84668ad4a33SUladzislau Rezki (Sony) 		return false;
84768ad4a33SUladzislau Rezki (Sony) 
84868ad4a33SUladzislau Rezki (Sony) 	return (nva_start_addr + size <= va->va_end);
84968ad4a33SUladzislau Rezki (Sony) }
85068ad4a33SUladzislau Rezki (Sony) 
85168ad4a33SUladzislau Rezki (Sony) /*
85268ad4a33SUladzislau Rezki (Sony)  * Find the first free block(lowest start address) in the tree,
85368ad4a33SUladzislau Rezki (Sony)  * that will accomplish the request corresponding to passing
85468ad4a33SUladzislau Rezki (Sony)  * parameters.
85568ad4a33SUladzislau Rezki (Sony)  */
85668ad4a33SUladzislau Rezki (Sony) static __always_inline struct vmap_area *
85768ad4a33SUladzislau Rezki (Sony) find_vmap_lowest_match(unsigned long size,
85868ad4a33SUladzislau Rezki (Sony) 	unsigned long align, unsigned long vstart)
85968ad4a33SUladzislau Rezki (Sony) {
86068ad4a33SUladzislau Rezki (Sony) 	struct vmap_area *va;
86168ad4a33SUladzislau Rezki (Sony) 	struct rb_node *node;
86268ad4a33SUladzislau Rezki (Sony) 	unsigned long length;
86368ad4a33SUladzislau Rezki (Sony) 
86468ad4a33SUladzislau Rezki (Sony) 	/* Start from the root. */
86568ad4a33SUladzislau Rezki (Sony) 	node = free_vmap_area_root.rb_node;
86668ad4a33SUladzislau Rezki (Sony) 
86768ad4a33SUladzislau Rezki (Sony) 	/* Adjust the search size for alignment overhead. */
86868ad4a33SUladzislau Rezki (Sony) 	length = size + align - 1;
86968ad4a33SUladzislau Rezki (Sony) 
87068ad4a33SUladzislau Rezki (Sony) 	while (node) {
87168ad4a33SUladzislau Rezki (Sony) 		va = rb_entry(node, struct vmap_area, rb_node);
87268ad4a33SUladzislau Rezki (Sony) 
87368ad4a33SUladzislau Rezki (Sony) 		if (get_subtree_max_size(node->rb_left) >= length &&
87468ad4a33SUladzislau Rezki (Sony) 				vstart < va->va_start) {
87568ad4a33SUladzislau Rezki (Sony) 			node = node->rb_left;
87668ad4a33SUladzislau Rezki (Sony) 		} else {
87768ad4a33SUladzislau Rezki (Sony) 			if (is_within_this_va(va, size, align, vstart))
87868ad4a33SUladzislau Rezki (Sony) 				return va;
87968ad4a33SUladzislau Rezki (Sony) 
88068ad4a33SUladzislau Rezki (Sony) 			/*
88168ad4a33SUladzislau Rezki (Sony) 			 * Does not make sense to go deeper towards the right
88268ad4a33SUladzislau Rezki (Sony) 			 * sub-tree if it does not have a free block that is
88368ad4a33SUladzislau Rezki (Sony) 			 * equal or bigger to the requested search length.
88468ad4a33SUladzislau Rezki (Sony) 			 */
88568ad4a33SUladzislau Rezki (Sony) 			if (get_subtree_max_size(node->rb_right) >= length) {
88668ad4a33SUladzislau Rezki (Sony) 				node = node->rb_right;
88768ad4a33SUladzislau Rezki (Sony) 				continue;
88868ad4a33SUladzislau Rezki (Sony) 			}
88968ad4a33SUladzislau Rezki (Sony) 
89068ad4a33SUladzislau Rezki (Sony) 			/*
8913806b041SAndrew Morton 			 * OK. We roll back and find the first right sub-tree,
89268ad4a33SUladzislau Rezki (Sony) 			 * that will satisfy the search criteria. It can happen
89368ad4a33SUladzislau Rezki (Sony) 			 * only once due to "vstart" restriction.
89468ad4a33SUladzislau Rezki (Sony) 			 */
89568ad4a33SUladzislau Rezki (Sony) 			while ((node = rb_parent(node))) {
89668ad4a33SUladzislau Rezki (Sony) 				va = rb_entry(node, struct vmap_area, rb_node);
89768ad4a33SUladzislau Rezki (Sony) 				if (is_within_this_va(va, size, align, vstart))
89868ad4a33SUladzislau Rezki (Sony) 					return va;
89968ad4a33SUladzislau Rezki (Sony) 
90068ad4a33SUladzislau Rezki (Sony) 				if (get_subtree_max_size(node->rb_right) >= length &&
90168ad4a33SUladzislau Rezki (Sony) 						vstart <= va->va_start) {
90268ad4a33SUladzislau Rezki (Sony) 					node = node->rb_right;
90368ad4a33SUladzislau Rezki (Sony) 					break;
90468ad4a33SUladzislau Rezki (Sony) 				}
90568ad4a33SUladzislau Rezki (Sony) 			}
90668ad4a33SUladzislau Rezki (Sony) 		}
90768ad4a33SUladzislau Rezki (Sony) 	}
90868ad4a33SUladzislau Rezki (Sony) 
90968ad4a33SUladzislau Rezki (Sony) 	return NULL;
91068ad4a33SUladzislau Rezki (Sony) }
91168ad4a33SUladzislau Rezki (Sony) 
912a6cf4e0fSUladzislau Rezki (Sony) #if DEBUG_AUGMENT_LOWEST_MATCH_CHECK
913a6cf4e0fSUladzislau Rezki (Sony) #include <linux/random.h>
914a6cf4e0fSUladzislau Rezki (Sony) 
915a6cf4e0fSUladzislau Rezki (Sony) static struct vmap_area *
916a6cf4e0fSUladzislau Rezki (Sony) find_vmap_lowest_linear_match(unsigned long size,
917a6cf4e0fSUladzislau Rezki (Sony) 	unsigned long align, unsigned long vstart)
918a6cf4e0fSUladzislau Rezki (Sony) {
919a6cf4e0fSUladzislau Rezki (Sony) 	struct vmap_area *va;
920a6cf4e0fSUladzislau Rezki (Sony) 
921a6cf4e0fSUladzislau Rezki (Sony) 	list_for_each_entry(va, &free_vmap_area_list, list) {
922a6cf4e0fSUladzislau Rezki (Sony) 		if (!is_within_this_va(va, size, align, vstart))
923a6cf4e0fSUladzislau Rezki (Sony) 			continue;
924a6cf4e0fSUladzislau Rezki (Sony) 
925a6cf4e0fSUladzislau Rezki (Sony) 		return va;
926a6cf4e0fSUladzislau Rezki (Sony) 	}
927a6cf4e0fSUladzislau Rezki (Sony) 
928a6cf4e0fSUladzislau Rezki (Sony) 	return NULL;
929a6cf4e0fSUladzislau Rezki (Sony) }
930a6cf4e0fSUladzislau Rezki (Sony) 
931a6cf4e0fSUladzislau Rezki (Sony) static void
932a6cf4e0fSUladzislau Rezki (Sony) find_vmap_lowest_match_check(unsigned long size)
933a6cf4e0fSUladzislau Rezki (Sony) {
934a6cf4e0fSUladzislau Rezki (Sony) 	struct vmap_area *va_1, *va_2;
935a6cf4e0fSUladzislau Rezki (Sony) 	unsigned long vstart;
936a6cf4e0fSUladzislau Rezki (Sony) 	unsigned int rnd;
937a6cf4e0fSUladzislau Rezki (Sony) 
938a6cf4e0fSUladzislau Rezki (Sony) 	get_random_bytes(&rnd, sizeof(rnd));
939a6cf4e0fSUladzislau Rezki (Sony) 	vstart = VMALLOC_START + rnd;
940a6cf4e0fSUladzislau Rezki (Sony) 
941a6cf4e0fSUladzislau Rezki (Sony) 	va_1 = find_vmap_lowest_match(size, 1, vstart);
942a6cf4e0fSUladzislau Rezki (Sony) 	va_2 = find_vmap_lowest_linear_match(size, 1, vstart);
943a6cf4e0fSUladzislau Rezki (Sony) 
944a6cf4e0fSUladzislau Rezki (Sony) 	if (va_1 != va_2)
945a6cf4e0fSUladzislau Rezki (Sony) 		pr_emerg("not lowest: t: 0x%p, l: 0x%p, v: 0x%lx\n",
946a6cf4e0fSUladzislau Rezki (Sony) 			va_1, va_2, vstart);
947a6cf4e0fSUladzislau Rezki (Sony) }
948a6cf4e0fSUladzislau Rezki (Sony) #endif
949a6cf4e0fSUladzislau Rezki (Sony) 
95068ad4a33SUladzislau Rezki (Sony) enum fit_type {
95168ad4a33SUladzislau Rezki (Sony) 	NOTHING_FIT = 0,
95268ad4a33SUladzislau Rezki (Sony) 	FL_FIT_TYPE = 1,	/* full fit */
95368ad4a33SUladzislau Rezki (Sony) 	LE_FIT_TYPE = 2,	/* left edge fit */
95468ad4a33SUladzislau Rezki (Sony) 	RE_FIT_TYPE = 3,	/* right edge fit */
95568ad4a33SUladzislau Rezki (Sony) 	NE_FIT_TYPE = 4		/* no edge fit */
95668ad4a33SUladzislau Rezki (Sony) };
95768ad4a33SUladzislau Rezki (Sony) 
95868ad4a33SUladzislau Rezki (Sony) static __always_inline enum fit_type
95968ad4a33SUladzislau Rezki (Sony) classify_va_fit_type(struct vmap_area *va,
96068ad4a33SUladzislau Rezki (Sony) 	unsigned long nva_start_addr, unsigned long size)
96168ad4a33SUladzislau Rezki (Sony) {
96268ad4a33SUladzislau Rezki (Sony) 	enum fit_type type;
96368ad4a33SUladzislau Rezki (Sony) 
96468ad4a33SUladzislau Rezki (Sony) 	/* Check if it is within VA. */
96568ad4a33SUladzislau Rezki (Sony) 	if (nva_start_addr < va->va_start ||
96668ad4a33SUladzislau Rezki (Sony) 			nva_start_addr + size > va->va_end)
96768ad4a33SUladzislau Rezki (Sony) 		return NOTHING_FIT;
96868ad4a33SUladzislau Rezki (Sony) 
96968ad4a33SUladzislau Rezki (Sony) 	/* Now classify. */
97068ad4a33SUladzislau Rezki (Sony) 	if (va->va_start == nva_start_addr) {
97168ad4a33SUladzislau Rezki (Sony) 		if (va->va_end == nva_start_addr + size)
97268ad4a33SUladzislau Rezki (Sony) 			type = FL_FIT_TYPE;
97368ad4a33SUladzislau Rezki (Sony) 		else
97468ad4a33SUladzislau Rezki (Sony) 			type = LE_FIT_TYPE;
97568ad4a33SUladzislau Rezki (Sony) 	} else if (va->va_end == nva_start_addr + size) {
97668ad4a33SUladzislau Rezki (Sony) 		type = RE_FIT_TYPE;
97768ad4a33SUladzislau Rezki (Sony) 	} else {
97868ad4a33SUladzislau Rezki (Sony) 		type = NE_FIT_TYPE;
97968ad4a33SUladzislau Rezki (Sony) 	}
98068ad4a33SUladzislau Rezki (Sony) 
98168ad4a33SUladzislau Rezki (Sony) 	return type;
98268ad4a33SUladzislau Rezki (Sony) }
98368ad4a33SUladzislau Rezki (Sony) 
98468ad4a33SUladzislau Rezki (Sony) static __always_inline int
98568ad4a33SUladzislau Rezki (Sony) adjust_va_to_fit_type(struct vmap_area *va,
98668ad4a33SUladzislau Rezki (Sony) 	unsigned long nva_start_addr, unsigned long size,
98768ad4a33SUladzislau Rezki (Sony) 	enum fit_type type)
98868ad4a33SUladzislau Rezki (Sony) {
9892c929233SArnd Bergmann 	struct vmap_area *lva = NULL;
99068ad4a33SUladzislau Rezki (Sony) 
99168ad4a33SUladzislau Rezki (Sony) 	if (type == FL_FIT_TYPE) {
99268ad4a33SUladzislau Rezki (Sony) 		/*
99368ad4a33SUladzislau Rezki (Sony) 		 * No need to split VA, it fully fits.
99468ad4a33SUladzislau Rezki (Sony) 		 *
99568ad4a33SUladzislau Rezki (Sony) 		 * |               |
99668ad4a33SUladzislau Rezki (Sony) 		 * V      NVA      V
99768ad4a33SUladzislau Rezki (Sony) 		 * |---------------|
99868ad4a33SUladzislau Rezki (Sony) 		 */
99968ad4a33SUladzislau Rezki (Sony) 		unlink_va(va, &free_vmap_area_root);
100068ad4a33SUladzislau Rezki (Sony) 		kmem_cache_free(vmap_area_cachep, va);
100168ad4a33SUladzislau Rezki (Sony) 	} else if (type == LE_FIT_TYPE) {
100268ad4a33SUladzislau Rezki (Sony) 		/*
100368ad4a33SUladzislau Rezki (Sony) 		 * Split left edge of fit VA.
100468ad4a33SUladzislau Rezki (Sony) 		 *
100568ad4a33SUladzislau Rezki (Sony) 		 * |       |
100668ad4a33SUladzislau Rezki (Sony) 		 * V  NVA  V   R
100768ad4a33SUladzislau Rezki (Sony) 		 * |-------|-------|
100868ad4a33SUladzislau Rezki (Sony) 		 */
100968ad4a33SUladzislau Rezki (Sony) 		va->va_start += size;
101068ad4a33SUladzislau Rezki (Sony) 	} else if (type == RE_FIT_TYPE) {
101168ad4a33SUladzislau Rezki (Sony) 		/*
101268ad4a33SUladzislau Rezki (Sony) 		 * Split right edge of fit VA.
101368ad4a33SUladzislau Rezki (Sony) 		 *
101468ad4a33SUladzislau Rezki (Sony) 		 *         |       |
101568ad4a33SUladzislau Rezki (Sony) 		 *     L   V  NVA  V
101668ad4a33SUladzislau Rezki (Sony) 		 * |-------|-------|
101768ad4a33SUladzislau Rezki (Sony) 		 */
101868ad4a33SUladzislau Rezki (Sony) 		va->va_end = nva_start_addr;
101968ad4a33SUladzislau Rezki (Sony) 	} else if (type == NE_FIT_TYPE) {
102068ad4a33SUladzislau Rezki (Sony) 		/*
102168ad4a33SUladzislau Rezki (Sony) 		 * Split no edge of fit VA.
102268ad4a33SUladzislau Rezki (Sony) 		 *
102368ad4a33SUladzislau Rezki (Sony) 		 *     |       |
102468ad4a33SUladzislau Rezki (Sony) 		 *   L V  NVA  V R
102568ad4a33SUladzislau Rezki (Sony) 		 * |---|-------|---|
102668ad4a33SUladzislau Rezki (Sony) 		 */
102782dd23e8SUladzislau Rezki (Sony) 		lva = __this_cpu_xchg(ne_fit_preload_node, NULL);
102882dd23e8SUladzislau Rezki (Sony) 		if (unlikely(!lva)) {
102982dd23e8SUladzislau Rezki (Sony) 			/*
103082dd23e8SUladzislau Rezki (Sony) 			 * For percpu allocator we do not do any pre-allocation
103182dd23e8SUladzislau Rezki (Sony) 			 * and leave it as it is. The reason is it most likely
103282dd23e8SUladzislau Rezki (Sony) 			 * never ends up with NE_FIT_TYPE splitting. In case of
103382dd23e8SUladzislau Rezki (Sony) 			 * percpu allocations offsets and sizes are aligned to
103482dd23e8SUladzislau Rezki (Sony) 			 * fixed align request, i.e. RE_FIT_TYPE and FL_FIT_TYPE
103582dd23e8SUladzislau Rezki (Sony) 			 * are its main fitting cases.
103682dd23e8SUladzislau Rezki (Sony) 			 *
103782dd23e8SUladzislau Rezki (Sony) 			 * There are a few exceptions though, as an example it is
103882dd23e8SUladzislau Rezki (Sony) 			 * a first allocation (early boot up) when we have "one"
103982dd23e8SUladzislau Rezki (Sony) 			 * big free space that has to be split.
1040060650a2SUladzislau Rezki (Sony) 			 *
1041060650a2SUladzislau Rezki (Sony) 			 * Also we can hit this path in case of regular "vmap"
1042060650a2SUladzislau Rezki (Sony) 			 * allocations, if "this" current CPU was not preloaded.
1043060650a2SUladzislau Rezki (Sony) 			 * See the comment in alloc_vmap_area() why. If so, then
1044060650a2SUladzislau Rezki (Sony) 			 * GFP_NOWAIT is used instead to get an extra object for
1045060650a2SUladzislau Rezki (Sony) 			 * split purpose. That is rare and most time does not
1046060650a2SUladzislau Rezki (Sony) 			 * occur.
1047060650a2SUladzislau Rezki (Sony) 			 *
1048060650a2SUladzislau Rezki (Sony) 			 * What happens if an allocation gets failed. Basically,
1049060650a2SUladzislau Rezki (Sony) 			 * an "overflow" path is triggered to purge lazily freed
1050060650a2SUladzislau Rezki (Sony) 			 * areas to free some memory, then, the "retry" path is
1051060650a2SUladzislau Rezki (Sony) 			 * triggered to repeat one more time. See more details
1052060650a2SUladzislau Rezki (Sony) 			 * in alloc_vmap_area() function.
105382dd23e8SUladzislau Rezki (Sony) 			 */
105468ad4a33SUladzislau Rezki (Sony) 			lva = kmem_cache_alloc(vmap_area_cachep, GFP_NOWAIT);
105582dd23e8SUladzislau Rezki (Sony) 			if (!lva)
105668ad4a33SUladzislau Rezki (Sony) 				return -1;
105782dd23e8SUladzislau Rezki (Sony) 		}
105868ad4a33SUladzislau Rezki (Sony) 
105968ad4a33SUladzislau Rezki (Sony) 		/*
106068ad4a33SUladzislau Rezki (Sony) 		 * Build the remainder.
106168ad4a33SUladzislau Rezki (Sony) 		 */
106268ad4a33SUladzislau Rezki (Sony) 		lva->va_start = va->va_start;
106368ad4a33SUladzislau Rezki (Sony) 		lva->va_end = nva_start_addr;
106468ad4a33SUladzislau Rezki (Sony) 
106568ad4a33SUladzislau Rezki (Sony) 		/*
106668ad4a33SUladzislau Rezki (Sony) 		 * Shrink this VA to remaining size.
106768ad4a33SUladzislau Rezki (Sony) 		 */
106868ad4a33SUladzislau Rezki (Sony) 		va->va_start = nva_start_addr + size;
106968ad4a33SUladzislau Rezki (Sony) 	} else {
107068ad4a33SUladzislau Rezki (Sony) 		return -1;
107168ad4a33SUladzislau Rezki (Sony) 	}
107268ad4a33SUladzislau Rezki (Sony) 
107368ad4a33SUladzislau Rezki (Sony) 	if (type != FL_FIT_TYPE) {
107468ad4a33SUladzislau Rezki (Sony) 		augment_tree_propagate_from(va);
107568ad4a33SUladzislau Rezki (Sony) 
10762c929233SArnd Bergmann 		if (lva)	/* type == NE_FIT_TYPE */
107768ad4a33SUladzislau Rezki (Sony) 			insert_vmap_area_augment(lva, &va->rb_node,
107868ad4a33SUladzislau Rezki (Sony) 				&free_vmap_area_root, &free_vmap_area_list);
107968ad4a33SUladzislau Rezki (Sony) 	}
108068ad4a33SUladzislau Rezki (Sony) 
108168ad4a33SUladzislau Rezki (Sony) 	return 0;
108268ad4a33SUladzislau Rezki (Sony) }
108368ad4a33SUladzislau Rezki (Sony) 
108468ad4a33SUladzislau Rezki (Sony) /*
108568ad4a33SUladzislau Rezki (Sony)  * Returns a start address of the newly allocated area, if success.
108668ad4a33SUladzislau Rezki (Sony)  * Otherwise a vend is returned that indicates failure.
108768ad4a33SUladzislau Rezki (Sony)  */
108868ad4a33SUladzislau Rezki (Sony) static __always_inline unsigned long
108968ad4a33SUladzislau Rezki (Sony) __alloc_vmap_area(unsigned long size, unsigned long align,
1090cacca6baSUladzislau Rezki (Sony) 	unsigned long vstart, unsigned long vend)
109168ad4a33SUladzislau Rezki (Sony) {
109268ad4a33SUladzislau Rezki (Sony) 	unsigned long nva_start_addr;
109368ad4a33SUladzislau Rezki (Sony) 	struct vmap_area *va;
109468ad4a33SUladzislau Rezki (Sony) 	enum fit_type type;
109568ad4a33SUladzislau Rezki (Sony) 	int ret;
109668ad4a33SUladzislau Rezki (Sony) 
109768ad4a33SUladzislau Rezki (Sony) 	va = find_vmap_lowest_match(size, align, vstart);
109868ad4a33SUladzislau Rezki (Sony) 	if (unlikely(!va))
109968ad4a33SUladzislau Rezki (Sony) 		return vend;
110068ad4a33SUladzislau Rezki (Sony) 
110168ad4a33SUladzislau Rezki (Sony) 	if (va->va_start > vstart)
110268ad4a33SUladzislau Rezki (Sony) 		nva_start_addr = ALIGN(va->va_start, align);
110368ad4a33SUladzislau Rezki (Sony) 	else
110468ad4a33SUladzislau Rezki (Sony) 		nva_start_addr = ALIGN(vstart, align);
110568ad4a33SUladzislau Rezki (Sony) 
110668ad4a33SUladzislau Rezki (Sony) 	/* Check the "vend" restriction. */
110768ad4a33SUladzislau Rezki (Sony) 	if (nva_start_addr + size > vend)
110868ad4a33SUladzislau Rezki (Sony) 		return vend;
110968ad4a33SUladzislau Rezki (Sony) 
111068ad4a33SUladzislau Rezki (Sony) 	/* Classify what we have found. */
111168ad4a33SUladzislau Rezki (Sony) 	type = classify_va_fit_type(va, nva_start_addr, size);
111268ad4a33SUladzislau Rezki (Sony) 	if (WARN_ON_ONCE(type == NOTHING_FIT))
111368ad4a33SUladzislau Rezki (Sony) 		return vend;
111468ad4a33SUladzislau Rezki (Sony) 
111568ad4a33SUladzislau Rezki (Sony) 	/* Update the free vmap_area. */
111668ad4a33SUladzislau Rezki (Sony) 	ret = adjust_va_to_fit_type(va, nva_start_addr, size, type);
111768ad4a33SUladzislau Rezki (Sony) 	if (ret)
111868ad4a33SUladzislau Rezki (Sony) 		return vend;
111968ad4a33SUladzislau Rezki (Sony) 
1120a6cf4e0fSUladzislau Rezki (Sony) #if DEBUG_AUGMENT_LOWEST_MATCH_CHECK
1121a6cf4e0fSUladzislau Rezki (Sony) 	find_vmap_lowest_match_check(size);
1122a6cf4e0fSUladzislau Rezki (Sony) #endif
1123a6cf4e0fSUladzislau Rezki (Sony) 
112468ad4a33SUladzislau Rezki (Sony) 	return nva_start_addr;
112568ad4a33SUladzislau Rezki (Sony) }
11264da56b99SChris Wilson 
1127db64fe02SNick Piggin /*
1128d98c9e83SAndrey Ryabinin  * Free a region of KVA allocated by alloc_vmap_area
1129d98c9e83SAndrey Ryabinin  */
1130d98c9e83SAndrey Ryabinin static void free_vmap_area(struct vmap_area *va)
1131d98c9e83SAndrey Ryabinin {
1132d98c9e83SAndrey Ryabinin 	/*
1133d98c9e83SAndrey Ryabinin 	 * Remove from the busy tree/list.
1134d98c9e83SAndrey Ryabinin 	 */
1135d98c9e83SAndrey Ryabinin 	spin_lock(&vmap_area_lock);
1136d98c9e83SAndrey Ryabinin 	unlink_va(va, &vmap_area_root);
1137d98c9e83SAndrey Ryabinin 	spin_unlock(&vmap_area_lock);
1138d98c9e83SAndrey Ryabinin 
1139d98c9e83SAndrey Ryabinin 	/*
1140d98c9e83SAndrey Ryabinin 	 * Insert/Merge it back to the free tree/list.
1141d98c9e83SAndrey Ryabinin 	 */
1142d98c9e83SAndrey Ryabinin 	spin_lock(&free_vmap_area_lock);
1143d98c9e83SAndrey Ryabinin 	merge_or_add_vmap_area(va, &free_vmap_area_root, &free_vmap_area_list);
1144d98c9e83SAndrey Ryabinin 	spin_unlock(&free_vmap_area_lock);
1145d98c9e83SAndrey Ryabinin }
1146d98c9e83SAndrey Ryabinin 
1147d98c9e83SAndrey Ryabinin /*
1148db64fe02SNick Piggin  * Allocate a region of KVA of the specified size and alignment, within the
1149db64fe02SNick Piggin  * vstart and vend.
1150db64fe02SNick Piggin  */
1151db64fe02SNick Piggin static struct vmap_area *alloc_vmap_area(unsigned long size,
1152db64fe02SNick Piggin 				unsigned long align,
1153db64fe02SNick Piggin 				unsigned long vstart, unsigned long vend,
1154db64fe02SNick Piggin 				int node, gfp_t gfp_mask)
1155db64fe02SNick Piggin {
115682dd23e8SUladzislau Rezki (Sony) 	struct vmap_area *va, *pva;
11571da177e4SLinus Torvalds 	unsigned long addr;
1158db64fe02SNick Piggin 	int purged = 0;
1159d98c9e83SAndrey Ryabinin 	int ret;
1160db64fe02SNick Piggin 
11617766970cSNick Piggin 	BUG_ON(!size);
1162891c49abSAlexander Kuleshov 	BUG_ON(offset_in_page(size));
116389699605SNick Piggin 	BUG_ON(!is_power_of_2(align));
1164db64fe02SNick Piggin 
116568ad4a33SUladzislau Rezki (Sony) 	if (unlikely(!vmap_initialized))
116668ad4a33SUladzislau Rezki (Sony) 		return ERR_PTR(-EBUSY);
116768ad4a33SUladzislau Rezki (Sony) 
11685803ed29SChristoph Hellwig 	might_sleep();
1169f07116d7SUladzislau Rezki (Sony) 	gfp_mask = gfp_mask & GFP_RECLAIM_MASK;
11704da56b99SChris Wilson 
1171f07116d7SUladzislau Rezki (Sony) 	va = kmem_cache_alloc_node(vmap_area_cachep, gfp_mask, node);
1172db64fe02SNick Piggin 	if (unlikely(!va))
1173db64fe02SNick Piggin 		return ERR_PTR(-ENOMEM);
1174db64fe02SNick Piggin 
11757f88f88fSCatalin Marinas 	/*
11767f88f88fSCatalin Marinas 	 * Only scan the relevant parts containing pointers to other objects
11777f88f88fSCatalin Marinas 	 * to avoid false negatives.
11787f88f88fSCatalin Marinas 	 */
1179f07116d7SUladzislau Rezki (Sony) 	kmemleak_scan_area(&va->rb_node, SIZE_MAX, gfp_mask);
11807f88f88fSCatalin Marinas 
1181db64fe02SNick Piggin retry:
118282dd23e8SUladzislau Rezki (Sony) 	/*
118381f1ba58SUladzislau Rezki (Sony) 	 * Preload this CPU with one extra vmap_area object. It is used
118481f1ba58SUladzislau Rezki (Sony) 	 * when fit type of free area is NE_FIT_TYPE. Please note, it
118581f1ba58SUladzislau Rezki (Sony) 	 * does not guarantee that an allocation occurs on a CPU that
118681f1ba58SUladzislau Rezki (Sony) 	 * is preloaded, instead we minimize the case when it is not.
118781f1ba58SUladzislau Rezki (Sony) 	 * It can happen because of cpu migration, because there is a
118881f1ba58SUladzislau Rezki (Sony) 	 * race until the below spinlock is taken.
118982dd23e8SUladzislau Rezki (Sony) 	 *
119082dd23e8SUladzislau Rezki (Sony) 	 * The preload is done in non-atomic context, thus it allows us
119182dd23e8SUladzislau Rezki (Sony) 	 * to use more permissive allocation masks to be more stable under
119281f1ba58SUladzislau Rezki (Sony) 	 * low memory condition and high memory pressure. In rare case,
119381f1ba58SUladzislau Rezki (Sony) 	 * if not preloaded, GFP_NOWAIT is used.
119482dd23e8SUladzislau Rezki (Sony) 	 *
119581f1ba58SUladzislau Rezki (Sony) 	 * Set "pva" to NULL here, because of "retry" path.
119682dd23e8SUladzislau Rezki (Sony) 	 */
119781f1ba58SUladzislau Rezki (Sony) 	pva = NULL;
119882dd23e8SUladzislau Rezki (Sony) 
119981f1ba58SUladzislau Rezki (Sony) 	if (!this_cpu_read(ne_fit_preload_node))
120081f1ba58SUladzislau Rezki (Sony) 		/*
120181f1ba58SUladzislau Rezki (Sony) 		 * Even if it fails we do not really care about that.
120281f1ba58SUladzislau Rezki (Sony) 		 * Just proceed as it is. If needed "overflow" path
120381f1ba58SUladzislau Rezki (Sony) 		 * will refill the cache we allocate from.
120481f1ba58SUladzislau Rezki (Sony) 		 */
1205f07116d7SUladzislau Rezki (Sony) 		pva = kmem_cache_alloc_node(vmap_area_cachep, gfp_mask, node);
120682dd23e8SUladzislau Rezki (Sony) 
1207e36176beSUladzislau Rezki (Sony) 	spin_lock(&free_vmap_area_lock);
120881f1ba58SUladzislau Rezki (Sony) 
120981f1ba58SUladzislau Rezki (Sony) 	if (pva && __this_cpu_cmpxchg(ne_fit_preload_node, NULL, pva))
121081f1ba58SUladzislau Rezki (Sony) 		kmem_cache_free(vmap_area_cachep, pva);
121168ad4a33SUladzislau Rezki (Sony) 
121289699605SNick Piggin 	/*
121368ad4a33SUladzislau Rezki (Sony) 	 * If an allocation fails, the "vend" address is
121468ad4a33SUladzislau Rezki (Sony) 	 * returned. Therefore trigger the overflow path.
121589699605SNick Piggin 	 */
1216cacca6baSUladzislau Rezki (Sony) 	addr = __alloc_vmap_area(size, align, vstart, vend);
1217e36176beSUladzislau Rezki (Sony) 	spin_unlock(&free_vmap_area_lock);
1218e36176beSUladzislau Rezki (Sony) 
121968ad4a33SUladzislau Rezki (Sony) 	if (unlikely(addr == vend))
122089699605SNick Piggin 		goto overflow;
122189699605SNick Piggin 
122289699605SNick Piggin 	va->va_start = addr;
122389699605SNick Piggin 	va->va_end = addr + size;
1224688fcbfcSPengfei Li 	va->vm = NULL;
122568ad4a33SUladzislau Rezki (Sony) 
1226d98c9e83SAndrey Ryabinin 
1227e36176beSUladzislau Rezki (Sony) 	spin_lock(&vmap_area_lock);
1228e36176beSUladzislau Rezki (Sony) 	insert_vmap_area(va, &vmap_area_root, &vmap_area_list);
122989699605SNick Piggin 	spin_unlock(&vmap_area_lock);
123089699605SNick Piggin 
123161e16557SWang Xiaoqiang 	BUG_ON(!IS_ALIGNED(va->va_start, align));
123289699605SNick Piggin 	BUG_ON(va->va_start < vstart);
123389699605SNick Piggin 	BUG_ON(va->va_end > vend);
123489699605SNick Piggin 
1235d98c9e83SAndrey Ryabinin 	ret = kasan_populate_vmalloc(addr, size);
1236d98c9e83SAndrey Ryabinin 	if (ret) {
1237d98c9e83SAndrey Ryabinin 		free_vmap_area(va);
1238d98c9e83SAndrey Ryabinin 		return ERR_PTR(ret);
1239d98c9e83SAndrey Ryabinin 	}
1240d98c9e83SAndrey Ryabinin 
124189699605SNick Piggin 	return va;
124289699605SNick Piggin 
12437766970cSNick Piggin overflow:
1244db64fe02SNick Piggin 	if (!purged) {
1245db64fe02SNick Piggin 		purge_vmap_area_lazy();
1246db64fe02SNick Piggin 		purged = 1;
1247db64fe02SNick Piggin 		goto retry;
1248db64fe02SNick Piggin 	}
12494da56b99SChris Wilson 
12504da56b99SChris Wilson 	if (gfpflags_allow_blocking(gfp_mask)) {
12514da56b99SChris Wilson 		unsigned long freed = 0;
12524da56b99SChris Wilson 		blocking_notifier_call_chain(&vmap_notify_list, 0, &freed);
12534da56b99SChris Wilson 		if (freed > 0) {
12544da56b99SChris Wilson 			purged = 0;
12554da56b99SChris Wilson 			goto retry;
12564da56b99SChris Wilson 		}
12574da56b99SChris Wilson 	}
12584da56b99SChris Wilson 
125903497d76SFlorian Fainelli 	if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit())
1260756a025fSJoe Perches 		pr_warn("vmap allocation for size %lu failed: use vmalloc=<size> to increase size\n",
1261756a025fSJoe Perches 			size);
126268ad4a33SUladzislau Rezki (Sony) 
126368ad4a33SUladzislau Rezki (Sony) 	kmem_cache_free(vmap_area_cachep, va);
1264db64fe02SNick Piggin 	return ERR_PTR(-EBUSY);
1265db64fe02SNick Piggin }
1266db64fe02SNick Piggin 
12674da56b99SChris Wilson int register_vmap_purge_notifier(struct notifier_block *nb)
12684da56b99SChris Wilson {
12694da56b99SChris Wilson 	return blocking_notifier_chain_register(&vmap_notify_list, nb);
12704da56b99SChris Wilson }
12714da56b99SChris Wilson EXPORT_SYMBOL_GPL(register_vmap_purge_notifier);
12724da56b99SChris Wilson 
12734da56b99SChris Wilson int unregister_vmap_purge_notifier(struct notifier_block *nb)
12744da56b99SChris Wilson {
12754da56b99SChris Wilson 	return blocking_notifier_chain_unregister(&vmap_notify_list, nb);
12764da56b99SChris Wilson }
12774da56b99SChris Wilson EXPORT_SYMBOL_GPL(unregister_vmap_purge_notifier);
12784da56b99SChris Wilson 
1279db64fe02SNick Piggin /*
1280db64fe02SNick Piggin  * lazy_max_pages is the maximum amount of virtual address space we gather up
1281db64fe02SNick Piggin  * before attempting to purge with a TLB flush.
1282db64fe02SNick Piggin  *
1283db64fe02SNick Piggin  * There is a tradeoff here: a larger number will cover more kernel page tables
1284db64fe02SNick Piggin  * and take slightly longer to purge, but it will linearly reduce the number of
1285db64fe02SNick Piggin  * global TLB flushes that must be performed. It would seem natural to scale
1286db64fe02SNick Piggin  * this number up linearly with the number of CPUs (because vmapping activity
1287db64fe02SNick Piggin  * could also scale linearly with the number of CPUs), however it is likely
1288db64fe02SNick Piggin  * that in practice, workloads might be constrained in other ways that mean
1289db64fe02SNick Piggin  * vmap activity will not scale linearly with CPUs. Also, I want to be
1290db64fe02SNick Piggin  * conservative and not introduce a big latency on huge systems, so go with
1291db64fe02SNick Piggin  * a less aggressive log scale. It will still be an improvement over the old
1292db64fe02SNick Piggin  * code, and it will be simple to change the scale factor if we find that it
1293db64fe02SNick Piggin  * becomes a problem on bigger systems.
1294db64fe02SNick Piggin  */
1295db64fe02SNick Piggin static unsigned long lazy_max_pages(void)
1296db64fe02SNick Piggin {
1297db64fe02SNick Piggin 	unsigned int log;
1298db64fe02SNick Piggin 
1299db64fe02SNick Piggin 	log = fls(num_online_cpus());
1300db64fe02SNick Piggin 
1301db64fe02SNick Piggin 	return log * (32UL * 1024 * 1024 / PAGE_SIZE);
1302db64fe02SNick Piggin }
1303db64fe02SNick Piggin 
13044d36e6f8SUladzislau Rezki (Sony) static atomic_long_t vmap_lazy_nr = ATOMIC_LONG_INIT(0);
1305db64fe02SNick Piggin 
13060574ecd1SChristoph Hellwig /*
13070574ecd1SChristoph Hellwig  * Serialize vmap purging.  There is no actual criticial section protected
13080574ecd1SChristoph Hellwig  * by this look, but we want to avoid concurrent calls for performance
13090574ecd1SChristoph Hellwig  * reasons and to make the pcpu_get_vm_areas more deterministic.
13100574ecd1SChristoph Hellwig  */
1311f9e09977SChristoph Hellwig static DEFINE_MUTEX(vmap_purge_lock);
13120574ecd1SChristoph Hellwig 
131302b709dfSNick Piggin /* for per-CPU blocks */
131402b709dfSNick Piggin static void purge_fragmented_blocks_allcpus(void);
131502b709dfSNick Piggin 
1316db64fe02SNick Piggin /*
13173ee48b6aSCliff Wickman  * called before a call to iounmap() if the caller wants vm_area_struct's
13183ee48b6aSCliff Wickman  * immediately freed.
13193ee48b6aSCliff Wickman  */
13203ee48b6aSCliff Wickman void set_iounmap_nonlazy(void)
13213ee48b6aSCliff Wickman {
13224d36e6f8SUladzislau Rezki (Sony) 	atomic_long_set(&vmap_lazy_nr, lazy_max_pages()+1);
13233ee48b6aSCliff Wickman }
13243ee48b6aSCliff Wickman 
13253ee48b6aSCliff Wickman /*
1326db64fe02SNick Piggin  * Purges all lazily-freed vmap areas.
1327db64fe02SNick Piggin  */
13280574ecd1SChristoph Hellwig static bool __purge_vmap_area_lazy(unsigned long start, unsigned long end)
1329db64fe02SNick Piggin {
13304d36e6f8SUladzislau Rezki (Sony) 	unsigned long resched_threshold;
133180c4bd7aSChris Wilson 	struct llist_node *valist;
1332db64fe02SNick Piggin 	struct vmap_area *va;
1333cbb76676SVegard Nossum 	struct vmap_area *n_va;
1334db64fe02SNick Piggin 
13350574ecd1SChristoph Hellwig 	lockdep_assert_held(&vmap_purge_lock);
133602b709dfSNick Piggin 
133780c4bd7aSChris Wilson 	valist = llist_del_all(&vmap_purge_list);
133868571be9SUladzislau Rezki (Sony) 	if (unlikely(valist == NULL))
133968571be9SUladzislau Rezki (Sony) 		return false;
134068571be9SUladzislau Rezki (Sony) 
134168571be9SUladzislau Rezki (Sony) 	/*
134268571be9SUladzislau Rezki (Sony) 	 * TODO: to calculate a flush range without looping.
134368571be9SUladzislau Rezki (Sony) 	 * The list can be up to lazy_max_pages() elements.
134468571be9SUladzislau Rezki (Sony) 	 */
134580c4bd7aSChris Wilson 	llist_for_each_entry(va, valist, purge_list) {
13460574ecd1SChristoph Hellwig 		if (va->va_start < start)
13470574ecd1SChristoph Hellwig 			start = va->va_start;
13480574ecd1SChristoph Hellwig 		if (va->va_end > end)
13490574ecd1SChristoph Hellwig 			end = va->va_end;
1350db64fe02SNick Piggin 	}
1351db64fe02SNick Piggin 
13520574ecd1SChristoph Hellwig 	flush_tlb_kernel_range(start, end);
13534d36e6f8SUladzislau Rezki (Sony) 	resched_threshold = lazy_max_pages() << 1;
1354db64fe02SNick Piggin 
1355e36176beSUladzislau Rezki (Sony) 	spin_lock(&free_vmap_area_lock);
1356763b218dSJoel Fernandes 	llist_for_each_entry_safe(va, n_va, valist, purge_list) {
13574d36e6f8SUladzislau Rezki (Sony) 		unsigned long nr = (va->va_end - va->va_start) >> PAGE_SHIFT;
13583c5c3cfbSDaniel Axtens 		unsigned long orig_start = va->va_start;
13593c5c3cfbSDaniel Axtens 		unsigned long orig_end = va->va_end;
1360763b218dSJoel Fernandes 
1361dd3b8353SUladzislau Rezki (Sony) 		/*
1362dd3b8353SUladzislau Rezki (Sony) 		 * Finally insert or merge lazily-freed area. It is
1363dd3b8353SUladzislau Rezki (Sony) 		 * detached and there is no need to "unlink" it from
1364dd3b8353SUladzislau Rezki (Sony) 		 * anything.
1365dd3b8353SUladzislau Rezki (Sony) 		 */
13663c5c3cfbSDaniel Axtens 		va = merge_or_add_vmap_area(va, &free_vmap_area_root,
13673c5c3cfbSDaniel Axtens 					    &free_vmap_area_list);
13683c5c3cfbSDaniel Axtens 
13699c801f61SUladzislau Rezki (Sony) 		if (!va)
13709c801f61SUladzislau Rezki (Sony) 			continue;
13719c801f61SUladzislau Rezki (Sony) 
13723c5c3cfbSDaniel Axtens 		if (is_vmalloc_or_module_addr((void *)orig_start))
13733c5c3cfbSDaniel Axtens 			kasan_release_vmalloc(orig_start, orig_end,
13743c5c3cfbSDaniel Axtens 					      va->va_start, va->va_end);
1375dd3b8353SUladzislau Rezki (Sony) 
13764d36e6f8SUladzislau Rezki (Sony) 		atomic_long_sub(nr, &vmap_lazy_nr);
137768571be9SUladzislau Rezki (Sony) 
13784d36e6f8SUladzislau Rezki (Sony) 		if (atomic_long_read(&vmap_lazy_nr) < resched_threshold)
1379e36176beSUladzislau Rezki (Sony) 			cond_resched_lock(&free_vmap_area_lock);
1380763b218dSJoel Fernandes 	}
1381e36176beSUladzislau Rezki (Sony) 	spin_unlock(&free_vmap_area_lock);
13820574ecd1SChristoph Hellwig 	return true;
1383db64fe02SNick Piggin }
1384db64fe02SNick Piggin 
1385db64fe02SNick Piggin /*
1386496850e5SNick Piggin  * Kick off a purge of the outstanding lazy areas. Don't bother if somebody
1387496850e5SNick Piggin  * is already purging.
1388496850e5SNick Piggin  */
1389496850e5SNick Piggin static void try_purge_vmap_area_lazy(void)
1390496850e5SNick Piggin {
1391f9e09977SChristoph Hellwig 	if (mutex_trylock(&vmap_purge_lock)) {
13920574ecd1SChristoph Hellwig 		__purge_vmap_area_lazy(ULONG_MAX, 0);
1393f9e09977SChristoph Hellwig 		mutex_unlock(&vmap_purge_lock);
13940574ecd1SChristoph Hellwig 	}
1395496850e5SNick Piggin }
1396496850e5SNick Piggin 
1397496850e5SNick Piggin /*
1398db64fe02SNick Piggin  * Kick off a purge of the outstanding lazy areas.
1399db64fe02SNick Piggin  */
1400db64fe02SNick Piggin static void purge_vmap_area_lazy(void)
1401db64fe02SNick Piggin {
1402f9e09977SChristoph Hellwig 	mutex_lock(&vmap_purge_lock);
14030574ecd1SChristoph Hellwig 	purge_fragmented_blocks_allcpus();
14040574ecd1SChristoph Hellwig 	__purge_vmap_area_lazy(ULONG_MAX, 0);
1405f9e09977SChristoph Hellwig 	mutex_unlock(&vmap_purge_lock);
1406db64fe02SNick Piggin }
1407db64fe02SNick Piggin 
1408db64fe02SNick Piggin /*
140964141da5SJeremy Fitzhardinge  * Free a vmap area, caller ensuring that the area has been unmapped
141064141da5SJeremy Fitzhardinge  * and flush_cache_vunmap had been called for the correct range
141164141da5SJeremy Fitzhardinge  * previously.
1412db64fe02SNick Piggin  */
141364141da5SJeremy Fitzhardinge static void free_vmap_area_noflush(struct vmap_area *va)
1414db64fe02SNick Piggin {
14154d36e6f8SUladzislau Rezki (Sony) 	unsigned long nr_lazy;
141680c4bd7aSChris Wilson 
1417dd3b8353SUladzislau Rezki (Sony) 	spin_lock(&vmap_area_lock);
1418dd3b8353SUladzislau Rezki (Sony) 	unlink_va(va, &vmap_area_root);
1419dd3b8353SUladzislau Rezki (Sony) 	spin_unlock(&vmap_area_lock);
1420dd3b8353SUladzislau Rezki (Sony) 
14214d36e6f8SUladzislau Rezki (Sony) 	nr_lazy = atomic_long_add_return((va->va_end - va->va_start) >>
14224d36e6f8SUladzislau Rezki (Sony) 				PAGE_SHIFT, &vmap_lazy_nr);
142380c4bd7aSChris Wilson 
142480c4bd7aSChris Wilson 	/* After this point, we may free va at any time */
142580c4bd7aSChris Wilson 	llist_add(&va->purge_list, &vmap_purge_list);
142680c4bd7aSChris Wilson 
142780c4bd7aSChris Wilson 	if (unlikely(nr_lazy > lazy_max_pages()))
1428496850e5SNick Piggin 		try_purge_vmap_area_lazy();
1429db64fe02SNick Piggin }
1430db64fe02SNick Piggin 
1431b29acbdcSNick Piggin /*
1432b29acbdcSNick Piggin  * Free and unmap a vmap area
1433b29acbdcSNick Piggin  */
1434b29acbdcSNick Piggin static void free_unmap_vmap_area(struct vmap_area *va)
1435b29acbdcSNick Piggin {
1436b29acbdcSNick Piggin 	flush_cache_vunmap(va->va_start, va->va_end);
1437855e57a1SChristoph Hellwig 	unmap_kernel_range_noflush(va->va_start, va->va_end - va->va_start);
14388e57f8acSVlastimil Babka 	if (debug_pagealloc_enabled_static())
143982a2e924SChintan Pandya 		flush_tlb_kernel_range(va->va_start, va->va_end);
144082a2e924SChintan Pandya 
1441c8eef01eSChristoph Hellwig 	free_vmap_area_noflush(va);
1442b29acbdcSNick Piggin }
1443b29acbdcSNick Piggin 
1444db64fe02SNick Piggin static struct vmap_area *find_vmap_area(unsigned long addr)
1445db64fe02SNick Piggin {
1446db64fe02SNick Piggin 	struct vmap_area *va;
1447db64fe02SNick Piggin 
1448db64fe02SNick Piggin 	spin_lock(&vmap_area_lock);
1449db64fe02SNick Piggin 	va = __find_vmap_area(addr);
1450db64fe02SNick Piggin 	spin_unlock(&vmap_area_lock);
1451db64fe02SNick Piggin 
1452db64fe02SNick Piggin 	return va;
1453db64fe02SNick Piggin }
1454db64fe02SNick Piggin 
1455db64fe02SNick Piggin /*** Per cpu kva allocator ***/
1456db64fe02SNick Piggin 
1457db64fe02SNick Piggin /*
1458db64fe02SNick Piggin  * vmap space is limited especially on 32 bit architectures. Ensure there is
1459db64fe02SNick Piggin  * room for at least 16 percpu vmap blocks per CPU.
1460db64fe02SNick Piggin  */
1461db64fe02SNick Piggin /*
1462db64fe02SNick Piggin  * If we had a constant VMALLOC_START and VMALLOC_END, we'd like to be able
1463db64fe02SNick Piggin  * to #define VMALLOC_SPACE		(VMALLOC_END-VMALLOC_START). Guess
1464db64fe02SNick Piggin  * instead (we just need a rough idea)
1465db64fe02SNick Piggin  */
1466db64fe02SNick Piggin #if BITS_PER_LONG == 32
1467db64fe02SNick Piggin #define VMALLOC_SPACE		(128UL*1024*1024)
1468db64fe02SNick Piggin #else
1469db64fe02SNick Piggin #define VMALLOC_SPACE		(128UL*1024*1024*1024)
1470db64fe02SNick Piggin #endif
1471db64fe02SNick Piggin 
1472db64fe02SNick Piggin #define VMALLOC_PAGES		(VMALLOC_SPACE / PAGE_SIZE)
1473db64fe02SNick Piggin #define VMAP_MAX_ALLOC		BITS_PER_LONG	/* 256K with 4K pages */
1474db64fe02SNick Piggin #define VMAP_BBMAP_BITS_MAX	1024	/* 4MB with 4K pages */
1475db64fe02SNick Piggin #define VMAP_BBMAP_BITS_MIN	(VMAP_MAX_ALLOC*2)
1476db64fe02SNick Piggin #define VMAP_MIN(x, y)		((x) < (y) ? (x) : (y)) /* can't use min() */
1477db64fe02SNick Piggin #define VMAP_MAX(x, y)		((x) > (y) ? (x) : (y)) /* can't use max() */
1478f982f915SClemens Ladisch #define VMAP_BBMAP_BITS		\
1479f982f915SClemens Ladisch 		VMAP_MIN(VMAP_BBMAP_BITS_MAX,	\
1480db64fe02SNick Piggin 		VMAP_MAX(VMAP_BBMAP_BITS_MIN,	\
1481f982f915SClemens Ladisch 			VMALLOC_PAGES / roundup_pow_of_two(NR_CPUS) / 16))
1482db64fe02SNick Piggin 
1483db64fe02SNick Piggin #define VMAP_BLOCK_SIZE		(VMAP_BBMAP_BITS * PAGE_SIZE)
1484db64fe02SNick Piggin 
1485db64fe02SNick Piggin struct vmap_block_queue {
1486db64fe02SNick Piggin 	spinlock_t lock;
1487db64fe02SNick Piggin 	struct list_head free;
1488db64fe02SNick Piggin };
1489db64fe02SNick Piggin 
1490db64fe02SNick Piggin struct vmap_block {
1491db64fe02SNick Piggin 	spinlock_t lock;
1492db64fe02SNick Piggin 	struct vmap_area *va;
1493db64fe02SNick Piggin 	unsigned long free, dirty;
14947d61bfe8SRoman Pen 	unsigned long dirty_min, dirty_max; /*< dirty range */
1495db64fe02SNick Piggin 	struct list_head free_list;
1496db64fe02SNick Piggin 	struct rcu_head rcu_head;
149702b709dfSNick Piggin 	struct list_head purge;
1498db64fe02SNick Piggin };
1499db64fe02SNick Piggin 
1500db64fe02SNick Piggin /* Queue of free and dirty vmap blocks, for allocation and flushing purposes */
1501db64fe02SNick Piggin static DEFINE_PER_CPU(struct vmap_block_queue, vmap_block_queue);
1502db64fe02SNick Piggin 
1503db64fe02SNick Piggin /*
15040f14599cSMatthew Wilcox (Oracle)  * XArray of vmap blocks, indexed by address, to quickly find a vmap block
1505db64fe02SNick Piggin  * in the free path. Could get rid of this if we change the API to return a
1506db64fe02SNick Piggin  * "cookie" from alloc, to be passed to free. But no big deal yet.
1507db64fe02SNick Piggin  */
15080f14599cSMatthew Wilcox (Oracle) static DEFINE_XARRAY(vmap_blocks);
1509db64fe02SNick Piggin 
1510db64fe02SNick Piggin /*
1511db64fe02SNick Piggin  * We should probably have a fallback mechanism to allocate virtual memory
1512db64fe02SNick Piggin  * out of partially filled vmap blocks. However vmap block sizing should be
1513db64fe02SNick Piggin  * fairly reasonable according to the vmalloc size, so it shouldn't be a
1514db64fe02SNick Piggin  * big problem.
1515db64fe02SNick Piggin  */
1516db64fe02SNick Piggin 
1517db64fe02SNick Piggin static unsigned long addr_to_vb_idx(unsigned long addr)
1518db64fe02SNick Piggin {
1519db64fe02SNick Piggin 	addr -= VMALLOC_START & ~(VMAP_BLOCK_SIZE-1);
1520db64fe02SNick Piggin 	addr /= VMAP_BLOCK_SIZE;
1521db64fe02SNick Piggin 	return addr;
1522db64fe02SNick Piggin }
1523db64fe02SNick Piggin 
1524cf725ce2SRoman Pen static void *vmap_block_vaddr(unsigned long va_start, unsigned long pages_off)
1525cf725ce2SRoman Pen {
1526cf725ce2SRoman Pen 	unsigned long addr;
1527cf725ce2SRoman Pen 
1528cf725ce2SRoman Pen 	addr = va_start + (pages_off << PAGE_SHIFT);
1529cf725ce2SRoman Pen 	BUG_ON(addr_to_vb_idx(addr) != addr_to_vb_idx(va_start));
1530cf725ce2SRoman Pen 	return (void *)addr;
1531cf725ce2SRoman Pen }
1532cf725ce2SRoman Pen 
1533cf725ce2SRoman Pen /**
1534cf725ce2SRoman Pen  * new_vmap_block - allocates new vmap_block and occupies 2^order pages in this
1535cf725ce2SRoman Pen  *                  block. Of course pages number can't exceed VMAP_BBMAP_BITS
1536cf725ce2SRoman Pen  * @order:    how many 2^order pages should be occupied in newly allocated block
1537cf725ce2SRoman Pen  * @gfp_mask: flags for the page level allocator
1538cf725ce2SRoman Pen  *
1539a862f68aSMike Rapoport  * Return: virtual address in a newly allocated block or ERR_PTR(-errno)
1540cf725ce2SRoman Pen  */
1541cf725ce2SRoman Pen static void *new_vmap_block(unsigned int order, gfp_t gfp_mask)
1542db64fe02SNick Piggin {
1543db64fe02SNick Piggin 	struct vmap_block_queue *vbq;
1544db64fe02SNick Piggin 	struct vmap_block *vb;
1545db64fe02SNick Piggin 	struct vmap_area *va;
1546db64fe02SNick Piggin 	unsigned long vb_idx;
1547db64fe02SNick Piggin 	int node, err;
1548cf725ce2SRoman Pen 	void *vaddr;
1549db64fe02SNick Piggin 
1550db64fe02SNick Piggin 	node = numa_node_id();
1551db64fe02SNick Piggin 
1552db64fe02SNick Piggin 	vb = kmalloc_node(sizeof(struct vmap_block),
1553db64fe02SNick Piggin 			gfp_mask & GFP_RECLAIM_MASK, node);
1554db64fe02SNick Piggin 	if (unlikely(!vb))
1555db64fe02SNick Piggin 		return ERR_PTR(-ENOMEM);
1556db64fe02SNick Piggin 
1557db64fe02SNick Piggin 	va = alloc_vmap_area(VMAP_BLOCK_SIZE, VMAP_BLOCK_SIZE,
1558db64fe02SNick Piggin 					VMALLOC_START, VMALLOC_END,
1559db64fe02SNick Piggin 					node, gfp_mask);
1560ddf9c6d4STobias Klauser 	if (IS_ERR(va)) {
1561db64fe02SNick Piggin 		kfree(vb);
1562e7d86340SJulia Lawall 		return ERR_CAST(va);
1563db64fe02SNick Piggin 	}
1564db64fe02SNick Piggin 
1565cf725ce2SRoman Pen 	vaddr = vmap_block_vaddr(va->va_start, 0);
1566db64fe02SNick Piggin 	spin_lock_init(&vb->lock);
1567db64fe02SNick Piggin 	vb->va = va;
1568cf725ce2SRoman Pen 	/* At least something should be left free */
1569cf725ce2SRoman Pen 	BUG_ON(VMAP_BBMAP_BITS <= (1UL << order));
1570cf725ce2SRoman Pen 	vb->free = VMAP_BBMAP_BITS - (1UL << order);
1571db64fe02SNick Piggin 	vb->dirty = 0;
15727d61bfe8SRoman Pen 	vb->dirty_min = VMAP_BBMAP_BITS;
15737d61bfe8SRoman Pen 	vb->dirty_max = 0;
1574db64fe02SNick Piggin 	INIT_LIST_HEAD(&vb->free_list);
1575db64fe02SNick Piggin 
1576db64fe02SNick Piggin 	vb_idx = addr_to_vb_idx(va->va_start);
15770f14599cSMatthew Wilcox (Oracle) 	err = xa_insert(&vmap_blocks, vb_idx, vb, gfp_mask);
15780f14599cSMatthew Wilcox (Oracle) 	if (err) {
15790f14599cSMatthew Wilcox (Oracle) 		kfree(vb);
15800f14599cSMatthew Wilcox (Oracle) 		free_vmap_area(va);
15810f14599cSMatthew Wilcox (Oracle) 		return ERR_PTR(err);
15820f14599cSMatthew Wilcox (Oracle) 	}
1583db64fe02SNick Piggin 
1584db64fe02SNick Piggin 	vbq = &get_cpu_var(vmap_block_queue);
1585db64fe02SNick Piggin 	spin_lock(&vbq->lock);
158668ac546fSRoman Pen 	list_add_tail_rcu(&vb->free_list, &vbq->free);
1587db64fe02SNick Piggin 	spin_unlock(&vbq->lock);
15883f04ba85STejun Heo 	put_cpu_var(vmap_block_queue);
1589db64fe02SNick Piggin 
1590cf725ce2SRoman Pen 	return vaddr;
1591db64fe02SNick Piggin }
1592db64fe02SNick Piggin 
1593db64fe02SNick Piggin static void free_vmap_block(struct vmap_block *vb)
1594db64fe02SNick Piggin {
1595db64fe02SNick Piggin 	struct vmap_block *tmp;
1596db64fe02SNick Piggin 
15970f14599cSMatthew Wilcox (Oracle) 	tmp = xa_erase(&vmap_blocks, addr_to_vb_idx(vb->va->va_start));
1598db64fe02SNick Piggin 	BUG_ON(tmp != vb);
1599db64fe02SNick Piggin 
160064141da5SJeremy Fitzhardinge 	free_vmap_area_noflush(vb->va);
160122a3c7d1SLai Jiangshan 	kfree_rcu(vb, rcu_head);
1602db64fe02SNick Piggin }
1603db64fe02SNick Piggin 
160402b709dfSNick Piggin static void purge_fragmented_blocks(int cpu)
160502b709dfSNick Piggin {
160602b709dfSNick Piggin 	LIST_HEAD(purge);
160702b709dfSNick Piggin 	struct vmap_block *vb;
160802b709dfSNick Piggin 	struct vmap_block *n_vb;
160902b709dfSNick Piggin 	struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu);
161002b709dfSNick Piggin 
161102b709dfSNick Piggin 	rcu_read_lock();
161202b709dfSNick Piggin 	list_for_each_entry_rcu(vb, &vbq->free, free_list) {
161302b709dfSNick Piggin 
161402b709dfSNick Piggin 		if (!(vb->free + vb->dirty == VMAP_BBMAP_BITS && vb->dirty != VMAP_BBMAP_BITS))
161502b709dfSNick Piggin 			continue;
161602b709dfSNick Piggin 
161702b709dfSNick Piggin 		spin_lock(&vb->lock);
161802b709dfSNick Piggin 		if (vb->free + vb->dirty == VMAP_BBMAP_BITS && vb->dirty != VMAP_BBMAP_BITS) {
161902b709dfSNick Piggin 			vb->free = 0; /* prevent further allocs after releasing lock */
162002b709dfSNick Piggin 			vb->dirty = VMAP_BBMAP_BITS; /* prevent purging it again */
16217d61bfe8SRoman Pen 			vb->dirty_min = 0;
16227d61bfe8SRoman Pen 			vb->dirty_max = VMAP_BBMAP_BITS;
162302b709dfSNick Piggin 			spin_lock(&vbq->lock);
162402b709dfSNick Piggin 			list_del_rcu(&vb->free_list);
162502b709dfSNick Piggin 			spin_unlock(&vbq->lock);
162602b709dfSNick Piggin 			spin_unlock(&vb->lock);
162702b709dfSNick Piggin 			list_add_tail(&vb->purge, &purge);
162802b709dfSNick Piggin 		} else
162902b709dfSNick Piggin 			spin_unlock(&vb->lock);
163002b709dfSNick Piggin 	}
163102b709dfSNick Piggin 	rcu_read_unlock();
163202b709dfSNick Piggin 
163302b709dfSNick Piggin 	list_for_each_entry_safe(vb, n_vb, &purge, purge) {
163402b709dfSNick Piggin 		list_del(&vb->purge);
163502b709dfSNick Piggin 		free_vmap_block(vb);
163602b709dfSNick Piggin 	}
163702b709dfSNick Piggin }
163802b709dfSNick Piggin 
163902b709dfSNick Piggin static void purge_fragmented_blocks_allcpus(void)
164002b709dfSNick Piggin {
164102b709dfSNick Piggin 	int cpu;
164202b709dfSNick Piggin 
164302b709dfSNick Piggin 	for_each_possible_cpu(cpu)
164402b709dfSNick Piggin 		purge_fragmented_blocks(cpu);
164502b709dfSNick Piggin }
164602b709dfSNick Piggin 
1647db64fe02SNick Piggin static void *vb_alloc(unsigned long size, gfp_t gfp_mask)
1648db64fe02SNick Piggin {
1649db64fe02SNick Piggin 	struct vmap_block_queue *vbq;
1650db64fe02SNick Piggin 	struct vmap_block *vb;
1651cf725ce2SRoman Pen 	void *vaddr = NULL;
1652db64fe02SNick Piggin 	unsigned int order;
1653db64fe02SNick Piggin 
1654891c49abSAlexander Kuleshov 	BUG_ON(offset_in_page(size));
1655db64fe02SNick Piggin 	BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
1656aa91c4d8SJan Kara 	if (WARN_ON(size == 0)) {
1657aa91c4d8SJan Kara 		/*
1658aa91c4d8SJan Kara 		 * Allocating 0 bytes isn't what caller wants since
1659aa91c4d8SJan Kara 		 * get_order(0) returns funny result. Just warn and terminate
1660aa91c4d8SJan Kara 		 * early.
1661aa91c4d8SJan Kara 		 */
1662aa91c4d8SJan Kara 		return NULL;
1663aa91c4d8SJan Kara 	}
1664db64fe02SNick Piggin 	order = get_order(size);
1665db64fe02SNick Piggin 
1666db64fe02SNick Piggin 	rcu_read_lock();
1667db64fe02SNick Piggin 	vbq = &get_cpu_var(vmap_block_queue);
1668db64fe02SNick Piggin 	list_for_each_entry_rcu(vb, &vbq->free, free_list) {
1669cf725ce2SRoman Pen 		unsigned long pages_off;
1670db64fe02SNick Piggin 
1671db64fe02SNick Piggin 		spin_lock(&vb->lock);
1672cf725ce2SRoman Pen 		if (vb->free < (1UL << order)) {
1673cf725ce2SRoman Pen 			spin_unlock(&vb->lock);
1674cf725ce2SRoman Pen 			continue;
1675cf725ce2SRoman Pen 		}
167602b709dfSNick Piggin 
1677cf725ce2SRoman Pen 		pages_off = VMAP_BBMAP_BITS - vb->free;
1678cf725ce2SRoman Pen 		vaddr = vmap_block_vaddr(vb->va->va_start, pages_off);
1679db64fe02SNick Piggin 		vb->free -= 1UL << order;
1680db64fe02SNick Piggin 		if (vb->free == 0) {
1681db64fe02SNick Piggin 			spin_lock(&vbq->lock);
1682de560423SNick Piggin 			list_del_rcu(&vb->free_list);
1683db64fe02SNick Piggin 			spin_unlock(&vbq->lock);
1684db64fe02SNick Piggin 		}
1685cf725ce2SRoman Pen 
1686db64fe02SNick Piggin 		spin_unlock(&vb->lock);
1687db64fe02SNick Piggin 		break;
1688db64fe02SNick Piggin 	}
168902b709dfSNick Piggin 
16903f04ba85STejun Heo 	put_cpu_var(vmap_block_queue);
1691db64fe02SNick Piggin 	rcu_read_unlock();
1692db64fe02SNick Piggin 
1693cf725ce2SRoman Pen 	/* Allocate new block if nothing was found */
1694cf725ce2SRoman Pen 	if (!vaddr)
1695cf725ce2SRoman Pen 		vaddr = new_vmap_block(order, gfp_mask);
1696db64fe02SNick Piggin 
1697cf725ce2SRoman Pen 	return vaddr;
1698db64fe02SNick Piggin }
1699db64fe02SNick Piggin 
170078a0e8c4SChristoph Hellwig static void vb_free(unsigned long addr, unsigned long size)
1701db64fe02SNick Piggin {
1702db64fe02SNick Piggin 	unsigned long offset;
1703db64fe02SNick Piggin 	unsigned int order;
1704db64fe02SNick Piggin 	struct vmap_block *vb;
1705db64fe02SNick Piggin 
1706891c49abSAlexander Kuleshov 	BUG_ON(offset_in_page(size));
1707db64fe02SNick Piggin 	BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
1708b29acbdcSNick Piggin 
170978a0e8c4SChristoph Hellwig 	flush_cache_vunmap(addr, addr + size);
1710b29acbdcSNick Piggin 
1711db64fe02SNick Piggin 	order = get_order(size);
171278a0e8c4SChristoph Hellwig 	offset = (addr & (VMAP_BLOCK_SIZE - 1)) >> PAGE_SHIFT;
17130f14599cSMatthew Wilcox (Oracle) 	vb = xa_load(&vmap_blocks, addr_to_vb_idx(addr));
1714db64fe02SNick Piggin 
1715b521c43fSChristoph Hellwig 	unmap_kernel_range_noflush(addr, size);
171664141da5SJeremy Fitzhardinge 
17178e57f8acSVlastimil Babka 	if (debug_pagealloc_enabled_static())
171878a0e8c4SChristoph Hellwig 		flush_tlb_kernel_range(addr, addr + size);
171982a2e924SChintan Pandya 
1720db64fe02SNick Piggin 	spin_lock(&vb->lock);
17217d61bfe8SRoman Pen 
17227d61bfe8SRoman Pen 	/* Expand dirty range */
17237d61bfe8SRoman Pen 	vb->dirty_min = min(vb->dirty_min, offset);
17247d61bfe8SRoman Pen 	vb->dirty_max = max(vb->dirty_max, offset + (1UL << order));
1725d086817dSMinChan Kim 
1726db64fe02SNick Piggin 	vb->dirty += 1UL << order;
1727db64fe02SNick Piggin 	if (vb->dirty == VMAP_BBMAP_BITS) {
1728de560423SNick Piggin 		BUG_ON(vb->free);
1729db64fe02SNick Piggin 		spin_unlock(&vb->lock);
1730db64fe02SNick Piggin 		free_vmap_block(vb);
1731db64fe02SNick Piggin 	} else
1732db64fe02SNick Piggin 		spin_unlock(&vb->lock);
1733db64fe02SNick Piggin }
1734db64fe02SNick Piggin 
1735868b104dSRick Edgecombe static void _vm_unmap_aliases(unsigned long start, unsigned long end, int flush)
1736db64fe02SNick Piggin {
1737db64fe02SNick Piggin 	int cpu;
1738db64fe02SNick Piggin 
17399b463334SJeremy Fitzhardinge 	if (unlikely(!vmap_initialized))
17409b463334SJeremy Fitzhardinge 		return;
17419b463334SJeremy Fitzhardinge 
17425803ed29SChristoph Hellwig 	might_sleep();
17435803ed29SChristoph Hellwig 
1744db64fe02SNick Piggin 	for_each_possible_cpu(cpu) {
1745db64fe02SNick Piggin 		struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu);
1746db64fe02SNick Piggin 		struct vmap_block *vb;
1747db64fe02SNick Piggin 
1748db64fe02SNick Piggin 		rcu_read_lock();
1749db64fe02SNick Piggin 		list_for_each_entry_rcu(vb, &vbq->free, free_list) {
1750db64fe02SNick Piggin 			spin_lock(&vb->lock);
17517d61bfe8SRoman Pen 			if (vb->dirty) {
17527d61bfe8SRoman Pen 				unsigned long va_start = vb->va->va_start;
1753db64fe02SNick Piggin 				unsigned long s, e;
1754b136be5eSJoonsoo Kim 
17557d61bfe8SRoman Pen 				s = va_start + (vb->dirty_min << PAGE_SHIFT);
17567d61bfe8SRoman Pen 				e = va_start + (vb->dirty_max << PAGE_SHIFT);
1757db64fe02SNick Piggin 
17587d61bfe8SRoman Pen 				start = min(s, start);
17597d61bfe8SRoman Pen 				end   = max(e, end);
17607d61bfe8SRoman Pen 
1761db64fe02SNick Piggin 				flush = 1;
1762db64fe02SNick Piggin 			}
1763db64fe02SNick Piggin 			spin_unlock(&vb->lock);
1764db64fe02SNick Piggin 		}
1765db64fe02SNick Piggin 		rcu_read_unlock();
1766db64fe02SNick Piggin 	}
1767db64fe02SNick Piggin 
1768f9e09977SChristoph Hellwig 	mutex_lock(&vmap_purge_lock);
17690574ecd1SChristoph Hellwig 	purge_fragmented_blocks_allcpus();
17700574ecd1SChristoph Hellwig 	if (!__purge_vmap_area_lazy(start, end) && flush)
17710574ecd1SChristoph Hellwig 		flush_tlb_kernel_range(start, end);
1772f9e09977SChristoph Hellwig 	mutex_unlock(&vmap_purge_lock);
1773db64fe02SNick Piggin }
1774868b104dSRick Edgecombe 
1775868b104dSRick Edgecombe /**
1776868b104dSRick Edgecombe  * vm_unmap_aliases - unmap outstanding lazy aliases in the vmap layer
1777868b104dSRick Edgecombe  *
1778868b104dSRick Edgecombe  * The vmap/vmalloc layer lazily flushes kernel virtual mappings primarily
1779868b104dSRick Edgecombe  * to amortize TLB flushing overheads. What this means is that any page you
1780868b104dSRick Edgecombe  * have now, may, in a former life, have been mapped into kernel virtual
1781868b104dSRick Edgecombe  * address by the vmap layer and so there might be some CPUs with TLB entries
1782868b104dSRick Edgecombe  * still referencing that page (additional to the regular 1:1 kernel mapping).
1783868b104dSRick Edgecombe  *
1784868b104dSRick Edgecombe  * vm_unmap_aliases flushes all such lazy mappings. After it returns, we can
1785868b104dSRick Edgecombe  * be sure that none of the pages we have control over will have any aliases
1786868b104dSRick Edgecombe  * from the vmap layer.
1787868b104dSRick Edgecombe  */
1788868b104dSRick Edgecombe void vm_unmap_aliases(void)
1789868b104dSRick Edgecombe {
1790868b104dSRick Edgecombe 	unsigned long start = ULONG_MAX, end = 0;
1791868b104dSRick Edgecombe 	int flush = 0;
1792868b104dSRick Edgecombe 
1793868b104dSRick Edgecombe 	_vm_unmap_aliases(start, end, flush);
1794868b104dSRick Edgecombe }
1795db64fe02SNick Piggin EXPORT_SYMBOL_GPL(vm_unmap_aliases);
1796db64fe02SNick Piggin 
1797db64fe02SNick Piggin /**
1798db64fe02SNick Piggin  * vm_unmap_ram - unmap linear kernel address space set up by vm_map_ram
1799db64fe02SNick Piggin  * @mem: the pointer returned by vm_map_ram
1800db64fe02SNick Piggin  * @count: the count passed to that vm_map_ram call (cannot unmap partial)
1801db64fe02SNick Piggin  */
1802db64fe02SNick Piggin void vm_unmap_ram(const void *mem, unsigned int count)
1803db64fe02SNick Piggin {
180465ee03c4SGuillermo Julián Moreno 	unsigned long size = (unsigned long)count << PAGE_SHIFT;
1805db64fe02SNick Piggin 	unsigned long addr = (unsigned long)mem;
18069c3acf60SChristoph Hellwig 	struct vmap_area *va;
1807db64fe02SNick Piggin 
18085803ed29SChristoph Hellwig 	might_sleep();
1809db64fe02SNick Piggin 	BUG_ON(!addr);
1810db64fe02SNick Piggin 	BUG_ON(addr < VMALLOC_START);
1811db64fe02SNick Piggin 	BUG_ON(addr > VMALLOC_END);
1812a1c0b1a0SShawn Lin 	BUG_ON(!PAGE_ALIGNED(addr));
1813db64fe02SNick Piggin 
1814d98c9e83SAndrey Ryabinin 	kasan_poison_vmalloc(mem, size);
1815d98c9e83SAndrey Ryabinin 
18169c3acf60SChristoph Hellwig 	if (likely(count <= VMAP_MAX_ALLOC)) {
181705e3ff95SChintan Pandya 		debug_check_no_locks_freed(mem, size);
181878a0e8c4SChristoph Hellwig 		vb_free(addr, size);
18199c3acf60SChristoph Hellwig 		return;
18209c3acf60SChristoph Hellwig 	}
18219c3acf60SChristoph Hellwig 
18229c3acf60SChristoph Hellwig 	va = find_vmap_area(addr);
18239c3acf60SChristoph Hellwig 	BUG_ON(!va);
182405e3ff95SChintan Pandya 	debug_check_no_locks_freed((void *)va->va_start,
182505e3ff95SChintan Pandya 				    (va->va_end - va->va_start));
18269c3acf60SChristoph Hellwig 	free_unmap_vmap_area(va);
1827db64fe02SNick Piggin }
1828db64fe02SNick Piggin EXPORT_SYMBOL(vm_unmap_ram);
1829db64fe02SNick Piggin 
1830db64fe02SNick Piggin /**
1831db64fe02SNick Piggin  * vm_map_ram - map pages linearly into kernel virtual address (vmalloc space)
1832db64fe02SNick Piggin  * @pages: an array of pointers to the pages to be mapped
1833db64fe02SNick Piggin  * @count: number of pages
1834db64fe02SNick Piggin  * @node: prefer to allocate data structures on this node
1835e99c97adSRandy Dunlap  *
183636437638SGioh Kim  * If you use this function for less than VMAP_MAX_ALLOC pages, it could be
183736437638SGioh Kim  * faster than vmap so it's good.  But if you mix long-life and short-life
183836437638SGioh Kim  * objects with vm_map_ram(), it could consume lots of address space through
183936437638SGioh Kim  * fragmentation (especially on a 32bit machine).  You could see failures in
184036437638SGioh Kim  * the end.  Please use this function for short-lived objects.
184136437638SGioh Kim  *
1842e99c97adSRandy Dunlap  * Returns: a pointer to the address that has been mapped, or %NULL on failure
1843db64fe02SNick Piggin  */
1844d4efd79aSChristoph Hellwig void *vm_map_ram(struct page **pages, unsigned int count, int node)
1845db64fe02SNick Piggin {
184665ee03c4SGuillermo Julián Moreno 	unsigned long size = (unsigned long)count << PAGE_SHIFT;
1847db64fe02SNick Piggin 	unsigned long addr;
1848db64fe02SNick Piggin 	void *mem;
1849db64fe02SNick Piggin 
1850db64fe02SNick Piggin 	if (likely(count <= VMAP_MAX_ALLOC)) {
1851db64fe02SNick Piggin 		mem = vb_alloc(size, GFP_KERNEL);
1852db64fe02SNick Piggin 		if (IS_ERR(mem))
1853db64fe02SNick Piggin 			return NULL;
1854db64fe02SNick Piggin 		addr = (unsigned long)mem;
1855db64fe02SNick Piggin 	} else {
1856db64fe02SNick Piggin 		struct vmap_area *va;
1857db64fe02SNick Piggin 		va = alloc_vmap_area(size, PAGE_SIZE,
1858db64fe02SNick Piggin 				VMALLOC_START, VMALLOC_END, node, GFP_KERNEL);
1859db64fe02SNick Piggin 		if (IS_ERR(va))
1860db64fe02SNick Piggin 			return NULL;
1861db64fe02SNick Piggin 
1862db64fe02SNick Piggin 		addr = va->va_start;
1863db64fe02SNick Piggin 		mem = (void *)addr;
1864db64fe02SNick Piggin 	}
1865d98c9e83SAndrey Ryabinin 
1866d98c9e83SAndrey Ryabinin 	kasan_unpoison_vmalloc(mem, size);
1867d98c9e83SAndrey Ryabinin 
1868d4efd79aSChristoph Hellwig 	if (map_kernel_range(addr, size, PAGE_KERNEL, pages) < 0) {
1869db64fe02SNick Piggin 		vm_unmap_ram(mem, count);
1870db64fe02SNick Piggin 		return NULL;
1871db64fe02SNick Piggin 	}
1872db64fe02SNick Piggin 	return mem;
1873db64fe02SNick Piggin }
1874db64fe02SNick Piggin EXPORT_SYMBOL(vm_map_ram);
1875db64fe02SNick Piggin 
18764341fa45SJoonsoo Kim static struct vm_struct *vmlist __initdata;
187792eac168SMike Rapoport 
1878f0aa6617STejun Heo /**
1879be9b7335SNicolas Pitre  * vm_area_add_early - add vmap area early during boot
1880be9b7335SNicolas Pitre  * @vm: vm_struct to add
1881be9b7335SNicolas Pitre  *
1882be9b7335SNicolas Pitre  * This function is used to add fixed kernel vm area to vmlist before
1883be9b7335SNicolas Pitre  * vmalloc_init() is called.  @vm->addr, @vm->size, and @vm->flags
1884be9b7335SNicolas Pitre  * should contain proper values and the other fields should be zero.
1885be9b7335SNicolas Pitre  *
1886be9b7335SNicolas Pitre  * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING.
1887be9b7335SNicolas Pitre  */
1888be9b7335SNicolas Pitre void __init vm_area_add_early(struct vm_struct *vm)
1889be9b7335SNicolas Pitre {
1890be9b7335SNicolas Pitre 	struct vm_struct *tmp, **p;
1891be9b7335SNicolas Pitre 
1892be9b7335SNicolas Pitre 	BUG_ON(vmap_initialized);
1893be9b7335SNicolas Pitre 	for (p = &vmlist; (tmp = *p) != NULL; p = &tmp->next) {
1894be9b7335SNicolas Pitre 		if (tmp->addr >= vm->addr) {
1895be9b7335SNicolas Pitre 			BUG_ON(tmp->addr < vm->addr + vm->size);
1896be9b7335SNicolas Pitre 			break;
1897be9b7335SNicolas Pitre 		} else
1898be9b7335SNicolas Pitre 			BUG_ON(tmp->addr + tmp->size > vm->addr);
1899be9b7335SNicolas Pitre 	}
1900be9b7335SNicolas Pitre 	vm->next = *p;
1901be9b7335SNicolas Pitre 	*p = vm;
1902be9b7335SNicolas Pitre }
1903be9b7335SNicolas Pitre 
1904be9b7335SNicolas Pitre /**
1905f0aa6617STejun Heo  * vm_area_register_early - register vmap area early during boot
1906f0aa6617STejun Heo  * @vm: vm_struct to register
1907c0c0a293STejun Heo  * @align: requested alignment
1908f0aa6617STejun Heo  *
1909f0aa6617STejun Heo  * This function is used to register kernel vm area before
1910f0aa6617STejun Heo  * vmalloc_init() is called.  @vm->size and @vm->flags should contain
1911f0aa6617STejun Heo  * proper values on entry and other fields should be zero.  On return,
1912f0aa6617STejun Heo  * vm->addr contains the allocated address.
1913f0aa6617STejun Heo  *
1914f0aa6617STejun Heo  * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING.
1915f0aa6617STejun Heo  */
1916c0c0a293STejun Heo void __init vm_area_register_early(struct vm_struct *vm, size_t align)
1917f0aa6617STejun Heo {
1918f0aa6617STejun Heo 	static size_t vm_init_off __initdata;
1919c0c0a293STejun Heo 	unsigned long addr;
1920f0aa6617STejun Heo 
1921c0c0a293STejun Heo 	addr = ALIGN(VMALLOC_START + vm_init_off, align);
1922c0c0a293STejun Heo 	vm_init_off = PFN_ALIGN(addr + vm->size) - VMALLOC_START;
1923c0c0a293STejun Heo 
1924c0c0a293STejun Heo 	vm->addr = (void *)addr;
1925f0aa6617STejun Heo 
1926be9b7335SNicolas Pitre 	vm_area_add_early(vm);
1927f0aa6617STejun Heo }
1928f0aa6617STejun Heo 
192968ad4a33SUladzislau Rezki (Sony) static void vmap_init_free_space(void)
193068ad4a33SUladzislau Rezki (Sony) {
193168ad4a33SUladzislau Rezki (Sony) 	unsigned long vmap_start = 1;
193268ad4a33SUladzislau Rezki (Sony) 	const unsigned long vmap_end = ULONG_MAX;
193368ad4a33SUladzislau Rezki (Sony) 	struct vmap_area *busy, *free;
193468ad4a33SUladzislau Rezki (Sony) 
193568ad4a33SUladzislau Rezki (Sony) 	/*
193668ad4a33SUladzislau Rezki (Sony) 	 *     B     F     B     B     B     F
193768ad4a33SUladzislau Rezki (Sony) 	 * -|-----|.....|-----|-----|-----|.....|-
193868ad4a33SUladzislau Rezki (Sony) 	 *  |           The KVA space           |
193968ad4a33SUladzislau Rezki (Sony) 	 *  |<--------------------------------->|
194068ad4a33SUladzislau Rezki (Sony) 	 */
194168ad4a33SUladzislau Rezki (Sony) 	list_for_each_entry(busy, &vmap_area_list, list) {
194268ad4a33SUladzislau Rezki (Sony) 		if (busy->va_start - vmap_start > 0) {
194368ad4a33SUladzislau Rezki (Sony) 			free = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
194468ad4a33SUladzislau Rezki (Sony) 			if (!WARN_ON_ONCE(!free)) {
194568ad4a33SUladzislau Rezki (Sony) 				free->va_start = vmap_start;
194668ad4a33SUladzislau Rezki (Sony) 				free->va_end = busy->va_start;
194768ad4a33SUladzislau Rezki (Sony) 
194868ad4a33SUladzislau Rezki (Sony) 				insert_vmap_area_augment(free, NULL,
194968ad4a33SUladzislau Rezki (Sony) 					&free_vmap_area_root,
195068ad4a33SUladzislau Rezki (Sony) 						&free_vmap_area_list);
195168ad4a33SUladzislau Rezki (Sony) 			}
195268ad4a33SUladzislau Rezki (Sony) 		}
195368ad4a33SUladzislau Rezki (Sony) 
195468ad4a33SUladzislau Rezki (Sony) 		vmap_start = busy->va_end;
195568ad4a33SUladzislau Rezki (Sony) 	}
195668ad4a33SUladzislau Rezki (Sony) 
195768ad4a33SUladzislau Rezki (Sony) 	if (vmap_end - vmap_start > 0) {
195868ad4a33SUladzislau Rezki (Sony) 		free = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
195968ad4a33SUladzislau Rezki (Sony) 		if (!WARN_ON_ONCE(!free)) {
196068ad4a33SUladzislau Rezki (Sony) 			free->va_start = vmap_start;
196168ad4a33SUladzislau Rezki (Sony) 			free->va_end = vmap_end;
196268ad4a33SUladzislau Rezki (Sony) 
196368ad4a33SUladzislau Rezki (Sony) 			insert_vmap_area_augment(free, NULL,
196468ad4a33SUladzislau Rezki (Sony) 				&free_vmap_area_root,
196568ad4a33SUladzislau Rezki (Sony) 					&free_vmap_area_list);
196668ad4a33SUladzislau Rezki (Sony) 		}
196768ad4a33SUladzislau Rezki (Sony) 	}
196868ad4a33SUladzislau Rezki (Sony) }
196968ad4a33SUladzislau Rezki (Sony) 
1970db64fe02SNick Piggin void __init vmalloc_init(void)
1971db64fe02SNick Piggin {
1972822c18f2SIvan Kokshaysky 	struct vmap_area *va;
1973822c18f2SIvan Kokshaysky 	struct vm_struct *tmp;
1974db64fe02SNick Piggin 	int i;
1975db64fe02SNick Piggin 
197668ad4a33SUladzislau Rezki (Sony) 	/*
197768ad4a33SUladzislau Rezki (Sony) 	 * Create the cache for vmap_area objects.
197868ad4a33SUladzislau Rezki (Sony) 	 */
197968ad4a33SUladzislau Rezki (Sony) 	vmap_area_cachep = KMEM_CACHE(vmap_area, SLAB_PANIC);
198068ad4a33SUladzislau Rezki (Sony) 
1981db64fe02SNick Piggin 	for_each_possible_cpu(i) {
1982db64fe02SNick Piggin 		struct vmap_block_queue *vbq;
198332fcfd40SAl Viro 		struct vfree_deferred *p;
1984db64fe02SNick Piggin 
1985db64fe02SNick Piggin 		vbq = &per_cpu(vmap_block_queue, i);
1986db64fe02SNick Piggin 		spin_lock_init(&vbq->lock);
1987db64fe02SNick Piggin 		INIT_LIST_HEAD(&vbq->free);
198832fcfd40SAl Viro 		p = &per_cpu(vfree_deferred, i);
198932fcfd40SAl Viro 		init_llist_head(&p->list);
199032fcfd40SAl Viro 		INIT_WORK(&p->wq, free_work);
1991db64fe02SNick Piggin 	}
19929b463334SJeremy Fitzhardinge 
1993822c18f2SIvan Kokshaysky 	/* Import existing vmlist entries. */
1994822c18f2SIvan Kokshaysky 	for (tmp = vmlist; tmp; tmp = tmp->next) {
199568ad4a33SUladzislau Rezki (Sony) 		va = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
199668ad4a33SUladzislau Rezki (Sony) 		if (WARN_ON_ONCE(!va))
199768ad4a33SUladzislau Rezki (Sony) 			continue;
199868ad4a33SUladzislau Rezki (Sony) 
1999822c18f2SIvan Kokshaysky 		va->va_start = (unsigned long)tmp->addr;
2000822c18f2SIvan Kokshaysky 		va->va_end = va->va_start + tmp->size;
2001dbda591dSKyongHo 		va->vm = tmp;
200268ad4a33SUladzislau Rezki (Sony) 		insert_vmap_area(va, &vmap_area_root, &vmap_area_list);
2003822c18f2SIvan Kokshaysky 	}
2004ca23e405STejun Heo 
200568ad4a33SUladzislau Rezki (Sony) 	/*
200668ad4a33SUladzislau Rezki (Sony) 	 * Now we can initialize a free vmap space.
200768ad4a33SUladzislau Rezki (Sony) 	 */
200868ad4a33SUladzislau Rezki (Sony) 	vmap_init_free_space();
20099b463334SJeremy Fitzhardinge 	vmap_initialized = true;
2010db64fe02SNick Piggin }
2011db64fe02SNick Piggin 
20128fc48985STejun Heo /**
20138fc48985STejun Heo  * unmap_kernel_range - unmap kernel VM area and flush cache and TLB
20148fc48985STejun Heo  * @addr: start of the VM area to unmap
20158fc48985STejun Heo  * @size: size of the VM area to unmap
20168fc48985STejun Heo  *
20178fc48985STejun Heo  * Similar to unmap_kernel_range_noflush() but flushes vcache before
20188fc48985STejun Heo  * the unmapping and tlb after.
20198fc48985STejun Heo  */
2020db64fe02SNick Piggin void unmap_kernel_range(unsigned long addr, unsigned long size)
2021db64fe02SNick Piggin {
2022db64fe02SNick Piggin 	unsigned long end = addr + size;
2023f6fcba70STejun Heo 
2024f6fcba70STejun Heo 	flush_cache_vunmap(addr, end);
2025b521c43fSChristoph Hellwig 	unmap_kernel_range_noflush(addr, size);
2026db64fe02SNick Piggin 	flush_tlb_kernel_range(addr, end);
2027db64fe02SNick Piggin }
2028db64fe02SNick Piggin 
2029e36176beSUladzislau Rezki (Sony) static inline void setup_vmalloc_vm_locked(struct vm_struct *vm,
2030e36176beSUladzislau Rezki (Sony) 	struct vmap_area *va, unsigned long flags, const void *caller)
2031cf88c790STejun Heo {
2032cf88c790STejun Heo 	vm->flags = flags;
2033cf88c790STejun Heo 	vm->addr = (void *)va->va_start;
2034cf88c790STejun Heo 	vm->size = va->va_end - va->va_start;
2035cf88c790STejun Heo 	vm->caller = caller;
2036db1aecafSMinchan Kim 	va->vm = vm;
2037e36176beSUladzislau Rezki (Sony) }
2038e36176beSUladzislau Rezki (Sony) 
2039e36176beSUladzislau Rezki (Sony) static void setup_vmalloc_vm(struct vm_struct *vm, struct vmap_area *va,
2040e36176beSUladzislau Rezki (Sony) 			      unsigned long flags, const void *caller)
2041e36176beSUladzislau Rezki (Sony) {
2042e36176beSUladzislau Rezki (Sony) 	spin_lock(&vmap_area_lock);
2043e36176beSUladzislau Rezki (Sony) 	setup_vmalloc_vm_locked(vm, va, flags, caller);
2044c69480adSJoonsoo Kim 	spin_unlock(&vmap_area_lock);
2045f5252e00SMitsuo Hayasaka }
2046cf88c790STejun Heo 
204720fc02b4SZhang Yanfei static void clear_vm_uninitialized_flag(struct vm_struct *vm)
2048f5252e00SMitsuo Hayasaka {
2049d4033afdSJoonsoo Kim 	/*
205020fc02b4SZhang Yanfei 	 * Before removing VM_UNINITIALIZED,
2051d4033afdSJoonsoo Kim 	 * we should make sure that vm has proper values.
2052d4033afdSJoonsoo Kim 	 * Pair with smp_rmb() in show_numa_info().
2053d4033afdSJoonsoo Kim 	 */
2054d4033afdSJoonsoo Kim 	smp_wmb();
205520fc02b4SZhang Yanfei 	vm->flags &= ~VM_UNINITIALIZED;
2056cf88c790STejun Heo }
2057cf88c790STejun Heo 
2058db64fe02SNick Piggin static struct vm_struct *__get_vm_area_node(unsigned long size,
20592dca6999SDavid Miller 		unsigned long align, unsigned long flags, unsigned long start,
20605e6cafc8SMarek Szyprowski 		unsigned long end, int node, gfp_t gfp_mask, const void *caller)
2061db64fe02SNick Piggin {
20620006526dSKautuk Consul 	struct vmap_area *va;
2063db64fe02SNick Piggin 	struct vm_struct *area;
2064d98c9e83SAndrey Ryabinin 	unsigned long requested_size = size;
20651da177e4SLinus Torvalds 
206652fd24caSGiridhar Pemmasani 	BUG_ON(in_interrupt());
20671da177e4SLinus Torvalds 	size = PAGE_ALIGN(size);
206831be8309SOGAWA Hirofumi 	if (unlikely(!size))
206931be8309SOGAWA Hirofumi 		return NULL;
20701da177e4SLinus Torvalds 
2071252e5c6eSzijun_hu 	if (flags & VM_IOREMAP)
2072252e5c6eSzijun_hu 		align = 1ul << clamp_t(int, get_count_order_long(size),
2073252e5c6eSzijun_hu 				       PAGE_SHIFT, IOREMAP_MAX_ORDER);
2074252e5c6eSzijun_hu 
2075cf88c790STejun Heo 	area = kzalloc_node(sizeof(*area), gfp_mask & GFP_RECLAIM_MASK, node);
20761da177e4SLinus Torvalds 	if (unlikely(!area))
20771da177e4SLinus Torvalds 		return NULL;
20781da177e4SLinus Torvalds 
207971394fe5SAndrey Ryabinin 	if (!(flags & VM_NO_GUARD))
20801da177e4SLinus Torvalds 		size += PAGE_SIZE;
20811da177e4SLinus Torvalds 
2082db64fe02SNick Piggin 	va = alloc_vmap_area(size, align, start, end, node, gfp_mask);
2083db64fe02SNick Piggin 	if (IS_ERR(va)) {
2084db64fe02SNick Piggin 		kfree(area);
2085db64fe02SNick Piggin 		return NULL;
20861da177e4SLinus Torvalds 	}
20871da177e4SLinus Torvalds 
2088d98c9e83SAndrey Ryabinin 	kasan_unpoison_vmalloc((void *)va->va_start, requested_size);
2089f5252e00SMitsuo Hayasaka 
2090d98c9e83SAndrey Ryabinin 	setup_vmalloc_vm(area, va, flags, caller);
20913c5c3cfbSDaniel Axtens 
20921da177e4SLinus Torvalds 	return area;
20931da177e4SLinus Torvalds }
20941da177e4SLinus Torvalds 
2095c2968612SBenjamin Herrenschmidt struct vm_struct *__get_vm_area_caller(unsigned long size, unsigned long flags,
2096c2968612SBenjamin Herrenschmidt 				       unsigned long start, unsigned long end,
20975e6cafc8SMarek Szyprowski 				       const void *caller)
2098c2968612SBenjamin Herrenschmidt {
209900ef2d2fSDavid Rientjes 	return __get_vm_area_node(size, 1, flags, start, end, NUMA_NO_NODE,
210000ef2d2fSDavid Rientjes 				  GFP_KERNEL, caller);
2101c2968612SBenjamin Herrenschmidt }
2102c2968612SBenjamin Herrenschmidt 
21031da177e4SLinus Torvalds /**
2104183ff22bSSimon Arlott  * get_vm_area - reserve a contiguous kernel virtual area
21051da177e4SLinus Torvalds  * @size:	 size of the area
21061da177e4SLinus Torvalds  * @flags:	 %VM_IOREMAP for I/O mappings or VM_ALLOC
21071da177e4SLinus Torvalds  *
21081da177e4SLinus Torvalds  * Search an area of @size in the kernel virtual mapping area,
21091da177e4SLinus Torvalds  * and reserved it for out purposes.  Returns the area descriptor
21101da177e4SLinus Torvalds  * on success or %NULL on failure.
2111a862f68aSMike Rapoport  *
2112a862f68aSMike Rapoport  * Return: the area descriptor on success or %NULL on failure.
21131da177e4SLinus Torvalds  */
21141da177e4SLinus Torvalds struct vm_struct *get_vm_area(unsigned long size, unsigned long flags)
21151da177e4SLinus Torvalds {
21162dca6999SDavid Miller 	return __get_vm_area_node(size, 1, flags, VMALLOC_START, VMALLOC_END,
211700ef2d2fSDavid Rientjes 				  NUMA_NO_NODE, GFP_KERNEL,
211800ef2d2fSDavid Rientjes 				  __builtin_return_address(0));
211923016969SChristoph Lameter }
212023016969SChristoph Lameter 
212123016969SChristoph Lameter struct vm_struct *get_vm_area_caller(unsigned long size, unsigned long flags,
21225e6cafc8SMarek Szyprowski 				const void *caller)
212323016969SChristoph Lameter {
21242dca6999SDavid Miller 	return __get_vm_area_node(size, 1, flags, VMALLOC_START, VMALLOC_END,
212500ef2d2fSDavid Rientjes 				  NUMA_NO_NODE, GFP_KERNEL, caller);
21261da177e4SLinus Torvalds }
21271da177e4SLinus Torvalds 
2128e9da6e99SMarek Szyprowski /**
2129e9da6e99SMarek Szyprowski  * find_vm_area - find a continuous kernel virtual area
2130e9da6e99SMarek Szyprowski  * @addr:	  base address
2131e9da6e99SMarek Szyprowski  *
2132e9da6e99SMarek Szyprowski  * Search for the kernel VM area starting at @addr, and return it.
2133e9da6e99SMarek Szyprowski  * It is up to the caller to do all required locking to keep the returned
2134e9da6e99SMarek Szyprowski  * pointer valid.
2135a862f68aSMike Rapoport  *
213674640617SHui Su  * Return: the area descriptor on success or %NULL on failure.
2137e9da6e99SMarek Szyprowski  */
2138e9da6e99SMarek Szyprowski struct vm_struct *find_vm_area(const void *addr)
213983342314SNick Piggin {
2140db64fe02SNick Piggin 	struct vmap_area *va;
214183342314SNick Piggin 
2142db64fe02SNick Piggin 	va = find_vmap_area((unsigned long)addr);
2143688fcbfcSPengfei Li 	if (!va)
21447856dfebSAndi Kleen 		return NULL;
2145688fcbfcSPengfei Li 
2146688fcbfcSPengfei Li 	return va->vm;
21477856dfebSAndi Kleen }
21487856dfebSAndi Kleen 
21491da177e4SLinus Torvalds /**
2150183ff22bSSimon Arlott  * remove_vm_area - find and remove a continuous kernel virtual area
21511da177e4SLinus Torvalds  * @addr:	    base address
21521da177e4SLinus Torvalds  *
21531da177e4SLinus Torvalds  * Search for the kernel VM area starting at @addr, and remove it.
21541da177e4SLinus Torvalds  * This function returns the found VM area, but using it is NOT safe
21557856dfebSAndi Kleen  * on SMP machines, except for its size or flags.
2156a862f68aSMike Rapoport  *
215774640617SHui Su  * Return: the area descriptor on success or %NULL on failure.
21581da177e4SLinus Torvalds  */
2159b3bdda02SChristoph Lameter struct vm_struct *remove_vm_area(const void *addr)
21601da177e4SLinus Torvalds {
2161db64fe02SNick Piggin 	struct vmap_area *va;
2162db64fe02SNick Piggin 
21635803ed29SChristoph Hellwig 	might_sleep();
21645803ed29SChristoph Hellwig 
2165dd3b8353SUladzislau Rezki (Sony) 	spin_lock(&vmap_area_lock);
2166dd3b8353SUladzislau Rezki (Sony) 	va = __find_vmap_area((unsigned long)addr);
2167688fcbfcSPengfei Li 	if (va && va->vm) {
2168db1aecafSMinchan Kim 		struct vm_struct *vm = va->vm;
2169f5252e00SMitsuo Hayasaka 
2170c69480adSJoonsoo Kim 		va->vm = NULL;
2171c69480adSJoonsoo Kim 		spin_unlock(&vmap_area_lock);
2172c69480adSJoonsoo Kim 
2173a5af5aa8SAndrey Ryabinin 		kasan_free_shadow(vm);
2174dd32c279SKAMEZAWA Hiroyuki 		free_unmap_vmap_area(va);
2175dd32c279SKAMEZAWA Hiroyuki 
2176db64fe02SNick Piggin 		return vm;
2177db64fe02SNick Piggin 	}
2178dd3b8353SUladzislau Rezki (Sony) 
2179dd3b8353SUladzislau Rezki (Sony) 	spin_unlock(&vmap_area_lock);
2180db64fe02SNick Piggin 	return NULL;
21811da177e4SLinus Torvalds }
21821da177e4SLinus Torvalds 
2183868b104dSRick Edgecombe static inline void set_area_direct_map(const struct vm_struct *area,
2184868b104dSRick Edgecombe 				       int (*set_direct_map)(struct page *page))
2185868b104dSRick Edgecombe {
2186868b104dSRick Edgecombe 	int i;
2187868b104dSRick Edgecombe 
2188868b104dSRick Edgecombe 	for (i = 0; i < area->nr_pages; i++)
2189868b104dSRick Edgecombe 		if (page_address(area->pages[i]))
2190868b104dSRick Edgecombe 			set_direct_map(area->pages[i]);
2191868b104dSRick Edgecombe }
2192868b104dSRick Edgecombe 
2193868b104dSRick Edgecombe /* Handle removing and resetting vm mappings related to the vm_struct. */
2194868b104dSRick Edgecombe static void vm_remove_mappings(struct vm_struct *area, int deallocate_pages)
2195868b104dSRick Edgecombe {
2196868b104dSRick Edgecombe 	unsigned long start = ULONG_MAX, end = 0;
2197868b104dSRick Edgecombe 	int flush_reset = area->flags & VM_FLUSH_RESET_PERMS;
219831e67340SRick Edgecombe 	int flush_dmap = 0;
2199868b104dSRick Edgecombe 	int i;
2200868b104dSRick Edgecombe 
2201868b104dSRick Edgecombe 	remove_vm_area(area->addr);
2202868b104dSRick Edgecombe 
2203868b104dSRick Edgecombe 	/* If this is not VM_FLUSH_RESET_PERMS memory, no need for the below. */
2204868b104dSRick Edgecombe 	if (!flush_reset)
2205868b104dSRick Edgecombe 		return;
2206868b104dSRick Edgecombe 
2207868b104dSRick Edgecombe 	/*
2208868b104dSRick Edgecombe 	 * If not deallocating pages, just do the flush of the VM area and
2209868b104dSRick Edgecombe 	 * return.
2210868b104dSRick Edgecombe 	 */
2211868b104dSRick Edgecombe 	if (!deallocate_pages) {
2212868b104dSRick Edgecombe 		vm_unmap_aliases();
2213868b104dSRick Edgecombe 		return;
2214868b104dSRick Edgecombe 	}
2215868b104dSRick Edgecombe 
2216868b104dSRick Edgecombe 	/*
2217868b104dSRick Edgecombe 	 * If execution gets here, flush the vm mapping and reset the direct
2218868b104dSRick Edgecombe 	 * map. Find the start and end range of the direct mappings to make sure
2219868b104dSRick Edgecombe 	 * the vm_unmap_aliases() flush includes the direct map.
2220868b104dSRick Edgecombe 	 */
2221868b104dSRick Edgecombe 	for (i = 0; i < area->nr_pages; i++) {
22228e41f872SRick Edgecombe 		unsigned long addr = (unsigned long)page_address(area->pages[i]);
22238e41f872SRick Edgecombe 		if (addr) {
2224868b104dSRick Edgecombe 			start = min(addr, start);
22258e41f872SRick Edgecombe 			end = max(addr + PAGE_SIZE, end);
222631e67340SRick Edgecombe 			flush_dmap = 1;
2227868b104dSRick Edgecombe 		}
2228868b104dSRick Edgecombe 	}
2229868b104dSRick Edgecombe 
2230868b104dSRick Edgecombe 	/*
2231868b104dSRick Edgecombe 	 * Set direct map to something invalid so that it won't be cached if
2232868b104dSRick Edgecombe 	 * there are any accesses after the TLB flush, then flush the TLB and
2233868b104dSRick Edgecombe 	 * reset the direct map permissions to the default.
2234868b104dSRick Edgecombe 	 */
2235868b104dSRick Edgecombe 	set_area_direct_map(area, set_direct_map_invalid_noflush);
223631e67340SRick Edgecombe 	_vm_unmap_aliases(start, end, flush_dmap);
2237868b104dSRick Edgecombe 	set_area_direct_map(area, set_direct_map_default_noflush);
2238868b104dSRick Edgecombe }
2239868b104dSRick Edgecombe 
2240b3bdda02SChristoph Lameter static void __vunmap(const void *addr, int deallocate_pages)
22411da177e4SLinus Torvalds {
22421da177e4SLinus Torvalds 	struct vm_struct *area;
22431da177e4SLinus Torvalds 
22441da177e4SLinus Torvalds 	if (!addr)
22451da177e4SLinus Torvalds 		return;
22461da177e4SLinus Torvalds 
2247e69e9d4aSHATAYAMA Daisuke 	if (WARN(!PAGE_ALIGNED(addr), "Trying to vfree() bad address (%p)\n",
2248ab15d9b4SDan Carpenter 			addr))
22491da177e4SLinus Torvalds 		return;
22501da177e4SLinus Torvalds 
22516ade2032SLiviu Dudau 	area = find_vm_area(addr);
22521da177e4SLinus Torvalds 	if (unlikely(!area)) {
22534c8573e2SArjan van de Ven 		WARN(1, KERN_ERR "Trying to vfree() nonexistent vm area (%p)\n",
22541da177e4SLinus Torvalds 				addr);
22551da177e4SLinus Torvalds 		return;
22561da177e4SLinus Torvalds 	}
22571da177e4SLinus Torvalds 
225805e3ff95SChintan Pandya 	debug_check_no_locks_freed(area->addr, get_vm_area_size(area));
225905e3ff95SChintan Pandya 	debug_check_no_obj_freed(area->addr, get_vm_area_size(area));
22609a11b49aSIngo Molnar 
22613c5c3cfbSDaniel Axtens 	kasan_poison_vmalloc(area->addr, area->size);
22623c5c3cfbSDaniel Axtens 
2263868b104dSRick Edgecombe 	vm_remove_mappings(area, deallocate_pages);
2264868b104dSRick Edgecombe 
22651da177e4SLinus Torvalds 	if (deallocate_pages) {
22661da177e4SLinus Torvalds 		int i;
22671da177e4SLinus Torvalds 
22681da177e4SLinus Torvalds 		for (i = 0; i < area->nr_pages; i++) {
2269bf53d6f8SChristoph Lameter 			struct page *page = area->pages[i];
2270bf53d6f8SChristoph Lameter 
2271bf53d6f8SChristoph Lameter 			BUG_ON(!page);
22724949148aSVladimir Davydov 			__free_pages(page, 0);
22731da177e4SLinus Torvalds 		}
227497105f0aSRoman Gushchin 		atomic_long_sub(area->nr_pages, &nr_vmalloc_pages);
22751da177e4SLinus Torvalds 
2276244d63eeSDavid Rientjes 		kvfree(area->pages);
22771da177e4SLinus Torvalds 	}
22781da177e4SLinus Torvalds 
22791da177e4SLinus Torvalds 	kfree(area);
22801da177e4SLinus Torvalds 	return;
22811da177e4SLinus Torvalds }
22821da177e4SLinus Torvalds 
2283bf22e37aSAndrey Ryabinin static inline void __vfree_deferred(const void *addr)
2284bf22e37aSAndrey Ryabinin {
2285bf22e37aSAndrey Ryabinin 	/*
2286bf22e37aSAndrey Ryabinin 	 * Use raw_cpu_ptr() because this can be called from preemptible
2287bf22e37aSAndrey Ryabinin 	 * context. Preemption is absolutely fine here, because the llist_add()
2288bf22e37aSAndrey Ryabinin 	 * implementation is lockless, so it works even if we are adding to
228973221d88SJeongtae Park 	 * another cpu's list. schedule_work() should be fine with this too.
2290bf22e37aSAndrey Ryabinin 	 */
2291bf22e37aSAndrey Ryabinin 	struct vfree_deferred *p = raw_cpu_ptr(&vfree_deferred);
2292bf22e37aSAndrey Ryabinin 
2293bf22e37aSAndrey Ryabinin 	if (llist_add((struct llist_node *)addr, &p->list))
2294bf22e37aSAndrey Ryabinin 		schedule_work(&p->wq);
2295bf22e37aSAndrey Ryabinin }
2296bf22e37aSAndrey Ryabinin 
2297bf22e37aSAndrey Ryabinin /**
2298bf22e37aSAndrey Ryabinin  * vfree_atomic - release memory allocated by vmalloc()
2299bf22e37aSAndrey Ryabinin  * @addr:	  memory base address
2300bf22e37aSAndrey Ryabinin  *
2301bf22e37aSAndrey Ryabinin  * This one is just like vfree() but can be called in any atomic context
2302bf22e37aSAndrey Ryabinin  * except NMIs.
2303bf22e37aSAndrey Ryabinin  */
2304bf22e37aSAndrey Ryabinin void vfree_atomic(const void *addr)
2305bf22e37aSAndrey Ryabinin {
2306bf22e37aSAndrey Ryabinin 	BUG_ON(in_nmi());
2307bf22e37aSAndrey Ryabinin 
2308bf22e37aSAndrey Ryabinin 	kmemleak_free(addr);
2309bf22e37aSAndrey Ryabinin 
2310bf22e37aSAndrey Ryabinin 	if (!addr)
2311bf22e37aSAndrey Ryabinin 		return;
2312bf22e37aSAndrey Ryabinin 	__vfree_deferred(addr);
2313bf22e37aSAndrey Ryabinin }
2314bf22e37aSAndrey Ryabinin 
2315c67dc624SRoman Penyaev static void __vfree(const void *addr)
2316c67dc624SRoman Penyaev {
2317c67dc624SRoman Penyaev 	if (unlikely(in_interrupt()))
2318c67dc624SRoman Penyaev 		__vfree_deferred(addr);
2319c67dc624SRoman Penyaev 	else
2320c67dc624SRoman Penyaev 		__vunmap(addr, 1);
2321c67dc624SRoman Penyaev }
2322c67dc624SRoman Penyaev 
23231da177e4SLinus Torvalds /**
2324fa307474SMatthew Wilcox (Oracle)  * vfree - Release memory allocated by vmalloc()
2325fa307474SMatthew Wilcox (Oracle)  * @addr:  Memory base address
23261da177e4SLinus Torvalds  *
2327fa307474SMatthew Wilcox (Oracle)  * Free the virtually continuous memory area starting at @addr, as obtained
2328fa307474SMatthew Wilcox (Oracle)  * from one of the vmalloc() family of APIs.  This will usually also free the
2329fa307474SMatthew Wilcox (Oracle)  * physical memory underlying the virtual allocation, but that memory is
2330fa307474SMatthew Wilcox (Oracle)  * reference counted, so it will not be freed until the last user goes away.
23311da177e4SLinus Torvalds  *
2332fa307474SMatthew Wilcox (Oracle)  * If @addr is NULL, no operation is performed.
233332fcfd40SAl Viro  *
2334fa307474SMatthew Wilcox (Oracle)  * Context:
23353ca4ea3aSAndrey Ryabinin  * May sleep if called *not* from interrupt context.
2336fa307474SMatthew Wilcox (Oracle)  * Must not be called in NMI context (strictly speaking, it could be
2337fa307474SMatthew Wilcox (Oracle)  * if we have CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG, but making the calling
2338fa307474SMatthew Wilcox (Oracle)  * conventions for vfree() arch-depenedent would be a really bad idea).
23391da177e4SLinus Torvalds  */
2340b3bdda02SChristoph Lameter void vfree(const void *addr)
23411da177e4SLinus Torvalds {
234232fcfd40SAl Viro 	BUG_ON(in_nmi());
234389219d37SCatalin Marinas 
234489219d37SCatalin Marinas 	kmemleak_free(addr);
234589219d37SCatalin Marinas 
2346a8dda165SAndrey Ryabinin 	might_sleep_if(!in_interrupt());
2347a8dda165SAndrey Ryabinin 
234832fcfd40SAl Viro 	if (!addr)
234932fcfd40SAl Viro 		return;
2350c67dc624SRoman Penyaev 
2351c67dc624SRoman Penyaev 	__vfree(addr);
23521da177e4SLinus Torvalds }
23531da177e4SLinus Torvalds EXPORT_SYMBOL(vfree);
23541da177e4SLinus Torvalds 
23551da177e4SLinus Torvalds /**
23561da177e4SLinus Torvalds  * vunmap - release virtual mapping obtained by vmap()
23571da177e4SLinus Torvalds  * @addr:   memory base address
23581da177e4SLinus Torvalds  *
23591da177e4SLinus Torvalds  * Free the virtually contiguous memory area starting at @addr,
23601da177e4SLinus Torvalds  * which was created from the page array passed to vmap().
23611da177e4SLinus Torvalds  *
236280e93effSPekka Enberg  * Must not be called in interrupt context.
23631da177e4SLinus Torvalds  */
2364b3bdda02SChristoph Lameter void vunmap(const void *addr)
23651da177e4SLinus Torvalds {
23661da177e4SLinus Torvalds 	BUG_ON(in_interrupt());
236734754b69SPeter Zijlstra 	might_sleep();
236832fcfd40SAl Viro 	if (addr)
23691da177e4SLinus Torvalds 		__vunmap(addr, 0);
23701da177e4SLinus Torvalds }
23711da177e4SLinus Torvalds EXPORT_SYMBOL(vunmap);
23721da177e4SLinus Torvalds 
23731da177e4SLinus Torvalds /**
23741da177e4SLinus Torvalds  * vmap - map an array of pages into virtually contiguous space
23751da177e4SLinus Torvalds  * @pages: array of page pointers
23761da177e4SLinus Torvalds  * @count: number of pages to map
23771da177e4SLinus Torvalds  * @flags: vm_area->flags
23781da177e4SLinus Torvalds  * @prot: page protection for the mapping
23791da177e4SLinus Torvalds  *
2380b944afc9SChristoph Hellwig  * Maps @count pages from @pages into contiguous kernel virtual space.
2381b944afc9SChristoph Hellwig  * If @flags contains %VM_MAP_PUT_PAGES the ownership of the pages array itself
2382b944afc9SChristoph Hellwig  * (which must be kmalloc or vmalloc memory) and one reference per pages in it
2383b944afc9SChristoph Hellwig  * are transferred from the caller to vmap(), and will be freed / dropped when
2384b944afc9SChristoph Hellwig  * vfree() is called on the return value.
2385a862f68aSMike Rapoport  *
2386a862f68aSMike Rapoport  * Return: the address of the area or %NULL on failure
23871da177e4SLinus Torvalds  */
23881da177e4SLinus Torvalds void *vmap(struct page **pages, unsigned int count,
23891da177e4SLinus Torvalds 	   unsigned long flags, pgprot_t prot)
23901da177e4SLinus Torvalds {
23911da177e4SLinus Torvalds 	struct vm_struct *area;
239265ee03c4SGuillermo Julián Moreno 	unsigned long size;		/* In bytes */
23931da177e4SLinus Torvalds 
239434754b69SPeter Zijlstra 	might_sleep();
239534754b69SPeter Zijlstra 
2396ca79b0c2SArun KS 	if (count > totalram_pages())
23971da177e4SLinus Torvalds 		return NULL;
23981da177e4SLinus Torvalds 
239965ee03c4SGuillermo Julián Moreno 	size = (unsigned long)count << PAGE_SHIFT;
240065ee03c4SGuillermo Julián Moreno 	area = get_vm_area_caller(size, flags, __builtin_return_address(0));
24011da177e4SLinus Torvalds 	if (!area)
24021da177e4SLinus Torvalds 		return NULL;
240323016969SChristoph Lameter 
2404cca98e9fSChristoph Hellwig 	if (map_kernel_range((unsigned long)area->addr, size, pgprot_nx(prot),
2405ed1f324cSChristoph Hellwig 			pages) < 0) {
24061da177e4SLinus Torvalds 		vunmap(area->addr);
24071da177e4SLinus Torvalds 		return NULL;
24081da177e4SLinus Torvalds 	}
24091da177e4SLinus Torvalds 
2410b944afc9SChristoph Hellwig 	if (flags & VM_MAP_PUT_PAGES)
2411b944afc9SChristoph Hellwig 		area->pages = pages;
24121da177e4SLinus Torvalds 	return area->addr;
24131da177e4SLinus Torvalds }
24141da177e4SLinus Torvalds EXPORT_SYMBOL(vmap);
24151da177e4SLinus Torvalds 
2416*3e9a9e25SChristoph Hellwig #ifdef CONFIG_VMAP_PFN
2417*3e9a9e25SChristoph Hellwig struct vmap_pfn_data {
2418*3e9a9e25SChristoph Hellwig 	unsigned long	*pfns;
2419*3e9a9e25SChristoph Hellwig 	pgprot_t	prot;
2420*3e9a9e25SChristoph Hellwig 	unsigned int	idx;
2421*3e9a9e25SChristoph Hellwig };
2422*3e9a9e25SChristoph Hellwig 
2423*3e9a9e25SChristoph Hellwig static int vmap_pfn_apply(pte_t *pte, unsigned long addr, void *private)
2424*3e9a9e25SChristoph Hellwig {
2425*3e9a9e25SChristoph Hellwig 	struct vmap_pfn_data *data = private;
2426*3e9a9e25SChristoph Hellwig 
2427*3e9a9e25SChristoph Hellwig 	if (WARN_ON_ONCE(pfn_valid(data->pfns[data->idx])))
2428*3e9a9e25SChristoph Hellwig 		return -EINVAL;
2429*3e9a9e25SChristoph Hellwig 	*pte = pte_mkspecial(pfn_pte(data->pfns[data->idx++], data->prot));
2430*3e9a9e25SChristoph Hellwig 	return 0;
2431*3e9a9e25SChristoph Hellwig }
2432*3e9a9e25SChristoph Hellwig 
2433*3e9a9e25SChristoph Hellwig /**
2434*3e9a9e25SChristoph Hellwig  * vmap_pfn - map an array of PFNs into virtually contiguous space
2435*3e9a9e25SChristoph Hellwig  * @pfns: array of PFNs
2436*3e9a9e25SChristoph Hellwig  * @count: number of pages to map
2437*3e9a9e25SChristoph Hellwig  * @prot: page protection for the mapping
2438*3e9a9e25SChristoph Hellwig  *
2439*3e9a9e25SChristoph Hellwig  * Maps @count PFNs from @pfns into contiguous kernel virtual space and returns
2440*3e9a9e25SChristoph Hellwig  * the start address of the mapping.
2441*3e9a9e25SChristoph Hellwig  */
2442*3e9a9e25SChristoph Hellwig void *vmap_pfn(unsigned long *pfns, unsigned int count, pgprot_t prot)
2443*3e9a9e25SChristoph Hellwig {
2444*3e9a9e25SChristoph Hellwig 	struct vmap_pfn_data data = { .pfns = pfns, .prot = pgprot_nx(prot) };
2445*3e9a9e25SChristoph Hellwig 	struct vm_struct *area;
2446*3e9a9e25SChristoph Hellwig 
2447*3e9a9e25SChristoph Hellwig 	area = get_vm_area_caller(count * PAGE_SIZE, VM_IOREMAP,
2448*3e9a9e25SChristoph Hellwig 			__builtin_return_address(0));
2449*3e9a9e25SChristoph Hellwig 	if (!area)
2450*3e9a9e25SChristoph Hellwig 		return NULL;
2451*3e9a9e25SChristoph Hellwig 	if (apply_to_page_range(&init_mm, (unsigned long)area->addr,
2452*3e9a9e25SChristoph Hellwig 			count * PAGE_SIZE, vmap_pfn_apply, &data)) {
2453*3e9a9e25SChristoph Hellwig 		free_vm_area(area);
2454*3e9a9e25SChristoph Hellwig 		return NULL;
2455*3e9a9e25SChristoph Hellwig 	}
2456*3e9a9e25SChristoph Hellwig 	return area->addr;
2457*3e9a9e25SChristoph Hellwig }
2458*3e9a9e25SChristoph Hellwig EXPORT_SYMBOL_GPL(vmap_pfn);
2459*3e9a9e25SChristoph Hellwig #endif /* CONFIG_VMAP_PFN */
2460*3e9a9e25SChristoph Hellwig 
2461e31d9eb5SAdrian Bunk static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask,
24623722e13cSWanpeng Li 				 pgprot_t prot, int node)
24631da177e4SLinus Torvalds {
24641da177e4SLinus Torvalds 	struct page **pages;
24651da177e4SLinus Torvalds 	unsigned int nr_pages, array_size, i;
2466930f036bSDavid Rientjes 	const gfp_t nested_gfp = (gfp_mask & GFP_RECLAIM_MASK) | __GFP_ZERO;
2467704b862fSLaura Abbott 	const gfp_t alloc_mask = gfp_mask | __GFP_NOWARN;
2468704b862fSLaura Abbott 	const gfp_t highmem_mask = (gfp_mask & (GFP_DMA | GFP_DMA32)) ?
2469704b862fSLaura Abbott 					0 :
2470704b862fSLaura Abbott 					__GFP_HIGHMEM;
24711da177e4SLinus Torvalds 
2472762216abSWanpeng Li 	nr_pages = get_vm_area_size(area) >> PAGE_SHIFT;
24731da177e4SLinus Torvalds 	array_size = (nr_pages * sizeof(struct page *));
24741da177e4SLinus Torvalds 
24751da177e4SLinus Torvalds 	/* Please note that the recursion is strictly bounded. */
24768757d5faSJan Kiszka 	if (array_size > PAGE_SIZE) {
2477704b862fSLaura Abbott 		pages = __vmalloc_node(array_size, 1, nested_gfp|highmem_mask,
2478f38fcb9cSChristoph Hellwig 				node, area->caller);
2479286e1ea3SAndrew Morton 	} else {
2480976d6dfbSJan Beulich 		pages = kmalloc_node(array_size, nested_gfp, node);
2481286e1ea3SAndrew Morton 	}
24827ea36242SAustin Kim 
24837ea36242SAustin Kim 	if (!pages) {
24841da177e4SLinus Torvalds 		remove_vm_area(area->addr);
24851da177e4SLinus Torvalds 		kfree(area);
24861da177e4SLinus Torvalds 		return NULL;
24871da177e4SLinus Torvalds 	}
24881da177e4SLinus Torvalds 
24897ea36242SAustin Kim 	area->pages = pages;
24907ea36242SAustin Kim 	area->nr_pages = nr_pages;
24917ea36242SAustin Kim 
24921da177e4SLinus Torvalds 	for (i = 0; i < area->nr_pages; i++) {
2493bf53d6f8SChristoph Lameter 		struct page *page;
2494bf53d6f8SChristoph Lameter 
24954b90951cSJianguo Wu 		if (node == NUMA_NO_NODE)
2496704b862fSLaura Abbott 			page = alloc_page(alloc_mask|highmem_mask);
2497930fc45aSChristoph Lameter 		else
2498704b862fSLaura Abbott 			page = alloc_pages_node(node, alloc_mask|highmem_mask, 0);
2499bf53d6f8SChristoph Lameter 
2500bf53d6f8SChristoph Lameter 		if (unlikely(!page)) {
250182afbc32SHui Su 			/* Successfully allocated i pages, free them in __vfree() */
25021da177e4SLinus Torvalds 			area->nr_pages = i;
250397105f0aSRoman Gushchin 			atomic_long_add(area->nr_pages, &nr_vmalloc_pages);
25041da177e4SLinus Torvalds 			goto fail;
25051da177e4SLinus Torvalds 		}
2506bf53d6f8SChristoph Lameter 		area->pages[i] = page;
2507dcf61ff0SLiu Xiang 		if (gfpflags_allow_blocking(gfp_mask))
2508660654f9SEric Dumazet 			cond_resched();
25091da177e4SLinus Torvalds 	}
251097105f0aSRoman Gushchin 	atomic_long_add(area->nr_pages, &nr_vmalloc_pages);
25111da177e4SLinus Torvalds 
2512ed1f324cSChristoph Hellwig 	if (map_kernel_range((unsigned long)area->addr, get_vm_area_size(area),
2513ed1f324cSChristoph Hellwig 			prot, pages) < 0)
25141da177e4SLinus Torvalds 		goto fail;
2515ed1f324cSChristoph Hellwig 
25161da177e4SLinus Torvalds 	return area->addr;
25171da177e4SLinus Torvalds 
25181da177e4SLinus Torvalds fail:
2519a8e99259SMichal Hocko 	warn_alloc(gfp_mask, NULL,
25207877cdccSMichal Hocko 			  "vmalloc: allocation failure, allocated %ld of %ld bytes",
252122943ab1SDave Hansen 			  (area->nr_pages*PAGE_SIZE), area->size);
2522c67dc624SRoman Penyaev 	__vfree(area->addr);
25231da177e4SLinus Torvalds 	return NULL;
25241da177e4SLinus Torvalds }
25251da177e4SLinus Torvalds 
2526d0a21265SDavid Rientjes /**
2527d0a21265SDavid Rientjes  * __vmalloc_node_range - allocate virtually contiguous memory
2528d0a21265SDavid Rientjes  * @size:		  allocation size
2529d0a21265SDavid Rientjes  * @align:		  desired alignment
2530d0a21265SDavid Rientjes  * @start:		  vm area range start
2531d0a21265SDavid Rientjes  * @end:		  vm area range end
2532d0a21265SDavid Rientjes  * @gfp_mask:		  flags for the page level allocator
2533d0a21265SDavid Rientjes  * @prot:		  protection mask for the allocated pages
2534cb9e3c29SAndrey Ryabinin  * @vm_flags:		  additional vm area flags (e.g. %VM_NO_GUARD)
253500ef2d2fSDavid Rientjes  * @node:		  node to use for allocation or NUMA_NO_NODE
2536d0a21265SDavid Rientjes  * @caller:		  caller's return address
2537d0a21265SDavid Rientjes  *
2538d0a21265SDavid Rientjes  * Allocate enough pages to cover @size from the page level
2539d0a21265SDavid Rientjes  * allocator with @gfp_mask flags.  Map them into contiguous
2540d0a21265SDavid Rientjes  * kernel virtual space, using a pagetable protection of @prot.
2541a862f68aSMike Rapoport  *
2542a862f68aSMike Rapoport  * Return: the address of the area or %NULL on failure
2543d0a21265SDavid Rientjes  */
2544d0a21265SDavid Rientjes void *__vmalloc_node_range(unsigned long size, unsigned long align,
2545d0a21265SDavid Rientjes 			unsigned long start, unsigned long end, gfp_t gfp_mask,
2546cb9e3c29SAndrey Ryabinin 			pgprot_t prot, unsigned long vm_flags, int node,
2547cb9e3c29SAndrey Ryabinin 			const void *caller)
2548930fc45aSChristoph Lameter {
2549d0a21265SDavid Rientjes 	struct vm_struct *area;
2550d0a21265SDavid Rientjes 	void *addr;
2551d0a21265SDavid Rientjes 	unsigned long real_size = size;
2552d0a21265SDavid Rientjes 
2553d0a21265SDavid Rientjes 	size = PAGE_ALIGN(size);
2554ca79b0c2SArun KS 	if (!size || (size >> PAGE_SHIFT) > totalram_pages())
2555de7d2b56SJoe Perches 		goto fail;
2556d0a21265SDavid Rientjes 
2557d98c9e83SAndrey Ryabinin 	area = __get_vm_area_node(real_size, align, VM_ALLOC | VM_UNINITIALIZED |
2558cb9e3c29SAndrey Ryabinin 				vm_flags, start, end, node, gfp_mask, caller);
2559d0a21265SDavid Rientjes 	if (!area)
2560de7d2b56SJoe Perches 		goto fail;
2561d0a21265SDavid Rientjes 
25623722e13cSWanpeng Li 	addr = __vmalloc_area_node(area, gfp_mask, prot, node);
25631368edf0SMel Gorman 	if (!addr)
2564b82225f3SWanpeng Li 		return NULL;
256589219d37SCatalin Marinas 
256689219d37SCatalin Marinas 	/*
256720fc02b4SZhang Yanfei 	 * In this function, newly allocated vm_struct has VM_UNINITIALIZED
256820fc02b4SZhang Yanfei 	 * flag. It means that vm_struct is not fully initialized.
25694341fa45SJoonsoo Kim 	 * Now, it is fully initialized, so remove this flag here.
2570f5252e00SMitsuo Hayasaka 	 */
257120fc02b4SZhang Yanfei 	clear_vm_uninitialized_flag(area);
2572f5252e00SMitsuo Hayasaka 
257394f4a161SCatalin Marinas 	kmemleak_vmalloc(area, size, gfp_mask);
257489219d37SCatalin Marinas 
257589219d37SCatalin Marinas 	return addr;
2576de7d2b56SJoe Perches 
2577de7d2b56SJoe Perches fail:
2578a8e99259SMichal Hocko 	warn_alloc(gfp_mask, NULL,
25797877cdccSMichal Hocko 			  "vmalloc: allocation failure: %lu bytes", real_size);
2580de7d2b56SJoe Perches 	return NULL;
2581930fc45aSChristoph Lameter }
2582930fc45aSChristoph Lameter 
25831da177e4SLinus Torvalds /**
2584930fc45aSChristoph Lameter  * __vmalloc_node - allocate virtually contiguous memory
25851da177e4SLinus Torvalds  * @size:	    allocation size
25862dca6999SDavid Miller  * @align:	    desired alignment
25871da177e4SLinus Torvalds  * @gfp_mask:	    flags for the page level allocator
258800ef2d2fSDavid Rientjes  * @node:	    node to use for allocation or NUMA_NO_NODE
2589c85d194bSRandy Dunlap  * @caller:	    caller's return address
25901da177e4SLinus Torvalds  *
2591f38fcb9cSChristoph Hellwig  * Allocate enough pages to cover @size from the page level allocator with
2592f38fcb9cSChristoph Hellwig  * @gfp_mask flags.  Map them into contiguous kernel virtual space.
2593a7c3e901SMichal Hocko  *
2594dcda9b04SMichal Hocko  * Reclaim modifiers in @gfp_mask - __GFP_NORETRY, __GFP_RETRY_MAYFAIL
2595a7c3e901SMichal Hocko  * and __GFP_NOFAIL are not supported
2596a7c3e901SMichal Hocko  *
2597a7c3e901SMichal Hocko  * Any use of gfp flags outside of GFP_KERNEL should be consulted
2598a7c3e901SMichal Hocko  * with mm people.
2599a862f68aSMike Rapoport  *
2600a862f68aSMike Rapoport  * Return: pointer to the allocated memory or %NULL on error
26011da177e4SLinus Torvalds  */
26022b905948SChristoph Hellwig void *__vmalloc_node(unsigned long size, unsigned long align,
2603f38fcb9cSChristoph Hellwig 			    gfp_t gfp_mask, int node, const void *caller)
26041da177e4SLinus Torvalds {
2605d0a21265SDavid Rientjes 	return __vmalloc_node_range(size, align, VMALLOC_START, VMALLOC_END,
2606f38fcb9cSChristoph Hellwig 				gfp_mask, PAGE_KERNEL, 0, node, caller);
26071da177e4SLinus Torvalds }
2608c3f896dcSChristoph Hellwig /*
2609c3f896dcSChristoph Hellwig  * This is only for performance analysis of vmalloc and stress purpose.
2610c3f896dcSChristoph Hellwig  * It is required by vmalloc test module, therefore do not use it other
2611c3f896dcSChristoph Hellwig  * than that.
2612c3f896dcSChristoph Hellwig  */
2613c3f896dcSChristoph Hellwig #ifdef CONFIG_TEST_VMALLOC_MODULE
2614c3f896dcSChristoph Hellwig EXPORT_SYMBOL_GPL(__vmalloc_node);
2615c3f896dcSChristoph Hellwig #endif
26161da177e4SLinus Torvalds 
261788dca4caSChristoph Hellwig void *__vmalloc(unsigned long size, gfp_t gfp_mask)
2618930fc45aSChristoph Lameter {
2619f38fcb9cSChristoph Hellwig 	return __vmalloc_node(size, 1, gfp_mask, NUMA_NO_NODE,
262023016969SChristoph Lameter 				__builtin_return_address(0));
2621930fc45aSChristoph Lameter }
26221da177e4SLinus Torvalds EXPORT_SYMBOL(__vmalloc);
26231da177e4SLinus Torvalds 
26241da177e4SLinus Torvalds /**
26251da177e4SLinus Torvalds  * vmalloc - allocate virtually contiguous memory
26261da177e4SLinus Torvalds  * @size:    allocation size
262792eac168SMike Rapoport  *
26281da177e4SLinus Torvalds  * Allocate enough pages to cover @size from the page level
26291da177e4SLinus Torvalds  * allocator and map them into contiguous kernel virtual space.
26301da177e4SLinus Torvalds  *
2631c1c8897fSMichael Opdenacker  * For tight control over page level allocator and protection flags
26321da177e4SLinus Torvalds  * use __vmalloc() instead.
2633a862f68aSMike Rapoport  *
2634a862f68aSMike Rapoport  * Return: pointer to the allocated memory or %NULL on error
26351da177e4SLinus Torvalds  */
26361da177e4SLinus Torvalds void *vmalloc(unsigned long size)
26371da177e4SLinus Torvalds {
26384d39d728SChristoph Hellwig 	return __vmalloc_node(size, 1, GFP_KERNEL, NUMA_NO_NODE,
26394d39d728SChristoph Hellwig 				__builtin_return_address(0));
26401da177e4SLinus Torvalds }
26411da177e4SLinus Torvalds EXPORT_SYMBOL(vmalloc);
26421da177e4SLinus Torvalds 
2643930fc45aSChristoph Lameter /**
2644e1ca7788SDave Young  * vzalloc - allocate virtually contiguous memory with zero fill
2645e1ca7788SDave Young  * @size:    allocation size
264692eac168SMike Rapoport  *
2647e1ca7788SDave Young  * Allocate enough pages to cover @size from the page level
2648e1ca7788SDave Young  * allocator and map them into contiguous kernel virtual space.
2649e1ca7788SDave Young  * The memory allocated is set to zero.
2650e1ca7788SDave Young  *
2651e1ca7788SDave Young  * For tight control over page level allocator and protection flags
2652e1ca7788SDave Young  * use __vmalloc() instead.
2653a862f68aSMike Rapoport  *
2654a862f68aSMike Rapoport  * Return: pointer to the allocated memory or %NULL on error
2655e1ca7788SDave Young  */
2656e1ca7788SDave Young void *vzalloc(unsigned long size)
2657e1ca7788SDave Young {
26584d39d728SChristoph Hellwig 	return __vmalloc_node(size, 1, GFP_KERNEL | __GFP_ZERO, NUMA_NO_NODE,
26594d39d728SChristoph Hellwig 				__builtin_return_address(0));
2660e1ca7788SDave Young }
2661e1ca7788SDave Young EXPORT_SYMBOL(vzalloc);
2662e1ca7788SDave Young 
2663e1ca7788SDave Young /**
2664ead04089SRolf Eike Beer  * vmalloc_user - allocate zeroed virtually contiguous memory for userspace
266583342314SNick Piggin  * @size: allocation size
2666ead04089SRolf Eike Beer  *
2667ead04089SRolf Eike Beer  * The resulting memory area is zeroed so it can be mapped to userspace
2668ead04089SRolf Eike Beer  * without leaking data.
2669a862f68aSMike Rapoport  *
2670a862f68aSMike Rapoport  * Return: pointer to the allocated memory or %NULL on error
267183342314SNick Piggin  */
267283342314SNick Piggin void *vmalloc_user(unsigned long size)
267383342314SNick Piggin {
2674bc84c535SRoman Penyaev 	return __vmalloc_node_range(size, SHMLBA,  VMALLOC_START, VMALLOC_END,
2675bc84c535SRoman Penyaev 				    GFP_KERNEL | __GFP_ZERO, PAGE_KERNEL,
2676bc84c535SRoman Penyaev 				    VM_USERMAP, NUMA_NO_NODE,
267700ef2d2fSDavid Rientjes 				    __builtin_return_address(0));
267883342314SNick Piggin }
267983342314SNick Piggin EXPORT_SYMBOL(vmalloc_user);
268083342314SNick Piggin 
268183342314SNick Piggin /**
2682930fc45aSChristoph Lameter  * vmalloc_node - allocate memory on a specific node
2683930fc45aSChristoph Lameter  * @size:	  allocation size
2684d44e0780SRandy Dunlap  * @node:	  numa node
2685930fc45aSChristoph Lameter  *
2686930fc45aSChristoph Lameter  * Allocate enough pages to cover @size from the page level
2687930fc45aSChristoph Lameter  * allocator and map them into contiguous kernel virtual space.
2688930fc45aSChristoph Lameter  *
2689c1c8897fSMichael Opdenacker  * For tight control over page level allocator and protection flags
2690930fc45aSChristoph Lameter  * use __vmalloc() instead.
2691a862f68aSMike Rapoport  *
2692a862f68aSMike Rapoport  * Return: pointer to the allocated memory or %NULL on error
2693930fc45aSChristoph Lameter  */
2694930fc45aSChristoph Lameter void *vmalloc_node(unsigned long size, int node)
2695930fc45aSChristoph Lameter {
2696f38fcb9cSChristoph Hellwig 	return __vmalloc_node(size, 1, GFP_KERNEL, node,
2697f38fcb9cSChristoph Hellwig 			__builtin_return_address(0));
2698930fc45aSChristoph Lameter }
2699930fc45aSChristoph Lameter EXPORT_SYMBOL(vmalloc_node);
2700930fc45aSChristoph Lameter 
2701e1ca7788SDave Young /**
2702e1ca7788SDave Young  * vzalloc_node - allocate memory on a specific node with zero fill
2703e1ca7788SDave Young  * @size:	allocation size
2704e1ca7788SDave Young  * @node:	numa node
2705e1ca7788SDave Young  *
2706e1ca7788SDave Young  * Allocate enough pages to cover @size from the page level
2707e1ca7788SDave Young  * allocator and map them into contiguous kernel virtual space.
2708e1ca7788SDave Young  * The memory allocated is set to zero.
2709e1ca7788SDave Young  *
2710a862f68aSMike Rapoport  * Return: pointer to the allocated memory or %NULL on error
2711e1ca7788SDave Young  */
2712e1ca7788SDave Young void *vzalloc_node(unsigned long size, int node)
2713e1ca7788SDave Young {
27144d39d728SChristoph Hellwig 	return __vmalloc_node(size, 1, GFP_KERNEL | __GFP_ZERO, node,
27154d39d728SChristoph Hellwig 				__builtin_return_address(0));
2716e1ca7788SDave Young }
2717e1ca7788SDave Young EXPORT_SYMBOL(vzalloc_node);
2718e1ca7788SDave Young 
27190d08e0d3SAndi Kleen #if defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA32)
2720698d0831SMichal Hocko #define GFP_VMALLOC32 (GFP_DMA32 | GFP_KERNEL)
27210d08e0d3SAndi Kleen #elif defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA)
2722698d0831SMichal Hocko #define GFP_VMALLOC32 (GFP_DMA | GFP_KERNEL)
27230d08e0d3SAndi Kleen #else
2724698d0831SMichal Hocko /*
2725698d0831SMichal Hocko  * 64b systems should always have either DMA or DMA32 zones. For others
2726698d0831SMichal Hocko  * GFP_DMA32 should do the right thing and use the normal zone.
2727698d0831SMichal Hocko  */
2728698d0831SMichal Hocko #define GFP_VMALLOC32 GFP_DMA32 | GFP_KERNEL
27290d08e0d3SAndi Kleen #endif
27300d08e0d3SAndi Kleen 
27311da177e4SLinus Torvalds /**
27321da177e4SLinus Torvalds  * vmalloc_32 - allocate virtually contiguous memory (32bit addressable)
27331da177e4SLinus Torvalds  * @size:	allocation size
27341da177e4SLinus Torvalds  *
27351da177e4SLinus Torvalds  * Allocate enough 32bit PA addressable pages to cover @size from the
27361da177e4SLinus Torvalds  * page level allocator and map them into contiguous kernel virtual space.
2737a862f68aSMike Rapoport  *
2738a862f68aSMike Rapoport  * Return: pointer to the allocated memory or %NULL on error
27391da177e4SLinus Torvalds  */
27401da177e4SLinus Torvalds void *vmalloc_32(unsigned long size)
27411da177e4SLinus Torvalds {
2742f38fcb9cSChristoph Hellwig 	return __vmalloc_node(size, 1, GFP_VMALLOC32, NUMA_NO_NODE,
2743f38fcb9cSChristoph Hellwig 			__builtin_return_address(0));
27441da177e4SLinus Torvalds }
27451da177e4SLinus Torvalds EXPORT_SYMBOL(vmalloc_32);
27461da177e4SLinus Torvalds 
274783342314SNick Piggin /**
2748ead04089SRolf Eike Beer  * vmalloc_32_user - allocate zeroed virtually contiguous 32bit memory
274983342314SNick Piggin  * @size:	     allocation size
2750ead04089SRolf Eike Beer  *
2751ead04089SRolf Eike Beer  * The resulting memory area is 32bit addressable and zeroed so it can be
2752ead04089SRolf Eike Beer  * mapped to userspace without leaking data.
2753a862f68aSMike Rapoport  *
2754a862f68aSMike Rapoport  * Return: pointer to the allocated memory or %NULL on error
275583342314SNick Piggin  */
275683342314SNick Piggin void *vmalloc_32_user(unsigned long size)
275783342314SNick Piggin {
2758bc84c535SRoman Penyaev 	return __vmalloc_node_range(size, SHMLBA,  VMALLOC_START, VMALLOC_END,
2759bc84c535SRoman Penyaev 				    GFP_VMALLOC32 | __GFP_ZERO, PAGE_KERNEL,
2760bc84c535SRoman Penyaev 				    VM_USERMAP, NUMA_NO_NODE,
27615a82ac71SRoman Penyaev 				    __builtin_return_address(0));
276283342314SNick Piggin }
276383342314SNick Piggin EXPORT_SYMBOL(vmalloc_32_user);
276483342314SNick Piggin 
2765d0107eb0SKAMEZAWA Hiroyuki /*
2766d0107eb0SKAMEZAWA Hiroyuki  * small helper routine , copy contents to buf from addr.
2767d0107eb0SKAMEZAWA Hiroyuki  * If the page is not present, fill zero.
2768d0107eb0SKAMEZAWA Hiroyuki  */
2769d0107eb0SKAMEZAWA Hiroyuki 
2770d0107eb0SKAMEZAWA Hiroyuki static int aligned_vread(char *buf, char *addr, unsigned long count)
2771d0107eb0SKAMEZAWA Hiroyuki {
2772d0107eb0SKAMEZAWA Hiroyuki 	struct page *p;
2773d0107eb0SKAMEZAWA Hiroyuki 	int copied = 0;
2774d0107eb0SKAMEZAWA Hiroyuki 
2775d0107eb0SKAMEZAWA Hiroyuki 	while (count) {
2776d0107eb0SKAMEZAWA Hiroyuki 		unsigned long offset, length;
2777d0107eb0SKAMEZAWA Hiroyuki 
2778891c49abSAlexander Kuleshov 		offset = offset_in_page(addr);
2779d0107eb0SKAMEZAWA Hiroyuki 		length = PAGE_SIZE - offset;
2780d0107eb0SKAMEZAWA Hiroyuki 		if (length > count)
2781d0107eb0SKAMEZAWA Hiroyuki 			length = count;
2782d0107eb0SKAMEZAWA Hiroyuki 		p = vmalloc_to_page(addr);
2783d0107eb0SKAMEZAWA Hiroyuki 		/*
2784d0107eb0SKAMEZAWA Hiroyuki 		 * To do safe access to this _mapped_ area, we need
2785d0107eb0SKAMEZAWA Hiroyuki 		 * lock. But adding lock here means that we need to add
2786d0107eb0SKAMEZAWA Hiroyuki 		 * overhead of vmalloc()/vfree() calles for this _debug_
2787d0107eb0SKAMEZAWA Hiroyuki 		 * interface, rarely used. Instead of that, we'll use
2788d0107eb0SKAMEZAWA Hiroyuki 		 * kmap() and get small overhead in this access function.
2789d0107eb0SKAMEZAWA Hiroyuki 		 */
2790d0107eb0SKAMEZAWA Hiroyuki 		if (p) {
2791d0107eb0SKAMEZAWA Hiroyuki 			/*
2792d0107eb0SKAMEZAWA Hiroyuki 			 * we can expect USER0 is not used (see vread/vwrite's
2793d0107eb0SKAMEZAWA Hiroyuki 			 * function description)
2794d0107eb0SKAMEZAWA Hiroyuki 			 */
27959b04c5feSCong Wang 			void *map = kmap_atomic(p);
2796d0107eb0SKAMEZAWA Hiroyuki 			memcpy(buf, map + offset, length);
27979b04c5feSCong Wang 			kunmap_atomic(map);
2798d0107eb0SKAMEZAWA Hiroyuki 		} else
2799d0107eb0SKAMEZAWA Hiroyuki 			memset(buf, 0, length);
2800d0107eb0SKAMEZAWA Hiroyuki 
2801d0107eb0SKAMEZAWA Hiroyuki 		addr += length;
2802d0107eb0SKAMEZAWA Hiroyuki 		buf += length;
2803d0107eb0SKAMEZAWA Hiroyuki 		copied += length;
2804d0107eb0SKAMEZAWA Hiroyuki 		count -= length;
2805d0107eb0SKAMEZAWA Hiroyuki 	}
2806d0107eb0SKAMEZAWA Hiroyuki 	return copied;
2807d0107eb0SKAMEZAWA Hiroyuki }
2808d0107eb0SKAMEZAWA Hiroyuki 
2809d0107eb0SKAMEZAWA Hiroyuki static int aligned_vwrite(char *buf, char *addr, unsigned long count)
2810d0107eb0SKAMEZAWA Hiroyuki {
2811d0107eb0SKAMEZAWA Hiroyuki 	struct page *p;
2812d0107eb0SKAMEZAWA Hiroyuki 	int copied = 0;
2813d0107eb0SKAMEZAWA Hiroyuki 
2814d0107eb0SKAMEZAWA Hiroyuki 	while (count) {
2815d0107eb0SKAMEZAWA Hiroyuki 		unsigned long offset, length;
2816d0107eb0SKAMEZAWA Hiroyuki 
2817891c49abSAlexander Kuleshov 		offset = offset_in_page(addr);
2818d0107eb0SKAMEZAWA Hiroyuki 		length = PAGE_SIZE - offset;
2819d0107eb0SKAMEZAWA Hiroyuki 		if (length > count)
2820d0107eb0SKAMEZAWA Hiroyuki 			length = count;
2821d0107eb0SKAMEZAWA Hiroyuki 		p = vmalloc_to_page(addr);
2822d0107eb0SKAMEZAWA Hiroyuki 		/*
2823d0107eb0SKAMEZAWA Hiroyuki 		 * To do safe access to this _mapped_ area, we need
2824d0107eb0SKAMEZAWA Hiroyuki 		 * lock. But adding lock here means that we need to add
2825d0107eb0SKAMEZAWA Hiroyuki 		 * overhead of vmalloc()/vfree() calles for this _debug_
2826d0107eb0SKAMEZAWA Hiroyuki 		 * interface, rarely used. Instead of that, we'll use
2827d0107eb0SKAMEZAWA Hiroyuki 		 * kmap() and get small overhead in this access function.
2828d0107eb0SKAMEZAWA Hiroyuki 		 */
2829d0107eb0SKAMEZAWA Hiroyuki 		if (p) {
2830d0107eb0SKAMEZAWA Hiroyuki 			/*
2831d0107eb0SKAMEZAWA Hiroyuki 			 * we can expect USER0 is not used (see vread/vwrite's
2832d0107eb0SKAMEZAWA Hiroyuki 			 * function description)
2833d0107eb0SKAMEZAWA Hiroyuki 			 */
28349b04c5feSCong Wang 			void *map = kmap_atomic(p);
2835d0107eb0SKAMEZAWA Hiroyuki 			memcpy(map + offset, buf, length);
28369b04c5feSCong Wang 			kunmap_atomic(map);
2837d0107eb0SKAMEZAWA Hiroyuki 		}
2838d0107eb0SKAMEZAWA Hiroyuki 		addr += length;
2839d0107eb0SKAMEZAWA Hiroyuki 		buf += length;
2840d0107eb0SKAMEZAWA Hiroyuki 		copied += length;
2841d0107eb0SKAMEZAWA Hiroyuki 		count -= length;
2842d0107eb0SKAMEZAWA Hiroyuki 	}
2843d0107eb0SKAMEZAWA Hiroyuki 	return copied;
2844d0107eb0SKAMEZAWA Hiroyuki }
2845d0107eb0SKAMEZAWA Hiroyuki 
2846d0107eb0SKAMEZAWA Hiroyuki /**
2847d0107eb0SKAMEZAWA Hiroyuki  * vread() - read vmalloc area in a safe way.
2848d0107eb0SKAMEZAWA Hiroyuki  * @buf:     buffer for reading data
2849d0107eb0SKAMEZAWA Hiroyuki  * @addr:    vm address.
2850d0107eb0SKAMEZAWA Hiroyuki  * @count:   number of bytes to be read.
2851d0107eb0SKAMEZAWA Hiroyuki  *
2852d0107eb0SKAMEZAWA Hiroyuki  * This function checks that addr is a valid vmalloc'ed area, and
2853d0107eb0SKAMEZAWA Hiroyuki  * copy data from that area to a given buffer. If the given memory range
2854d0107eb0SKAMEZAWA Hiroyuki  * of [addr...addr+count) includes some valid address, data is copied to
2855d0107eb0SKAMEZAWA Hiroyuki  * proper area of @buf. If there are memory holes, they'll be zero-filled.
2856d0107eb0SKAMEZAWA Hiroyuki  * IOREMAP area is treated as memory hole and no copy is done.
2857d0107eb0SKAMEZAWA Hiroyuki  *
2858d0107eb0SKAMEZAWA Hiroyuki  * If [addr...addr+count) doesn't includes any intersects with alive
2859a8e5202dSCong Wang  * vm_struct area, returns 0. @buf should be kernel's buffer.
2860d0107eb0SKAMEZAWA Hiroyuki  *
2861d0107eb0SKAMEZAWA Hiroyuki  * Note: In usual ops, vread() is never necessary because the caller
2862d0107eb0SKAMEZAWA Hiroyuki  * should know vmalloc() area is valid and can use memcpy().
2863d0107eb0SKAMEZAWA Hiroyuki  * This is for routines which have to access vmalloc area without
2864d9009d67SGeert Uytterhoeven  * any information, as /dev/kmem.
2865a862f68aSMike Rapoport  *
2866a862f68aSMike Rapoport  * Return: number of bytes for which addr and buf should be increased
2867a862f68aSMike Rapoport  * (same number as @count) or %0 if [addr...addr+count) doesn't
2868a862f68aSMike Rapoport  * include any intersection with valid vmalloc area
2869d0107eb0SKAMEZAWA Hiroyuki  */
28701da177e4SLinus Torvalds long vread(char *buf, char *addr, unsigned long count)
28711da177e4SLinus Torvalds {
2872e81ce85fSJoonsoo Kim 	struct vmap_area *va;
2873e81ce85fSJoonsoo Kim 	struct vm_struct *vm;
28741da177e4SLinus Torvalds 	char *vaddr, *buf_start = buf;
2875d0107eb0SKAMEZAWA Hiroyuki 	unsigned long buflen = count;
28761da177e4SLinus Torvalds 	unsigned long n;
28771da177e4SLinus Torvalds 
28781da177e4SLinus Torvalds 	/* Don't allow overflow */
28791da177e4SLinus Torvalds 	if ((unsigned long) addr + count < count)
28801da177e4SLinus Torvalds 		count = -(unsigned long) addr;
28811da177e4SLinus Torvalds 
2882e81ce85fSJoonsoo Kim 	spin_lock(&vmap_area_lock);
2883e81ce85fSJoonsoo Kim 	list_for_each_entry(va, &vmap_area_list, list) {
2884e81ce85fSJoonsoo Kim 		if (!count)
2885e81ce85fSJoonsoo Kim 			break;
2886e81ce85fSJoonsoo Kim 
2887688fcbfcSPengfei Li 		if (!va->vm)
2888e81ce85fSJoonsoo Kim 			continue;
2889e81ce85fSJoonsoo Kim 
2890e81ce85fSJoonsoo Kim 		vm = va->vm;
2891e81ce85fSJoonsoo Kim 		vaddr = (char *) vm->addr;
2892762216abSWanpeng Li 		if (addr >= vaddr + get_vm_area_size(vm))
28931da177e4SLinus Torvalds 			continue;
28941da177e4SLinus Torvalds 		while (addr < vaddr) {
28951da177e4SLinus Torvalds 			if (count == 0)
28961da177e4SLinus Torvalds 				goto finished;
28971da177e4SLinus Torvalds 			*buf = '\0';
28981da177e4SLinus Torvalds 			buf++;
28991da177e4SLinus Torvalds 			addr++;
29001da177e4SLinus Torvalds 			count--;
29011da177e4SLinus Torvalds 		}
2902762216abSWanpeng Li 		n = vaddr + get_vm_area_size(vm) - addr;
2903d0107eb0SKAMEZAWA Hiroyuki 		if (n > count)
2904d0107eb0SKAMEZAWA Hiroyuki 			n = count;
2905e81ce85fSJoonsoo Kim 		if (!(vm->flags & VM_IOREMAP))
2906d0107eb0SKAMEZAWA Hiroyuki 			aligned_vread(buf, addr, n);
2907d0107eb0SKAMEZAWA Hiroyuki 		else /* IOREMAP area is treated as memory hole */
2908d0107eb0SKAMEZAWA Hiroyuki 			memset(buf, 0, n);
2909d0107eb0SKAMEZAWA Hiroyuki 		buf += n;
2910d0107eb0SKAMEZAWA Hiroyuki 		addr += n;
2911d0107eb0SKAMEZAWA Hiroyuki 		count -= n;
29121da177e4SLinus Torvalds 	}
29131da177e4SLinus Torvalds finished:
2914e81ce85fSJoonsoo Kim 	spin_unlock(&vmap_area_lock);
2915d0107eb0SKAMEZAWA Hiroyuki 
2916d0107eb0SKAMEZAWA Hiroyuki 	if (buf == buf_start)
2917d0107eb0SKAMEZAWA Hiroyuki 		return 0;
2918d0107eb0SKAMEZAWA Hiroyuki 	/* zero-fill memory holes */
2919d0107eb0SKAMEZAWA Hiroyuki 	if (buf != buf_start + buflen)
2920d0107eb0SKAMEZAWA Hiroyuki 		memset(buf, 0, buflen - (buf - buf_start));
2921d0107eb0SKAMEZAWA Hiroyuki 
2922d0107eb0SKAMEZAWA Hiroyuki 	return buflen;
29231da177e4SLinus Torvalds }
29241da177e4SLinus Torvalds 
2925d0107eb0SKAMEZAWA Hiroyuki /**
2926d0107eb0SKAMEZAWA Hiroyuki  * vwrite() - write vmalloc area in a safe way.
2927d0107eb0SKAMEZAWA Hiroyuki  * @buf:      buffer for source data
2928d0107eb0SKAMEZAWA Hiroyuki  * @addr:     vm address.
2929d0107eb0SKAMEZAWA Hiroyuki  * @count:    number of bytes to be read.
2930d0107eb0SKAMEZAWA Hiroyuki  *
2931d0107eb0SKAMEZAWA Hiroyuki  * This function checks that addr is a valid vmalloc'ed area, and
2932d0107eb0SKAMEZAWA Hiroyuki  * copy data from a buffer to the given addr. If specified range of
2933d0107eb0SKAMEZAWA Hiroyuki  * [addr...addr+count) includes some valid address, data is copied from
2934d0107eb0SKAMEZAWA Hiroyuki  * proper area of @buf. If there are memory holes, no copy to hole.
2935d0107eb0SKAMEZAWA Hiroyuki  * IOREMAP area is treated as memory hole and no copy is done.
2936d0107eb0SKAMEZAWA Hiroyuki  *
2937d0107eb0SKAMEZAWA Hiroyuki  * If [addr...addr+count) doesn't includes any intersects with alive
2938a8e5202dSCong Wang  * vm_struct area, returns 0. @buf should be kernel's buffer.
2939d0107eb0SKAMEZAWA Hiroyuki  *
2940d0107eb0SKAMEZAWA Hiroyuki  * Note: In usual ops, vwrite() is never necessary because the caller
2941d0107eb0SKAMEZAWA Hiroyuki  * should know vmalloc() area is valid and can use memcpy().
2942d0107eb0SKAMEZAWA Hiroyuki  * This is for routines which have to access vmalloc area without
2943d9009d67SGeert Uytterhoeven  * any information, as /dev/kmem.
2944a862f68aSMike Rapoport  *
2945a862f68aSMike Rapoport  * Return: number of bytes for which addr and buf should be
2946a862f68aSMike Rapoport  * increased (same number as @count) or %0 if [addr...addr+count)
2947a862f68aSMike Rapoport  * doesn't include any intersection with valid vmalloc area
2948d0107eb0SKAMEZAWA Hiroyuki  */
29491da177e4SLinus Torvalds long vwrite(char *buf, char *addr, unsigned long count)
29501da177e4SLinus Torvalds {
2951e81ce85fSJoonsoo Kim 	struct vmap_area *va;
2952e81ce85fSJoonsoo Kim 	struct vm_struct *vm;
2953d0107eb0SKAMEZAWA Hiroyuki 	char *vaddr;
2954d0107eb0SKAMEZAWA Hiroyuki 	unsigned long n, buflen;
2955d0107eb0SKAMEZAWA Hiroyuki 	int copied = 0;
29561da177e4SLinus Torvalds 
29571da177e4SLinus Torvalds 	/* Don't allow overflow */
29581da177e4SLinus Torvalds 	if ((unsigned long) addr + count < count)
29591da177e4SLinus Torvalds 		count = -(unsigned long) addr;
2960d0107eb0SKAMEZAWA Hiroyuki 	buflen = count;
29611da177e4SLinus Torvalds 
2962e81ce85fSJoonsoo Kim 	spin_lock(&vmap_area_lock);
2963e81ce85fSJoonsoo Kim 	list_for_each_entry(va, &vmap_area_list, list) {
2964e81ce85fSJoonsoo Kim 		if (!count)
2965e81ce85fSJoonsoo Kim 			break;
2966e81ce85fSJoonsoo Kim 
2967688fcbfcSPengfei Li 		if (!va->vm)
2968e81ce85fSJoonsoo Kim 			continue;
2969e81ce85fSJoonsoo Kim 
2970e81ce85fSJoonsoo Kim 		vm = va->vm;
2971e81ce85fSJoonsoo Kim 		vaddr = (char *) vm->addr;
2972762216abSWanpeng Li 		if (addr >= vaddr + get_vm_area_size(vm))
29731da177e4SLinus Torvalds 			continue;
29741da177e4SLinus Torvalds 		while (addr < vaddr) {
29751da177e4SLinus Torvalds 			if (count == 0)
29761da177e4SLinus Torvalds 				goto finished;
29771da177e4SLinus Torvalds 			buf++;
29781da177e4SLinus Torvalds 			addr++;
29791da177e4SLinus Torvalds 			count--;
29801da177e4SLinus Torvalds 		}
2981762216abSWanpeng Li 		n = vaddr + get_vm_area_size(vm) - addr;
2982d0107eb0SKAMEZAWA Hiroyuki 		if (n > count)
2983d0107eb0SKAMEZAWA Hiroyuki 			n = count;
2984e81ce85fSJoonsoo Kim 		if (!(vm->flags & VM_IOREMAP)) {
2985d0107eb0SKAMEZAWA Hiroyuki 			aligned_vwrite(buf, addr, n);
2986d0107eb0SKAMEZAWA Hiroyuki 			copied++;
2987d0107eb0SKAMEZAWA Hiroyuki 		}
2988d0107eb0SKAMEZAWA Hiroyuki 		buf += n;
2989d0107eb0SKAMEZAWA Hiroyuki 		addr += n;
2990d0107eb0SKAMEZAWA Hiroyuki 		count -= n;
29911da177e4SLinus Torvalds 	}
29921da177e4SLinus Torvalds finished:
2993e81ce85fSJoonsoo Kim 	spin_unlock(&vmap_area_lock);
2994d0107eb0SKAMEZAWA Hiroyuki 	if (!copied)
2995d0107eb0SKAMEZAWA Hiroyuki 		return 0;
2996d0107eb0SKAMEZAWA Hiroyuki 	return buflen;
29971da177e4SLinus Torvalds }
299883342314SNick Piggin 
299983342314SNick Piggin /**
3000e69e9d4aSHATAYAMA Daisuke  * remap_vmalloc_range_partial - map vmalloc pages to userspace
3001e69e9d4aSHATAYAMA Daisuke  * @vma:		vma to cover
3002e69e9d4aSHATAYAMA Daisuke  * @uaddr:		target user address to start at
3003e69e9d4aSHATAYAMA Daisuke  * @kaddr:		virtual address of vmalloc kernel memory
3004bdebd6a2SJann Horn  * @pgoff:		offset from @kaddr to start at
3005e69e9d4aSHATAYAMA Daisuke  * @size:		size of map area
3006e69e9d4aSHATAYAMA Daisuke  *
3007e69e9d4aSHATAYAMA Daisuke  * Returns:	0 for success, -Exxx on failure
3008e69e9d4aSHATAYAMA Daisuke  *
3009e69e9d4aSHATAYAMA Daisuke  * This function checks that @kaddr is a valid vmalloc'ed area,
3010e69e9d4aSHATAYAMA Daisuke  * and that it is big enough to cover the range starting at
3011e69e9d4aSHATAYAMA Daisuke  * @uaddr in @vma. Will return failure if that criteria isn't
3012e69e9d4aSHATAYAMA Daisuke  * met.
3013e69e9d4aSHATAYAMA Daisuke  *
3014e69e9d4aSHATAYAMA Daisuke  * Similar to remap_pfn_range() (see mm/memory.c)
3015e69e9d4aSHATAYAMA Daisuke  */
3016e69e9d4aSHATAYAMA Daisuke int remap_vmalloc_range_partial(struct vm_area_struct *vma, unsigned long uaddr,
3017bdebd6a2SJann Horn 				void *kaddr, unsigned long pgoff,
3018bdebd6a2SJann Horn 				unsigned long size)
3019e69e9d4aSHATAYAMA Daisuke {
3020e69e9d4aSHATAYAMA Daisuke 	struct vm_struct *area;
3021bdebd6a2SJann Horn 	unsigned long off;
3022bdebd6a2SJann Horn 	unsigned long end_index;
3023bdebd6a2SJann Horn 
3024bdebd6a2SJann Horn 	if (check_shl_overflow(pgoff, PAGE_SHIFT, &off))
3025bdebd6a2SJann Horn 		return -EINVAL;
3026e69e9d4aSHATAYAMA Daisuke 
3027e69e9d4aSHATAYAMA Daisuke 	size = PAGE_ALIGN(size);
3028e69e9d4aSHATAYAMA Daisuke 
3029e69e9d4aSHATAYAMA Daisuke 	if (!PAGE_ALIGNED(uaddr) || !PAGE_ALIGNED(kaddr))
3030e69e9d4aSHATAYAMA Daisuke 		return -EINVAL;
3031e69e9d4aSHATAYAMA Daisuke 
3032e69e9d4aSHATAYAMA Daisuke 	area = find_vm_area(kaddr);
3033e69e9d4aSHATAYAMA Daisuke 	if (!area)
3034e69e9d4aSHATAYAMA Daisuke 		return -EINVAL;
3035e69e9d4aSHATAYAMA Daisuke 
3036fe9041c2SChristoph Hellwig 	if (!(area->flags & (VM_USERMAP | VM_DMA_COHERENT)))
3037e69e9d4aSHATAYAMA Daisuke 		return -EINVAL;
3038e69e9d4aSHATAYAMA Daisuke 
3039bdebd6a2SJann Horn 	if (check_add_overflow(size, off, &end_index) ||
3040bdebd6a2SJann Horn 	    end_index > get_vm_area_size(area))
3041e69e9d4aSHATAYAMA Daisuke 		return -EINVAL;
3042bdebd6a2SJann Horn 	kaddr += off;
3043e69e9d4aSHATAYAMA Daisuke 
3044e69e9d4aSHATAYAMA Daisuke 	do {
3045e69e9d4aSHATAYAMA Daisuke 		struct page *page = vmalloc_to_page(kaddr);
3046e69e9d4aSHATAYAMA Daisuke 		int ret;
3047e69e9d4aSHATAYAMA Daisuke 
3048e69e9d4aSHATAYAMA Daisuke 		ret = vm_insert_page(vma, uaddr, page);
3049e69e9d4aSHATAYAMA Daisuke 		if (ret)
3050e69e9d4aSHATAYAMA Daisuke 			return ret;
3051e69e9d4aSHATAYAMA Daisuke 
3052e69e9d4aSHATAYAMA Daisuke 		uaddr += PAGE_SIZE;
3053e69e9d4aSHATAYAMA Daisuke 		kaddr += PAGE_SIZE;
3054e69e9d4aSHATAYAMA Daisuke 		size -= PAGE_SIZE;
3055e69e9d4aSHATAYAMA Daisuke 	} while (size > 0);
3056e69e9d4aSHATAYAMA Daisuke 
3057e69e9d4aSHATAYAMA Daisuke 	vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
3058e69e9d4aSHATAYAMA Daisuke 
3059e69e9d4aSHATAYAMA Daisuke 	return 0;
3060e69e9d4aSHATAYAMA Daisuke }
3061e69e9d4aSHATAYAMA Daisuke EXPORT_SYMBOL(remap_vmalloc_range_partial);
3062e69e9d4aSHATAYAMA Daisuke 
3063e69e9d4aSHATAYAMA Daisuke /**
306483342314SNick Piggin  * remap_vmalloc_range - map vmalloc pages to userspace
306583342314SNick Piggin  * @vma:		vma to cover (map full range of vma)
306683342314SNick Piggin  * @addr:		vmalloc memory
306783342314SNick Piggin  * @pgoff:		number of pages into addr before first page to map
30687682486bSRandy Dunlap  *
30697682486bSRandy Dunlap  * Returns:	0 for success, -Exxx on failure
307083342314SNick Piggin  *
307183342314SNick Piggin  * This function checks that addr is a valid vmalloc'ed area, and
307283342314SNick Piggin  * that it is big enough to cover the vma. Will return failure if
307383342314SNick Piggin  * that criteria isn't met.
307483342314SNick Piggin  *
307572fd4a35SRobert P. J. Day  * Similar to remap_pfn_range() (see mm/memory.c)
307683342314SNick Piggin  */
307783342314SNick Piggin int remap_vmalloc_range(struct vm_area_struct *vma, void *addr,
307883342314SNick Piggin 						unsigned long pgoff)
307983342314SNick Piggin {
3080e69e9d4aSHATAYAMA Daisuke 	return remap_vmalloc_range_partial(vma, vma->vm_start,
3081bdebd6a2SJann Horn 					   addr, pgoff,
3082e69e9d4aSHATAYAMA Daisuke 					   vma->vm_end - vma->vm_start);
308383342314SNick Piggin }
308483342314SNick Piggin EXPORT_SYMBOL(remap_vmalloc_range);
308583342314SNick Piggin 
30868b1e0f81SAnshuman Khandual static int f(pte_t *pte, unsigned long addr, void *data)
30875f4352fbSJeremy Fitzhardinge {
3088cd12909cSDavid Vrabel 	pte_t ***p = data;
3089cd12909cSDavid Vrabel 
3090cd12909cSDavid Vrabel 	if (p) {
3091cd12909cSDavid Vrabel 		*(*p) = pte;
3092cd12909cSDavid Vrabel 		(*p)++;
3093cd12909cSDavid Vrabel 	}
30945f4352fbSJeremy Fitzhardinge 	return 0;
30955f4352fbSJeremy Fitzhardinge }
30965f4352fbSJeremy Fitzhardinge 
30975f4352fbSJeremy Fitzhardinge /**
30985f4352fbSJeremy Fitzhardinge  * alloc_vm_area - allocate a range of kernel address space
30995f4352fbSJeremy Fitzhardinge  * @size:	   size of the area
3100cd12909cSDavid Vrabel  * @ptes:	   returns the PTEs for the address space
31017682486bSRandy Dunlap  *
31027682486bSRandy Dunlap  * Returns:	NULL on failure, vm_struct on success
31035f4352fbSJeremy Fitzhardinge  *
31045f4352fbSJeremy Fitzhardinge  * This function reserves a range of kernel address space, and
31055f4352fbSJeremy Fitzhardinge  * allocates pagetables to map that range.  No actual mappings
3106cd12909cSDavid Vrabel  * are created.
3107cd12909cSDavid Vrabel  *
3108cd12909cSDavid Vrabel  * If @ptes is non-NULL, pointers to the PTEs (in init_mm)
3109cd12909cSDavid Vrabel  * allocated for the VM area are returned.
31105f4352fbSJeremy Fitzhardinge  */
3111cd12909cSDavid Vrabel struct vm_struct *alloc_vm_area(size_t size, pte_t **ptes)
31125f4352fbSJeremy Fitzhardinge {
31135f4352fbSJeremy Fitzhardinge 	struct vm_struct *area;
31145f4352fbSJeremy Fitzhardinge 
311523016969SChristoph Lameter 	area = get_vm_area_caller(size, VM_IOREMAP,
311623016969SChristoph Lameter 				__builtin_return_address(0));
31175f4352fbSJeremy Fitzhardinge 	if (area == NULL)
31185f4352fbSJeremy Fitzhardinge 		return NULL;
31195f4352fbSJeremy Fitzhardinge 
31205f4352fbSJeremy Fitzhardinge 	/*
31215f4352fbSJeremy Fitzhardinge 	 * This ensures that page tables are constructed for this region
31225f4352fbSJeremy Fitzhardinge 	 * of kernel virtual address space and mapped into init_mm.
31235f4352fbSJeremy Fitzhardinge 	 */
31245f4352fbSJeremy Fitzhardinge 	if (apply_to_page_range(&init_mm, (unsigned long)area->addr,
3125cd12909cSDavid Vrabel 				size, f, ptes ? &ptes : NULL)) {
31265f4352fbSJeremy Fitzhardinge 		free_vm_area(area);
31275f4352fbSJeremy Fitzhardinge 		return NULL;
31285f4352fbSJeremy Fitzhardinge 	}
31295f4352fbSJeremy Fitzhardinge 
31305f4352fbSJeremy Fitzhardinge 	return area;
31315f4352fbSJeremy Fitzhardinge }
31325f4352fbSJeremy Fitzhardinge EXPORT_SYMBOL_GPL(alloc_vm_area);
31335f4352fbSJeremy Fitzhardinge 
31345f4352fbSJeremy Fitzhardinge void free_vm_area(struct vm_struct *area)
31355f4352fbSJeremy Fitzhardinge {
31365f4352fbSJeremy Fitzhardinge 	struct vm_struct *ret;
31375f4352fbSJeremy Fitzhardinge 	ret = remove_vm_area(area->addr);
31385f4352fbSJeremy Fitzhardinge 	BUG_ON(ret != area);
31395f4352fbSJeremy Fitzhardinge 	kfree(area);
31405f4352fbSJeremy Fitzhardinge }
31415f4352fbSJeremy Fitzhardinge EXPORT_SYMBOL_GPL(free_vm_area);
3142a10aa579SChristoph Lameter 
31434f8b02b4STejun Heo #ifdef CONFIG_SMP
3144ca23e405STejun Heo static struct vmap_area *node_to_va(struct rb_node *n)
3145ca23e405STejun Heo {
31464583e773SGeliang Tang 	return rb_entry_safe(n, struct vmap_area, rb_node);
3147ca23e405STejun Heo }
3148ca23e405STejun Heo 
3149ca23e405STejun Heo /**
315068ad4a33SUladzislau Rezki (Sony)  * pvm_find_va_enclose_addr - find the vmap_area @addr belongs to
315168ad4a33SUladzislau Rezki (Sony)  * @addr: target address
3152ca23e405STejun Heo  *
315368ad4a33SUladzislau Rezki (Sony)  * Returns: vmap_area if it is found. If there is no such area
315468ad4a33SUladzislau Rezki (Sony)  *   the first highest(reverse order) vmap_area is returned
315568ad4a33SUladzislau Rezki (Sony)  *   i.e. va->va_start < addr && va->va_end < addr or NULL
315668ad4a33SUladzislau Rezki (Sony)  *   if there are no any areas before @addr.
3157ca23e405STejun Heo  */
315868ad4a33SUladzislau Rezki (Sony) static struct vmap_area *
315968ad4a33SUladzislau Rezki (Sony) pvm_find_va_enclose_addr(unsigned long addr)
3160ca23e405STejun Heo {
316168ad4a33SUladzislau Rezki (Sony) 	struct vmap_area *va, *tmp;
316268ad4a33SUladzislau Rezki (Sony) 	struct rb_node *n;
316368ad4a33SUladzislau Rezki (Sony) 
316468ad4a33SUladzislau Rezki (Sony) 	n = free_vmap_area_root.rb_node;
316568ad4a33SUladzislau Rezki (Sony) 	va = NULL;
3166ca23e405STejun Heo 
3167ca23e405STejun Heo 	while (n) {
316868ad4a33SUladzislau Rezki (Sony) 		tmp = rb_entry(n, struct vmap_area, rb_node);
316968ad4a33SUladzislau Rezki (Sony) 		if (tmp->va_start <= addr) {
317068ad4a33SUladzislau Rezki (Sony) 			va = tmp;
317168ad4a33SUladzislau Rezki (Sony) 			if (tmp->va_end >= addr)
3172ca23e405STejun Heo 				break;
3173ca23e405STejun Heo 
317468ad4a33SUladzislau Rezki (Sony) 			n = n->rb_right;
3175ca23e405STejun Heo 		} else {
317668ad4a33SUladzislau Rezki (Sony) 			n = n->rb_left;
3177ca23e405STejun Heo 		}
317868ad4a33SUladzislau Rezki (Sony) 	}
317968ad4a33SUladzislau Rezki (Sony) 
318068ad4a33SUladzislau Rezki (Sony) 	return va;
3181ca23e405STejun Heo }
3182ca23e405STejun Heo 
3183ca23e405STejun Heo /**
318468ad4a33SUladzislau Rezki (Sony)  * pvm_determine_end_from_reverse - find the highest aligned address
318568ad4a33SUladzislau Rezki (Sony)  * of free block below VMALLOC_END
318668ad4a33SUladzislau Rezki (Sony)  * @va:
318768ad4a33SUladzislau Rezki (Sony)  *   in - the VA we start the search(reverse order);
318868ad4a33SUladzislau Rezki (Sony)  *   out - the VA with the highest aligned end address.
3189ca23e405STejun Heo  *
319068ad4a33SUladzislau Rezki (Sony)  * Returns: determined end address within vmap_area
3191ca23e405STejun Heo  */
319268ad4a33SUladzislau Rezki (Sony) static unsigned long
319368ad4a33SUladzislau Rezki (Sony) pvm_determine_end_from_reverse(struct vmap_area **va, unsigned long align)
3194ca23e405STejun Heo {
319568ad4a33SUladzislau Rezki (Sony) 	unsigned long vmalloc_end = VMALLOC_END & ~(align - 1);
3196ca23e405STejun Heo 	unsigned long addr;
3197ca23e405STejun Heo 
319868ad4a33SUladzislau Rezki (Sony) 	if (likely(*va)) {
319968ad4a33SUladzislau Rezki (Sony) 		list_for_each_entry_from_reverse((*va),
320068ad4a33SUladzislau Rezki (Sony) 				&free_vmap_area_list, list) {
320168ad4a33SUladzislau Rezki (Sony) 			addr = min((*va)->va_end & ~(align - 1), vmalloc_end);
320268ad4a33SUladzislau Rezki (Sony) 			if ((*va)->va_start < addr)
320368ad4a33SUladzislau Rezki (Sony) 				return addr;
320468ad4a33SUladzislau Rezki (Sony) 		}
3205ca23e405STejun Heo 	}
3206ca23e405STejun Heo 
320768ad4a33SUladzislau Rezki (Sony) 	return 0;
3208ca23e405STejun Heo }
3209ca23e405STejun Heo 
3210ca23e405STejun Heo /**
3211ca23e405STejun Heo  * pcpu_get_vm_areas - allocate vmalloc areas for percpu allocator
3212ca23e405STejun Heo  * @offsets: array containing offset of each area
3213ca23e405STejun Heo  * @sizes: array containing size of each area
3214ca23e405STejun Heo  * @nr_vms: the number of areas to allocate
3215ca23e405STejun Heo  * @align: alignment, all entries in @offsets and @sizes must be aligned to this
3216ca23e405STejun Heo  *
3217ca23e405STejun Heo  * Returns: kmalloc'd vm_struct pointer array pointing to allocated
3218ca23e405STejun Heo  *	    vm_structs on success, %NULL on failure
3219ca23e405STejun Heo  *
3220ca23e405STejun Heo  * Percpu allocator wants to use congruent vm areas so that it can
3221ca23e405STejun Heo  * maintain the offsets among percpu areas.  This function allocates
3222ec3f64fcSDavid Rientjes  * congruent vmalloc areas for it with GFP_KERNEL.  These areas tend to
3223ec3f64fcSDavid Rientjes  * be scattered pretty far, distance between two areas easily going up
3224ec3f64fcSDavid Rientjes  * to gigabytes.  To avoid interacting with regular vmallocs, these
3225ec3f64fcSDavid Rientjes  * areas are allocated from top.
3226ca23e405STejun Heo  *
3227ca23e405STejun Heo  * Despite its complicated look, this allocator is rather simple. It
322868ad4a33SUladzislau Rezki (Sony)  * does everything top-down and scans free blocks from the end looking
322968ad4a33SUladzislau Rezki (Sony)  * for matching base. While scanning, if any of the areas do not fit the
323068ad4a33SUladzislau Rezki (Sony)  * base address is pulled down to fit the area. Scanning is repeated till
323168ad4a33SUladzislau Rezki (Sony)  * all the areas fit and then all necessary data structures are inserted
323268ad4a33SUladzislau Rezki (Sony)  * and the result is returned.
3233ca23e405STejun Heo  */
3234ca23e405STejun Heo struct vm_struct **pcpu_get_vm_areas(const unsigned long *offsets,
3235ca23e405STejun Heo 				     const size_t *sizes, int nr_vms,
3236ec3f64fcSDavid Rientjes 				     size_t align)
3237ca23e405STejun Heo {
3238ca23e405STejun Heo 	const unsigned long vmalloc_start = ALIGN(VMALLOC_START, align);
3239ca23e405STejun Heo 	const unsigned long vmalloc_end = VMALLOC_END & ~(align - 1);
324068ad4a33SUladzislau Rezki (Sony) 	struct vmap_area **vas, *va;
3241ca23e405STejun Heo 	struct vm_struct **vms;
3242ca23e405STejun Heo 	int area, area2, last_area, term_area;
3243253a496dSDaniel Axtens 	unsigned long base, start, size, end, last_end, orig_start, orig_end;
3244ca23e405STejun Heo 	bool purged = false;
324568ad4a33SUladzislau Rezki (Sony) 	enum fit_type type;
3246ca23e405STejun Heo 
3247ca23e405STejun Heo 	/* verify parameters and allocate data structures */
3248891c49abSAlexander Kuleshov 	BUG_ON(offset_in_page(align) || !is_power_of_2(align));
3249ca23e405STejun Heo 	for (last_area = 0, area = 0; area < nr_vms; area++) {
3250ca23e405STejun Heo 		start = offsets[area];
3251ca23e405STejun Heo 		end = start + sizes[area];
3252ca23e405STejun Heo 
3253ca23e405STejun Heo 		/* is everything aligned properly? */
3254ca23e405STejun Heo 		BUG_ON(!IS_ALIGNED(offsets[area], align));
3255ca23e405STejun Heo 		BUG_ON(!IS_ALIGNED(sizes[area], align));
3256ca23e405STejun Heo 
3257ca23e405STejun Heo 		/* detect the area with the highest address */
3258ca23e405STejun Heo 		if (start > offsets[last_area])
3259ca23e405STejun Heo 			last_area = area;
3260ca23e405STejun Heo 
3261c568da28SWei Yang 		for (area2 = area + 1; area2 < nr_vms; area2++) {
3262ca23e405STejun Heo 			unsigned long start2 = offsets[area2];
3263ca23e405STejun Heo 			unsigned long end2 = start2 + sizes[area2];
3264ca23e405STejun Heo 
3265c568da28SWei Yang 			BUG_ON(start2 < end && start < end2);
3266ca23e405STejun Heo 		}
3267ca23e405STejun Heo 	}
3268ca23e405STejun Heo 	last_end = offsets[last_area] + sizes[last_area];
3269ca23e405STejun Heo 
3270ca23e405STejun Heo 	if (vmalloc_end - vmalloc_start < last_end) {
3271ca23e405STejun Heo 		WARN_ON(true);
3272ca23e405STejun Heo 		return NULL;
3273ca23e405STejun Heo 	}
3274ca23e405STejun Heo 
32754d67d860SThomas Meyer 	vms = kcalloc(nr_vms, sizeof(vms[0]), GFP_KERNEL);
32764d67d860SThomas Meyer 	vas = kcalloc(nr_vms, sizeof(vas[0]), GFP_KERNEL);
3277ca23e405STejun Heo 	if (!vas || !vms)
3278f1db7afdSKautuk Consul 		goto err_free2;
3279ca23e405STejun Heo 
3280ca23e405STejun Heo 	for (area = 0; area < nr_vms; area++) {
328168ad4a33SUladzislau Rezki (Sony) 		vas[area] = kmem_cache_zalloc(vmap_area_cachep, GFP_KERNEL);
3282ec3f64fcSDavid Rientjes 		vms[area] = kzalloc(sizeof(struct vm_struct), GFP_KERNEL);
3283ca23e405STejun Heo 		if (!vas[area] || !vms[area])
3284ca23e405STejun Heo 			goto err_free;
3285ca23e405STejun Heo 	}
3286ca23e405STejun Heo retry:
3287e36176beSUladzislau Rezki (Sony) 	spin_lock(&free_vmap_area_lock);
3288ca23e405STejun Heo 
3289ca23e405STejun Heo 	/* start scanning - we scan from the top, begin with the last area */
3290ca23e405STejun Heo 	area = term_area = last_area;
3291ca23e405STejun Heo 	start = offsets[area];
3292ca23e405STejun Heo 	end = start + sizes[area];
3293ca23e405STejun Heo 
329468ad4a33SUladzislau Rezki (Sony) 	va = pvm_find_va_enclose_addr(vmalloc_end);
329568ad4a33SUladzislau Rezki (Sony) 	base = pvm_determine_end_from_reverse(&va, align) - end;
3296ca23e405STejun Heo 
3297ca23e405STejun Heo 	while (true) {
3298ca23e405STejun Heo 		/*
3299ca23e405STejun Heo 		 * base might have underflowed, add last_end before
3300ca23e405STejun Heo 		 * comparing.
3301ca23e405STejun Heo 		 */
330268ad4a33SUladzislau Rezki (Sony) 		if (base + last_end < vmalloc_start + last_end)
330368ad4a33SUladzislau Rezki (Sony) 			goto overflow;
3304ca23e405STejun Heo 
3305ca23e405STejun Heo 		/*
330668ad4a33SUladzislau Rezki (Sony) 		 * Fitting base has not been found.
3307ca23e405STejun Heo 		 */
330868ad4a33SUladzislau Rezki (Sony) 		if (va == NULL)
330968ad4a33SUladzislau Rezki (Sony) 			goto overflow;
3310ca23e405STejun Heo 
3311ca23e405STejun Heo 		/*
3312d8cc323dSQiujun Huang 		 * If required width exceeds current VA block, move
33135336e52cSKuppuswamy Sathyanarayanan 		 * base downwards and then recheck.
33145336e52cSKuppuswamy Sathyanarayanan 		 */
33155336e52cSKuppuswamy Sathyanarayanan 		if (base + end > va->va_end) {
33165336e52cSKuppuswamy Sathyanarayanan 			base = pvm_determine_end_from_reverse(&va, align) - end;
33175336e52cSKuppuswamy Sathyanarayanan 			term_area = area;
33185336e52cSKuppuswamy Sathyanarayanan 			continue;
33195336e52cSKuppuswamy Sathyanarayanan 		}
33205336e52cSKuppuswamy Sathyanarayanan 
33215336e52cSKuppuswamy Sathyanarayanan 		/*
332268ad4a33SUladzislau Rezki (Sony) 		 * If this VA does not fit, move base downwards and recheck.
3323ca23e405STejun Heo 		 */
33245336e52cSKuppuswamy Sathyanarayanan 		if (base + start < va->va_start) {
332568ad4a33SUladzislau Rezki (Sony) 			va = node_to_va(rb_prev(&va->rb_node));
332668ad4a33SUladzislau Rezki (Sony) 			base = pvm_determine_end_from_reverse(&va, align) - end;
3327ca23e405STejun Heo 			term_area = area;
3328ca23e405STejun Heo 			continue;
3329ca23e405STejun Heo 		}
3330ca23e405STejun Heo 
3331ca23e405STejun Heo 		/*
3332ca23e405STejun Heo 		 * This area fits, move on to the previous one.  If
3333ca23e405STejun Heo 		 * the previous one is the terminal one, we're done.
3334ca23e405STejun Heo 		 */
3335ca23e405STejun Heo 		area = (area + nr_vms - 1) % nr_vms;
3336ca23e405STejun Heo 		if (area == term_area)
3337ca23e405STejun Heo 			break;
333868ad4a33SUladzislau Rezki (Sony) 
3339ca23e405STejun Heo 		start = offsets[area];
3340ca23e405STejun Heo 		end = start + sizes[area];
334168ad4a33SUladzislau Rezki (Sony) 		va = pvm_find_va_enclose_addr(base + end);
3342ca23e405STejun Heo 	}
334368ad4a33SUladzislau Rezki (Sony) 
3344ca23e405STejun Heo 	/* we've found a fitting base, insert all va's */
3345ca23e405STejun Heo 	for (area = 0; area < nr_vms; area++) {
334668ad4a33SUladzislau Rezki (Sony) 		int ret;
3347ca23e405STejun Heo 
334868ad4a33SUladzislau Rezki (Sony) 		start = base + offsets[area];
334968ad4a33SUladzislau Rezki (Sony) 		size = sizes[area];
335068ad4a33SUladzislau Rezki (Sony) 
335168ad4a33SUladzislau Rezki (Sony) 		va = pvm_find_va_enclose_addr(start);
335268ad4a33SUladzislau Rezki (Sony) 		if (WARN_ON_ONCE(va == NULL))
335368ad4a33SUladzislau Rezki (Sony) 			/* It is a BUG(), but trigger recovery instead. */
335468ad4a33SUladzislau Rezki (Sony) 			goto recovery;
335568ad4a33SUladzislau Rezki (Sony) 
335668ad4a33SUladzislau Rezki (Sony) 		type = classify_va_fit_type(va, start, size);
335768ad4a33SUladzislau Rezki (Sony) 		if (WARN_ON_ONCE(type == NOTHING_FIT))
335868ad4a33SUladzislau Rezki (Sony) 			/* It is a BUG(), but trigger recovery instead. */
335968ad4a33SUladzislau Rezki (Sony) 			goto recovery;
336068ad4a33SUladzislau Rezki (Sony) 
336168ad4a33SUladzislau Rezki (Sony) 		ret = adjust_va_to_fit_type(va, start, size, type);
336268ad4a33SUladzislau Rezki (Sony) 		if (unlikely(ret))
336368ad4a33SUladzislau Rezki (Sony) 			goto recovery;
336468ad4a33SUladzislau Rezki (Sony) 
336568ad4a33SUladzislau Rezki (Sony) 		/* Allocated area. */
336668ad4a33SUladzislau Rezki (Sony) 		va = vas[area];
336768ad4a33SUladzislau Rezki (Sony) 		va->va_start = start;
336868ad4a33SUladzislau Rezki (Sony) 		va->va_end = start + size;
3369ca23e405STejun Heo 	}
3370ca23e405STejun Heo 
3371e36176beSUladzislau Rezki (Sony) 	spin_unlock(&free_vmap_area_lock);
3372ca23e405STejun Heo 
3373253a496dSDaniel Axtens 	/* populate the kasan shadow space */
3374253a496dSDaniel Axtens 	for (area = 0; area < nr_vms; area++) {
3375253a496dSDaniel Axtens 		if (kasan_populate_vmalloc(vas[area]->va_start, sizes[area]))
3376253a496dSDaniel Axtens 			goto err_free_shadow;
3377253a496dSDaniel Axtens 
3378253a496dSDaniel Axtens 		kasan_unpoison_vmalloc((void *)vas[area]->va_start,
3379253a496dSDaniel Axtens 				       sizes[area]);
3380253a496dSDaniel Axtens 	}
3381253a496dSDaniel Axtens 
3382ca23e405STejun Heo 	/* insert all vm's */
3383e36176beSUladzislau Rezki (Sony) 	spin_lock(&vmap_area_lock);
3384e36176beSUladzislau Rezki (Sony) 	for (area = 0; area < nr_vms; area++) {
3385e36176beSUladzislau Rezki (Sony) 		insert_vmap_area(vas[area], &vmap_area_root, &vmap_area_list);
3386e36176beSUladzislau Rezki (Sony) 
3387e36176beSUladzislau Rezki (Sony) 		setup_vmalloc_vm_locked(vms[area], vas[area], VM_ALLOC,
3388ca23e405STejun Heo 				 pcpu_get_vm_areas);
3389e36176beSUladzislau Rezki (Sony) 	}
3390e36176beSUladzislau Rezki (Sony) 	spin_unlock(&vmap_area_lock);
3391ca23e405STejun Heo 
3392ca23e405STejun Heo 	kfree(vas);
3393ca23e405STejun Heo 	return vms;
3394ca23e405STejun Heo 
339568ad4a33SUladzislau Rezki (Sony) recovery:
3396e36176beSUladzislau Rezki (Sony) 	/*
3397e36176beSUladzislau Rezki (Sony) 	 * Remove previously allocated areas. There is no
3398e36176beSUladzislau Rezki (Sony) 	 * need in removing these areas from the busy tree,
3399e36176beSUladzislau Rezki (Sony) 	 * because they are inserted only on the final step
3400e36176beSUladzislau Rezki (Sony) 	 * and when pcpu_get_vm_areas() is success.
3401e36176beSUladzislau Rezki (Sony) 	 */
340268ad4a33SUladzislau Rezki (Sony) 	while (area--) {
3403253a496dSDaniel Axtens 		orig_start = vas[area]->va_start;
3404253a496dSDaniel Axtens 		orig_end = vas[area]->va_end;
3405253a496dSDaniel Axtens 		va = merge_or_add_vmap_area(vas[area], &free_vmap_area_root,
34063c5c3cfbSDaniel Axtens 					    &free_vmap_area_list);
34079c801f61SUladzislau Rezki (Sony) 		if (va)
3408253a496dSDaniel Axtens 			kasan_release_vmalloc(orig_start, orig_end,
3409253a496dSDaniel Axtens 				va->va_start, va->va_end);
341068ad4a33SUladzislau Rezki (Sony) 		vas[area] = NULL;
341168ad4a33SUladzislau Rezki (Sony) 	}
341268ad4a33SUladzislau Rezki (Sony) 
341368ad4a33SUladzislau Rezki (Sony) overflow:
3414e36176beSUladzislau Rezki (Sony) 	spin_unlock(&free_vmap_area_lock);
341568ad4a33SUladzislau Rezki (Sony) 	if (!purged) {
341668ad4a33SUladzislau Rezki (Sony) 		purge_vmap_area_lazy();
341768ad4a33SUladzislau Rezki (Sony) 		purged = true;
341868ad4a33SUladzislau Rezki (Sony) 
341968ad4a33SUladzislau Rezki (Sony) 		/* Before "retry", check if we recover. */
342068ad4a33SUladzislau Rezki (Sony) 		for (area = 0; area < nr_vms; area++) {
342168ad4a33SUladzislau Rezki (Sony) 			if (vas[area])
342268ad4a33SUladzislau Rezki (Sony) 				continue;
342368ad4a33SUladzislau Rezki (Sony) 
342468ad4a33SUladzislau Rezki (Sony) 			vas[area] = kmem_cache_zalloc(
342568ad4a33SUladzislau Rezki (Sony) 				vmap_area_cachep, GFP_KERNEL);
342668ad4a33SUladzislau Rezki (Sony) 			if (!vas[area])
342768ad4a33SUladzislau Rezki (Sony) 				goto err_free;
342868ad4a33SUladzislau Rezki (Sony) 		}
342968ad4a33SUladzislau Rezki (Sony) 
343068ad4a33SUladzislau Rezki (Sony) 		goto retry;
343168ad4a33SUladzislau Rezki (Sony) 	}
343268ad4a33SUladzislau Rezki (Sony) 
3433ca23e405STejun Heo err_free:
3434ca23e405STejun Heo 	for (area = 0; area < nr_vms; area++) {
343568ad4a33SUladzislau Rezki (Sony) 		if (vas[area])
343668ad4a33SUladzislau Rezki (Sony) 			kmem_cache_free(vmap_area_cachep, vas[area]);
343768ad4a33SUladzislau Rezki (Sony) 
3438ca23e405STejun Heo 		kfree(vms[area]);
3439ca23e405STejun Heo 	}
3440f1db7afdSKautuk Consul err_free2:
3441ca23e405STejun Heo 	kfree(vas);
3442ca23e405STejun Heo 	kfree(vms);
3443ca23e405STejun Heo 	return NULL;
3444253a496dSDaniel Axtens 
3445253a496dSDaniel Axtens err_free_shadow:
3446253a496dSDaniel Axtens 	spin_lock(&free_vmap_area_lock);
3447253a496dSDaniel Axtens 	/*
3448253a496dSDaniel Axtens 	 * We release all the vmalloc shadows, even the ones for regions that
3449253a496dSDaniel Axtens 	 * hadn't been successfully added. This relies on kasan_release_vmalloc
3450253a496dSDaniel Axtens 	 * being able to tolerate this case.
3451253a496dSDaniel Axtens 	 */
3452253a496dSDaniel Axtens 	for (area = 0; area < nr_vms; area++) {
3453253a496dSDaniel Axtens 		orig_start = vas[area]->va_start;
3454253a496dSDaniel Axtens 		orig_end = vas[area]->va_end;
3455253a496dSDaniel Axtens 		va = merge_or_add_vmap_area(vas[area], &free_vmap_area_root,
3456253a496dSDaniel Axtens 					    &free_vmap_area_list);
34579c801f61SUladzislau Rezki (Sony) 		if (va)
3458253a496dSDaniel Axtens 			kasan_release_vmalloc(orig_start, orig_end,
3459253a496dSDaniel Axtens 				va->va_start, va->va_end);
3460253a496dSDaniel Axtens 		vas[area] = NULL;
3461253a496dSDaniel Axtens 		kfree(vms[area]);
3462253a496dSDaniel Axtens 	}
3463253a496dSDaniel Axtens 	spin_unlock(&free_vmap_area_lock);
3464253a496dSDaniel Axtens 	kfree(vas);
3465253a496dSDaniel Axtens 	kfree(vms);
3466253a496dSDaniel Axtens 	return NULL;
3467ca23e405STejun Heo }
3468ca23e405STejun Heo 
3469ca23e405STejun Heo /**
3470ca23e405STejun Heo  * pcpu_free_vm_areas - free vmalloc areas for percpu allocator
3471ca23e405STejun Heo  * @vms: vm_struct pointer array returned by pcpu_get_vm_areas()
3472ca23e405STejun Heo  * @nr_vms: the number of allocated areas
3473ca23e405STejun Heo  *
3474ca23e405STejun Heo  * Free vm_structs and the array allocated by pcpu_get_vm_areas().
3475ca23e405STejun Heo  */
3476ca23e405STejun Heo void pcpu_free_vm_areas(struct vm_struct **vms, int nr_vms)
3477ca23e405STejun Heo {
3478ca23e405STejun Heo 	int i;
3479ca23e405STejun Heo 
3480ca23e405STejun Heo 	for (i = 0; i < nr_vms; i++)
3481ca23e405STejun Heo 		free_vm_area(vms[i]);
3482ca23e405STejun Heo 	kfree(vms);
3483ca23e405STejun Heo }
34844f8b02b4STejun Heo #endif	/* CONFIG_SMP */
3485a10aa579SChristoph Lameter 
3486a10aa579SChristoph Lameter #ifdef CONFIG_PROC_FS
3487a10aa579SChristoph Lameter static void *s_start(struct seq_file *m, loff_t *pos)
3488e36176beSUladzislau Rezki (Sony) 	__acquires(&vmap_purge_lock)
3489d4033afdSJoonsoo Kim 	__acquires(&vmap_area_lock)
3490a10aa579SChristoph Lameter {
3491e36176beSUladzislau Rezki (Sony) 	mutex_lock(&vmap_purge_lock);
3492d4033afdSJoonsoo Kim 	spin_lock(&vmap_area_lock);
3493e36176beSUladzislau Rezki (Sony) 
34943f500069Szijun_hu 	return seq_list_start(&vmap_area_list, *pos);
3495a10aa579SChristoph Lameter }
3496a10aa579SChristoph Lameter 
3497a10aa579SChristoph Lameter static void *s_next(struct seq_file *m, void *p, loff_t *pos)
3498a10aa579SChristoph Lameter {
34993f500069Szijun_hu 	return seq_list_next(p, &vmap_area_list, pos);
3500a10aa579SChristoph Lameter }
3501a10aa579SChristoph Lameter 
3502a10aa579SChristoph Lameter static void s_stop(struct seq_file *m, void *p)
3503e36176beSUladzislau Rezki (Sony) 	__releases(&vmap_purge_lock)
3504d4033afdSJoonsoo Kim 	__releases(&vmap_area_lock)
3505a10aa579SChristoph Lameter {
3506e36176beSUladzislau Rezki (Sony) 	mutex_unlock(&vmap_purge_lock);
3507d4033afdSJoonsoo Kim 	spin_unlock(&vmap_area_lock);
3508a10aa579SChristoph Lameter }
3509a10aa579SChristoph Lameter 
3510a47a126aSEric Dumazet static void show_numa_info(struct seq_file *m, struct vm_struct *v)
3511a47a126aSEric Dumazet {
3512e5adfffcSKirill A. Shutemov 	if (IS_ENABLED(CONFIG_NUMA)) {
3513a47a126aSEric Dumazet 		unsigned int nr, *counters = m->private;
3514a47a126aSEric Dumazet 
3515a47a126aSEric Dumazet 		if (!counters)
3516a47a126aSEric Dumazet 			return;
3517a47a126aSEric Dumazet 
3518af12346cSWanpeng Li 		if (v->flags & VM_UNINITIALIZED)
3519af12346cSWanpeng Li 			return;
35207e5b528bSDmitry Vyukov 		/* Pair with smp_wmb() in clear_vm_uninitialized_flag() */
35217e5b528bSDmitry Vyukov 		smp_rmb();
3522af12346cSWanpeng Li 
3523a47a126aSEric Dumazet 		memset(counters, 0, nr_node_ids * sizeof(unsigned int));
3524a47a126aSEric Dumazet 
3525a47a126aSEric Dumazet 		for (nr = 0; nr < v->nr_pages; nr++)
3526a47a126aSEric Dumazet 			counters[page_to_nid(v->pages[nr])]++;
3527a47a126aSEric Dumazet 
3528a47a126aSEric Dumazet 		for_each_node_state(nr, N_HIGH_MEMORY)
3529a47a126aSEric Dumazet 			if (counters[nr])
3530a47a126aSEric Dumazet 				seq_printf(m, " N%u=%u", nr, counters[nr]);
3531a47a126aSEric Dumazet 	}
3532a47a126aSEric Dumazet }
3533a47a126aSEric Dumazet 
3534dd3b8353SUladzislau Rezki (Sony) static void show_purge_info(struct seq_file *m)
3535dd3b8353SUladzislau Rezki (Sony) {
3536dd3b8353SUladzislau Rezki (Sony) 	struct llist_node *head;
3537dd3b8353SUladzislau Rezki (Sony) 	struct vmap_area *va;
3538dd3b8353SUladzislau Rezki (Sony) 
3539dd3b8353SUladzislau Rezki (Sony) 	head = READ_ONCE(vmap_purge_list.first);
3540dd3b8353SUladzislau Rezki (Sony) 	if (head == NULL)
3541dd3b8353SUladzislau Rezki (Sony) 		return;
3542dd3b8353SUladzislau Rezki (Sony) 
3543dd3b8353SUladzislau Rezki (Sony) 	llist_for_each_entry(va, head, purge_list) {
3544dd3b8353SUladzislau Rezki (Sony) 		seq_printf(m, "0x%pK-0x%pK %7ld unpurged vm_area\n",
3545dd3b8353SUladzislau Rezki (Sony) 			(void *)va->va_start, (void *)va->va_end,
3546dd3b8353SUladzislau Rezki (Sony) 			va->va_end - va->va_start);
3547dd3b8353SUladzislau Rezki (Sony) 	}
3548dd3b8353SUladzislau Rezki (Sony) }
3549dd3b8353SUladzislau Rezki (Sony) 
3550a10aa579SChristoph Lameter static int s_show(struct seq_file *m, void *p)
3551a10aa579SChristoph Lameter {
35523f500069Szijun_hu 	struct vmap_area *va;
3553d4033afdSJoonsoo Kim 	struct vm_struct *v;
3554d4033afdSJoonsoo Kim 
35553f500069Szijun_hu 	va = list_entry(p, struct vmap_area, list);
35563f500069Szijun_hu 
3557c2ce8c14SWanpeng Li 	/*
3558688fcbfcSPengfei Li 	 * s_show can encounter race with remove_vm_area, !vm on behalf
3559688fcbfcSPengfei Li 	 * of vmap area is being tear down or vm_map_ram allocation.
3560c2ce8c14SWanpeng Li 	 */
3561688fcbfcSPengfei Li 	if (!va->vm) {
3562dd3b8353SUladzislau Rezki (Sony) 		seq_printf(m, "0x%pK-0x%pK %7ld vm_map_ram\n",
356378c72746SYisheng Xie 			(void *)va->va_start, (void *)va->va_end,
3564dd3b8353SUladzislau Rezki (Sony) 			va->va_end - va->va_start);
356578c72746SYisheng Xie 
3566d4033afdSJoonsoo Kim 		return 0;
356778c72746SYisheng Xie 	}
3568d4033afdSJoonsoo Kim 
3569d4033afdSJoonsoo Kim 	v = va->vm;
3570a10aa579SChristoph Lameter 
357145ec1690SKees Cook 	seq_printf(m, "0x%pK-0x%pK %7ld",
3572a10aa579SChristoph Lameter 		v->addr, v->addr + v->size, v->size);
3573a10aa579SChristoph Lameter 
357462c70bceSJoe Perches 	if (v->caller)
357562c70bceSJoe Perches 		seq_printf(m, " %pS", v->caller);
357623016969SChristoph Lameter 
3577a10aa579SChristoph Lameter 	if (v->nr_pages)
3578a10aa579SChristoph Lameter 		seq_printf(m, " pages=%d", v->nr_pages);
3579a10aa579SChristoph Lameter 
3580a10aa579SChristoph Lameter 	if (v->phys_addr)
3581199eaa05SMiles Chen 		seq_printf(m, " phys=%pa", &v->phys_addr);
3582a10aa579SChristoph Lameter 
3583a10aa579SChristoph Lameter 	if (v->flags & VM_IOREMAP)
3584f4527c90SFabian Frederick 		seq_puts(m, " ioremap");
3585a10aa579SChristoph Lameter 
3586a10aa579SChristoph Lameter 	if (v->flags & VM_ALLOC)
3587f4527c90SFabian Frederick 		seq_puts(m, " vmalloc");
3588a10aa579SChristoph Lameter 
3589a10aa579SChristoph Lameter 	if (v->flags & VM_MAP)
3590f4527c90SFabian Frederick 		seq_puts(m, " vmap");
3591a10aa579SChristoph Lameter 
3592a10aa579SChristoph Lameter 	if (v->flags & VM_USERMAP)
3593f4527c90SFabian Frederick 		seq_puts(m, " user");
3594a10aa579SChristoph Lameter 
3595fe9041c2SChristoph Hellwig 	if (v->flags & VM_DMA_COHERENT)
3596fe9041c2SChristoph Hellwig 		seq_puts(m, " dma-coherent");
3597fe9041c2SChristoph Hellwig 
3598244d63eeSDavid Rientjes 	if (is_vmalloc_addr(v->pages))
3599f4527c90SFabian Frederick 		seq_puts(m, " vpages");
3600a10aa579SChristoph Lameter 
3601a47a126aSEric Dumazet 	show_numa_info(m, v);
3602a10aa579SChristoph Lameter 	seq_putc(m, '\n');
3603dd3b8353SUladzislau Rezki (Sony) 
3604dd3b8353SUladzislau Rezki (Sony) 	/*
3605dd3b8353SUladzislau Rezki (Sony) 	 * As a final step, dump "unpurged" areas. Note,
3606dd3b8353SUladzislau Rezki (Sony) 	 * that entire "/proc/vmallocinfo" output will not
3607dd3b8353SUladzislau Rezki (Sony) 	 * be address sorted, because the purge list is not
3608dd3b8353SUladzislau Rezki (Sony) 	 * sorted.
3609dd3b8353SUladzislau Rezki (Sony) 	 */
3610dd3b8353SUladzislau Rezki (Sony) 	if (list_is_last(&va->list, &vmap_area_list))
3611dd3b8353SUladzislau Rezki (Sony) 		show_purge_info(m);
3612dd3b8353SUladzislau Rezki (Sony) 
3613a10aa579SChristoph Lameter 	return 0;
3614a10aa579SChristoph Lameter }
3615a10aa579SChristoph Lameter 
36165f6a6a9cSAlexey Dobriyan static const struct seq_operations vmalloc_op = {
3617a10aa579SChristoph Lameter 	.start = s_start,
3618a10aa579SChristoph Lameter 	.next = s_next,
3619a10aa579SChristoph Lameter 	.stop = s_stop,
3620a10aa579SChristoph Lameter 	.show = s_show,
3621a10aa579SChristoph Lameter };
36225f6a6a9cSAlexey Dobriyan 
36235f6a6a9cSAlexey Dobriyan static int __init proc_vmalloc_init(void)
36245f6a6a9cSAlexey Dobriyan {
3625fddda2b7SChristoph Hellwig 	if (IS_ENABLED(CONFIG_NUMA))
36260825a6f9SJoe Perches 		proc_create_seq_private("vmallocinfo", 0400, NULL,
362744414d82SChristoph Hellwig 				&vmalloc_op,
362844414d82SChristoph Hellwig 				nr_node_ids * sizeof(unsigned int), NULL);
3629fddda2b7SChristoph Hellwig 	else
36300825a6f9SJoe Perches 		proc_create_seq("vmallocinfo", 0400, NULL, &vmalloc_op);
36315f6a6a9cSAlexey Dobriyan 	return 0;
36325f6a6a9cSAlexey Dobriyan }
36335f6a6a9cSAlexey Dobriyan module_init(proc_vmalloc_init);
3634db3808c1SJoonsoo Kim 
3635a10aa579SChristoph Lameter #endif
3636