Home | History | Annotate | Line # | Download | only in uvm
uvm_km.c revision 1.149
      1 /*	$NetBSD: uvm_km.c,v 1.149 2019/12/01 14:43:26 ad Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1997 Charles D. Cranor and Washington University.
      5  * Copyright (c) 1991, 1993, The Regents of the University of California.
      6  *
      7  * All rights reserved.
      8  *
      9  * This code is derived from software contributed to Berkeley by
     10  * The Mach Operating System project at Carnegie-Mellon University.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  *
     36  *	@(#)vm_kern.c   8.3 (Berkeley) 1/12/94
     37  * from: Id: uvm_km.c,v 1.1.2.14 1998/02/06 05:19:27 chs Exp
     38  *
     39  *
     40  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
     41  * All rights reserved.
     42  *
     43  * Permission to use, copy, modify and distribute this software and
     44  * its documentation is hereby granted, provided that both the copyright
     45  * notice and this permission notice appear in all copies of the
     46  * software, derivative works or modified versions, and any portions
     47  * thereof, and that both notices appear in supporting documentation.
     48  *
     49  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
     50  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
     51  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
     52  *
     53  * Carnegie Mellon requests users of this software to return to
     54  *
     55  *  Software Distribution Coordinator  or  Software.Distribution (at) CS.CMU.EDU
     56  *  School of Computer Science
     57  *  Carnegie Mellon University
     58  *  Pittsburgh PA 15213-3890
     59  *
     60  * any improvements or extensions that they make and grant Carnegie the
     61  * rights to redistribute these changes.
     62  */
     63 
     64 /*
     65  * uvm_km.c: handle kernel memory allocation and management
     66  */
     67 
     68 /*
     69  * overview of kernel memory management:
     70  *
     71  * the kernel virtual address space is mapped by "kernel_map."   kernel_map
     72  * starts at VM_MIN_KERNEL_ADDRESS and goes to VM_MAX_KERNEL_ADDRESS.
     73  * note that VM_MIN_KERNEL_ADDRESS is equal to vm_map_min(kernel_map).
     74  *
     75  * the kernel_map has several "submaps."   submaps can only appear in
     76  * the kernel_map (user processes can't use them).   submaps "take over"
     77  * the management of a sub-range of the kernel's address space.  submaps
     78  * are typically allocated at boot time and are never released.   kernel
     79  * virtual address space that is mapped by a submap is locked by the
     80  * submap's lock -- not the kernel_map's lock.
     81  *
     82  * thus, the useful feature of submaps is that they allow us to break
     83  * up the locking and protection of the kernel address space into smaller
     84  * chunks.
     85  *
     86  * the vm system has several standard kernel submaps/arenas, including:
     87  *   kmem_arena => used for kmem/pool (memoryallocators(9))
     88  *   pager_map => used to map "buf" structures into kernel space
     89  *   exec_map => used during exec to handle exec args
     90  *   etc...
     91  *
     92  * The kmem_arena is a "special submap", as it lives in a fixed map entry
     93  * within the kernel_map and is controlled by vmem(9).
     94  *
     95  * the kernel allocates its private memory out of special uvm_objects whose
     96  * reference count is set to UVM_OBJ_KERN (thus indicating that the objects
     97  * are "special" and never die).   all kernel objects should be thought of
     98  * as large, fixed-sized, sparsely populated uvm_objects.   each kernel
     99  * object is equal to the size of kernel virtual address space (i.e. the
    100  * value "VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS").
    101  *
    102  * note that just because a kernel object spans the entire kernel virtual
    103  * address space doesn't mean that it has to be mapped into the entire space.
    104  * large chunks of a kernel object's space go unused either because
    105  * that area of kernel VM is unmapped, or there is some other type of
    106  * object mapped into that range (e.g. a vnode).    for submap's kernel
    107  * objects, the only part of the object that can ever be populated is the
    108  * offsets that are managed by the submap.
    109  *
    110  * note that the "offset" in a kernel object is always the kernel virtual
    111  * address minus the VM_MIN_KERNEL_ADDRESS (aka vm_map_min(kernel_map)).
    112  * example:
    113  *   suppose VM_MIN_KERNEL_ADDRESS is 0xf8000000 and the kernel does a
    114  *   uvm_km_alloc(kernel_map, PAGE_SIZE) [allocate 1 wired down page in the
    115  *   kernel map].    if uvm_km_alloc returns virtual address 0xf8235000,
    116  *   then that means that the page at offset 0x235000 in kernel_object is
    117  *   mapped at 0xf8235000.
    118  *
    119  * kernel object have one other special property: when the kernel virtual
    120  * memory mapping them is unmapped, the backing memory in the object is
    121  * freed right away.   this is done with the uvm_km_pgremove() function.
    122  * this has to be done because there is no backing store for kernel pages
    123  * and no need to save them after they are no longer referenced.
    124  *
    125  * Generic arenas:
    126  *
    127  * kmem_arena:
    128  *	Main arena controlling the kernel KVA used by other arenas.
    129  *
    130  * kmem_va_arena:
    131  *	Implements quantum caching in order to speedup allocations and
    132  *	reduce fragmentation.  The pool(9), unless created with a custom
    133  *	meta-data allocator, and kmem(9) subsystems use this arena.
    134  *
    135  * Arenas for meta-data allocations are used by vmem(9) and pool(9).
    136  * These arenas cannot use quantum cache.  However, kmem_va_meta_arena
    137  * compensates this by importing larger chunks from kmem_arena.
    138  *
    139  * kmem_va_meta_arena:
    140  *	Space for meta-data.
    141  *
    142  * kmem_meta_arena:
    143  *	Imports from kmem_va_meta_arena.  Allocations from this arena are
    144  *	backed with the pages.
    145  *
    146  * Arena stacking:
    147  *
    148  *	kmem_arena
    149  *		kmem_va_arena
    150  *		kmem_va_meta_arena
    151  *			kmem_meta_arena
    152  */
    153 
    154 #include <sys/cdefs.h>
    155 __KERNEL_RCSID(0, "$NetBSD: uvm_km.c,v 1.149 2019/12/01 14:43:26 ad Exp $");
    156 
    157 #include "opt_uvmhist.h"
    158 
    159 #include "opt_kmempages.h"
    160 
    161 #ifndef NKMEMPAGES
    162 #define NKMEMPAGES 0
    163 #endif
    164 
    165 /*
    166  * Defaults for lower and upper-bounds for the kmem_arena page count.
    167  * Can be overridden by kernel config options.
    168  */
    169 #ifndef NKMEMPAGES_MIN
    170 #define NKMEMPAGES_MIN NKMEMPAGES_MIN_DEFAULT
    171 #endif
    172 
    173 #ifndef NKMEMPAGES_MAX
    174 #define NKMEMPAGES_MAX NKMEMPAGES_MAX_DEFAULT
    175 #endif
    176 
    177 
    178 #include <sys/param.h>
    179 #include <sys/systm.h>
    180 #include <sys/proc.h>
    181 #include <sys/pool.h>
    182 #include <sys/vmem.h>
    183 #include <sys/vmem_impl.h>
    184 #include <sys/kmem.h>
    185 #include <sys/msan.h>
    186 
    187 #include <uvm/uvm.h>
    188 
    189 /*
    190  * global data structures
    191  */
    192 
    193 struct vm_map *kernel_map = NULL;
    194 
    195 /*
    196  * local data structues
    197  */
    198 
    199 static struct vm_map		kernel_map_store;
    200 static struct vm_map_entry	kernel_image_mapent_store;
    201 static struct vm_map_entry	kernel_kmem_mapent_store;
    202 
    203 int nkmempages = 0;
    204 vaddr_t kmembase;
    205 vsize_t kmemsize;
    206 
    207 static struct vmem kmem_arena_store;
    208 vmem_t *kmem_arena = NULL;
    209 static struct vmem kmem_va_arena_store;
    210 vmem_t *kmem_va_arena;
    211 
    212 /*
    213  * kmeminit_nkmempages: calculate the size of kmem_arena.
    214  */
    215 void
    216 kmeminit_nkmempages(void)
    217 {
    218 	int npages;
    219 
    220 	if (nkmempages != 0) {
    221 		/*
    222 		 * It's already been set (by us being here before)
    223 		 * bail out now;
    224 		 */
    225 		return;
    226 	}
    227 
    228 #if defined(KMSAN)
    229 	npages = (physmem / 8);
    230 #elif defined(PMAP_MAP_POOLPAGE)
    231 	npages = (physmem / 4);
    232 #else
    233 	npages = (physmem / 3) * 2;
    234 #endif /* defined(PMAP_MAP_POOLPAGE) */
    235 
    236 #ifndef NKMEMPAGES_MAX_UNLIMITED
    237 	if (npages > NKMEMPAGES_MAX)
    238 		npages = NKMEMPAGES_MAX;
    239 #endif
    240 
    241 	if (npages < NKMEMPAGES_MIN)
    242 		npages = NKMEMPAGES_MIN;
    243 
    244 	nkmempages = npages;
    245 }
    246 
    247 /*
    248  * uvm_km_bootstrap: init kernel maps and objects to reflect reality (i.e.
    249  * KVM already allocated for text, data, bss, and static data structures).
    250  *
    251  * => KVM is defined by VM_MIN_KERNEL_ADDRESS/VM_MAX_KERNEL_ADDRESS.
    252  *    we assume that [vmin -> start] has already been allocated and that
    253  *    "end" is the end.
    254  */
    255 
    256 void
    257 uvm_km_bootstrap(vaddr_t start, vaddr_t end)
    258 {
    259 	bool kmem_arena_small;
    260 	vaddr_t base = VM_MIN_KERNEL_ADDRESS;
    261 	struct uvm_map_args args;
    262 	int error;
    263 
    264 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
    265 	UVMHIST_LOG(maphist, "start=%#jx end=%#jx", start, end, 0,0);
    266 
    267 	kmeminit_nkmempages();
    268 	kmemsize = (vsize_t)nkmempages * PAGE_SIZE;
    269 	kmem_arena_small = kmemsize < 64 * 1024 * 1024;
    270 
    271 	UVMHIST_LOG(maphist, "kmemsize=%#jx", kmemsize, 0,0,0);
    272 
    273 	/*
    274 	 * next, init kernel memory objects.
    275 	 */
    276 
    277 	/* kernel_object: for pageable anonymous kernel memory */
    278 	uvm_kernel_object = uao_create(VM_MAX_KERNEL_ADDRESS -
    279 				VM_MIN_KERNEL_ADDRESS, UAO_FLAG_KERNOBJ);
    280 
    281 	/*
    282 	 * init the map and reserve any space that might already
    283 	 * have been allocated kernel space before installing.
    284 	 */
    285 
    286 	uvm_map_setup(&kernel_map_store, base, end, VM_MAP_PAGEABLE);
    287 	kernel_map_store.pmap = pmap_kernel();
    288 	if (start != base) {
    289 		error = uvm_map_prepare(&kernel_map_store,
    290 		    base, start - base,
    291 		    NULL, UVM_UNKNOWN_OFFSET, 0,
    292 		    UVM_MAPFLAG(UVM_PROT_ALL, UVM_PROT_ALL, UVM_INH_NONE,
    293 		    		UVM_ADV_RANDOM, UVM_FLAG_FIXED), &args);
    294 		if (!error) {
    295 			kernel_image_mapent_store.flags =
    296 			    UVM_MAP_KERNEL | UVM_MAP_STATIC | UVM_MAP_NOMERGE;
    297 			error = uvm_map_enter(&kernel_map_store, &args,
    298 			    &kernel_image_mapent_store);
    299 		}
    300 
    301 		if (error)
    302 			panic(
    303 			    "uvm_km_bootstrap: could not reserve space for kernel");
    304 
    305 		kmembase = args.uma_start + args.uma_size;
    306 	} else {
    307 		kmembase = base;
    308 	}
    309 
    310 	error = uvm_map_prepare(&kernel_map_store,
    311 	    kmembase, kmemsize,
    312 	    NULL, UVM_UNKNOWN_OFFSET, 0,
    313 	    UVM_MAPFLAG(UVM_PROT_ALL, UVM_PROT_ALL, UVM_INH_NONE,
    314 	    		UVM_ADV_RANDOM, UVM_FLAG_FIXED), &args);
    315 	if (!error) {
    316 		kernel_kmem_mapent_store.flags =
    317 		    UVM_MAP_KERNEL | UVM_MAP_STATIC | UVM_MAP_NOMERGE;
    318 		error = uvm_map_enter(&kernel_map_store, &args,
    319 		    &kernel_kmem_mapent_store);
    320 	}
    321 
    322 	if (error)
    323 		panic("uvm_km_bootstrap: could not reserve kernel kmem");
    324 
    325 	/*
    326 	 * install!
    327 	 */
    328 
    329 	kernel_map = &kernel_map_store;
    330 
    331 	pool_subsystem_init();
    332 
    333 	kmem_arena = vmem_init(&kmem_arena_store, "kmem",
    334 	    kmembase, kmemsize, PAGE_SIZE, NULL, NULL, NULL,
    335 	    0, VM_NOSLEEP | VM_BOOTSTRAP, IPL_VM);
    336 #ifdef PMAP_GROWKERNEL
    337 	/*
    338 	 * kmem_arena VA allocations happen independently of uvm_map.
    339 	 * grow kernel to accommodate the kmem_arena.
    340 	 */
    341 	if (uvm_maxkaddr < kmembase + kmemsize) {
    342 		uvm_maxkaddr = pmap_growkernel(kmembase + kmemsize);
    343 		KASSERTMSG(uvm_maxkaddr >= kmembase + kmemsize,
    344 		    "%#"PRIxVADDR" %#"PRIxVADDR" %#"PRIxVSIZE,
    345 		    uvm_maxkaddr, kmembase, kmemsize);
    346 	}
    347 #endif
    348 
    349 	vmem_subsystem_init(kmem_arena);
    350 
    351 	UVMHIST_LOG(maphist, "kmem vmem created (base=%#jx, size=%#jx",
    352 	    kmembase, kmemsize, 0,0);
    353 
    354 	kmem_va_arena = vmem_init(&kmem_va_arena_store, "kva",
    355 	    0, 0, PAGE_SIZE, vmem_alloc, vmem_free, kmem_arena,
    356 	    (kmem_arena_small ? 4 : VMEM_QCACHE_IDX_MAX) * PAGE_SIZE,
    357 	    VM_NOSLEEP, IPL_VM);
    358 
    359 	UVMHIST_LOG(maphist, "<- done", 0,0,0,0);
    360 }
    361 
    362 /*
    363  * uvm_km_init: init the kernel maps virtual memory caches
    364  * and start the pool/kmem allocator.
    365  */
    366 void
    367 uvm_km_init(void)
    368 {
    369 	kmem_init();
    370 }
    371 
    372 /*
    373  * uvm_km_suballoc: allocate a submap in the kernel map.   once a submap
    374  * is allocated all references to that area of VM must go through it.  this
    375  * allows the locking of VAs in kernel_map to be broken up into regions.
    376  *
    377  * => if `fixed' is true, *vmin specifies where the region described
    378  *   pager_map => used to map "buf" structures into kernel space
    379  *      by the submap must start
    380  * => if submap is non NULL we use that as the submap, otherwise we
    381  *	alloc a new map
    382  */
    383 
    384 struct vm_map *
    385 uvm_km_suballoc(struct vm_map *map, vaddr_t *vmin /* IN/OUT */,
    386     vaddr_t *vmax /* OUT */, vsize_t size, int flags, bool fixed,
    387     struct vm_map *submap)
    388 {
    389 	int mapflags = UVM_FLAG_NOMERGE | (fixed ? UVM_FLAG_FIXED : 0);
    390 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
    391 
    392 	KASSERT(vm_map_pmap(map) == pmap_kernel());
    393 
    394 	size = round_page(size);	/* round up to pagesize */
    395 
    396 	/*
    397 	 * first allocate a blank spot in the parent map
    398 	 */
    399 
    400 	if (uvm_map(map, vmin, size, NULL, UVM_UNKNOWN_OFFSET, 0,
    401 	    UVM_MAPFLAG(UVM_PROT_ALL, UVM_PROT_ALL, UVM_INH_NONE,
    402 	    UVM_ADV_RANDOM, mapflags)) != 0) {
    403 		panic("%s: unable to allocate space in parent map", __func__);
    404 	}
    405 
    406 	/*
    407 	 * set VM bounds (vmin is filled in by uvm_map)
    408 	 */
    409 
    410 	*vmax = *vmin + size;
    411 
    412 	/*
    413 	 * add references to pmap and create or init the submap
    414 	 */
    415 
    416 	pmap_reference(vm_map_pmap(map));
    417 	if (submap == NULL) {
    418 		submap = kmem_alloc(sizeof(*submap), KM_SLEEP);
    419 	}
    420 	uvm_map_setup(submap, *vmin, *vmax, flags);
    421 	submap->pmap = vm_map_pmap(map);
    422 
    423 	/*
    424 	 * now let uvm_map_submap plug in it...
    425 	 */
    426 
    427 	if (uvm_map_submap(map, *vmin, *vmax, submap) != 0)
    428 		panic("uvm_km_suballoc: submap allocation failed");
    429 
    430 	return(submap);
    431 }
    432 
    433 /*
    434  * uvm_km_pgremove: remove pages from a kernel uvm_object and KVA.
    435  */
    436 
    437 void
    438 uvm_km_pgremove(vaddr_t startva, vaddr_t endva)
    439 {
    440 	struct uvm_object * const uobj = uvm_kernel_object;
    441 	const voff_t start = startva - vm_map_min(kernel_map);
    442 	const voff_t end = endva - vm_map_min(kernel_map);
    443 	struct vm_page *pg;
    444 	voff_t curoff, nextoff;
    445 	int swpgonlydelta = 0;
    446 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
    447 
    448 	KASSERT(VM_MIN_KERNEL_ADDRESS <= startva);
    449 	KASSERT(startva < endva);
    450 	KASSERT(endva <= VM_MAX_KERNEL_ADDRESS);
    451 
    452 	mutex_enter(uobj->vmobjlock);
    453 	pmap_remove(pmap_kernel(), startva, endva);
    454 	for (curoff = start; curoff < end; curoff = nextoff) {
    455 		nextoff = curoff + PAGE_SIZE;
    456 		pg = uvm_pagelookup(uobj, curoff);
    457 		if (pg != NULL && pg->flags & PG_BUSY) {
    458 			pg->flags |= PG_WANTED;
    459 			UVM_UNLOCK_AND_WAIT(pg, uobj->vmobjlock, 0,
    460 				    "km_pgrm", 0);
    461 			mutex_enter(uobj->vmobjlock);
    462 			nextoff = curoff;
    463 			continue;
    464 		}
    465 
    466 		/*
    467 		 * free the swap slot, then the page.
    468 		 */
    469 
    470 		if (pg == NULL &&
    471 		    uao_find_swslot(uobj, curoff >> PAGE_SHIFT) > 0) {
    472 			swpgonlydelta++;
    473 		}
    474 		uao_dropswap(uobj, curoff >> PAGE_SHIFT);
    475 		if (pg != NULL) {
    476 			mutex_enter(&uvm_pageqlock);
    477 			uvm_pagefree(pg);
    478 			mutex_exit(&uvm_pageqlock);
    479 		}
    480 	}
    481 	mutex_exit(uobj->vmobjlock);
    482 
    483 	if (swpgonlydelta > 0) {
    484 		KASSERT(uvmexp.swpgonly >= swpgonlydelta);
    485 		atomic_add_int(&uvmexp.swpgonly, -swpgonlydelta);
    486 	}
    487 }
    488 
    489 
    490 /*
    491  * uvm_km_pgremove_intrsafe: like uvm_km_pgremove(), but for non object backed
    492  *    regions.
    493  *
    494  * => when you unmap a part of anonymous kernel memory you want to toss
    495  *    the pages right away.    (this is called from uvm_unmap_...).
    496  * => none of the pages will ever be busy, and none of them will ever
    497  *    be on the active or inactive queues (because they have no object).
    498  */
    499 
    500 void
    501 uvm_km_pgremove_intrsafe(struct vm_map *map, vaddr_t start, vaddr_t end)
    502 {
    503 #define __PGRM_BATCH 16
    504 	struct vm_page *pg;
    505 	paddr_t pa[__PGRM_BATCH];
    506 	int npgrm, i;
    507 	vaddr_t va, batch_vastart;
    508 
    509 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
    510 
    511 	KASSERT(VM_MAP_IS_KERNEL(map));
    512 	KASSERTMSG(vm_map_min(map) <= start,
    513 	    "vm_map_min(map) [%#"PRIxVADDR"] <= start [%#"PRIxVADDR"]"
    514 	    " (size=%#"PRIxVSIZE")",
    515 	    vm_map_min(map), start, end - start);
    516 	KASSERT(start < end);
    517 	KASSERT(end <= vm_map_max(map));
    518 
    519 	for (va = start; va < end;) {
    520 		batch_vastart = va;
    521 		/* create a batch of at most __PGRM_BATCH pages to free */
    522 		for (i = 0;
    523 		     i < __PGRM_BATCH && va < end;
    524 		     va += PAGE_SIZE) {
    525 			if (!pmap_extract(pmap_kernel(), va, &pa[i])) {
    526 				continue;
    527 			}
    528 			i++;
    529 		}
    530 		npgrm = i;
    531 		/* now remove the mappings */
    532 		pmap_kremove(batch_vastart, va - batch_vastart);
    533 		/* and free the pages */
    534 		for (i = 0; i < npgrm; i++) {
    535 			pg = PHYS_TO_VM_PAGE(pa[i]);
    536 			KASSERT(pg);
    537 			KASSERT(pg->uobject == NULL && pg->uanon == NULL);
    538 			KASSERT((pg->flags & PG_BUSY) == 0);
    539 			uvm_pagefree(pg);
    540 		}
    541 	}
    542 #undef __PGRM_BATCH
    543 }
    544 
    545 #if defined(DEBUG)
    546 void
    547 uvm_km_check_empty(struct vm_map *map, vaddr_t start, vaddr_t end)
    548 {
    549 	struct vm_page *pg;
    550 	vaddr_t va;
    551 	paddr_t pa;
    552 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
    553 
    554 	KDASSERT(VM_MAP_IS_KERNEL(map));
    555 	KDASSERT(vm_map_min(map) <= start);
    556 	KDASSERT(start < end);
    557 	KDASSERT(end <= vm_map_max(map));
    558 
    559 	for (va = start; va < end; va += PAGE_SIZE) {
    560 		if (pmap_extract(pmap_kernel(), va, &pa)) {
    561 			panic("uvm_km_check_empty: va %p has pa 0x%llx",
    562 			    (void *)va, (long long)pa);
    563 		}
    564 		mutex_enter(uvm_kernel_object->vmobjlock);
    565 		pg = uvm_pagelookup(uvm_kernel_object,
    566 		    va - vm_map_min(kernel_map));
    567 		mutex_exit(uvm_kernel_object->vmobjlock);
    568 		if (pg) {
    569 			panic("uvm_km_check_empty: "
    570 			    "has page hashed at %p", (const void *)va);
    571 		}
    572 	}
    573 }
    574 #endif /* defined(DEBUG) */
    575 
    576 /*
    577  * uvm_km_alloc: allocate an area of kernel memory.
    578  *
    579  * => NOTE: we can return 0 even if we can wait if there is not enough
    580  *	free VM space in the map... caller should be prepared to handle
    581  *	this case.
    582  * => we return KVA of memory allocated
    583  */
    584 
    585 vaddr_t
    586 uvm_km_alloc(struct vm_map *map, vsize_t size, vsize_t align, uvm_flag_t flags)
    587 {
    588 	vaddr_t kva, loopva;
    589 	vaddr_t offset;
    590 	vsize_t loopsize;
    591 	struct vm_page *pg;
    592 	struct uvm_object *obj;
    593 	int pgaflags;
    594 	vm_prot_t prot, vaprot;
    595 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
    596 
    597 	KASSERT(vm_map_pmap(map) == pmap_kernel());
    598 	KASSERT((flags & UVM_KMF_TYPEMASK) == UVM_KMF_WIRED ||
    599 		(flags & UVM_KMF_TYPEMASK) == UVM_KMF_PAGEABLE ||
    600 		(flags & UVM_KMF_TYPEMASK) == UVM_KMF_VAONLY);
    601 	KASSERT((flags & UVM_KMF_VAONLY) != 0 || (flags & UVM_KMF_COLORMATCH) == 0);
    602 	KASSERT((flags & UVM_KMF_COLORMATCH) == 0 || (flags & UVM_KMF_VAONLY) != 0);
    603 
    604 	/*
    605 	 * setup for call
    606 	 */
    607 
    608 	kva = vm_map_min(map);	/* hint */
    609 	size = round_page(size);
    610 	obj = (flags & UVM_KMF_PAGEABLE) ? uvm_kernel_object : NULL;
    611 	UVMHIST_LOG(maphist,"  (map=0x%#jx, obj=0x%#jx, size=0x%jx, flags=%jd)",
    612 	    (uintptr_t)map, (uintptr_t)obj, size, flags);
    613 
    614 	/*
    615 	 * allocate some virtual space
    616 	 */
    617 
    618 	vaprot = (flags & UVM_KMF_EXEC) ? UVM_PROT_ALL : UVM_PROT_RW;
    619 	if (__predict_false(uvm_map(map, &kva, size, obj, UVM_UNKNOWN_OFFSET,
    620 	    align, UVM_MAPFLAG(vaprot, UVM_PROT_ALL, UVM_INH_NONE,
    621 	    UVM_ADV_RANDOM,
    622 	    (flags & (UVM_KMF_TRYLOCK | UVM_KMF_NOWAIT | UVM_KMF_WAITVA
    623 	     | UVM_KMF_COLORMATCH)))) != 0)) {
    624 		UVMHIST_LOG(maphist, "<- done (no VM)",0,0,0,0);
    625 		return(0);
    626 	}
    627 
    628 	/*
    629 	 * if all we wanted was VA, return now
    630 	 */
    631 
    632 	if (flags & (UVM_KMF_VAONLY | UVM_KMF_PAGEABLE)) {
    633 		UVMHIST_LOG(maphist,"<- done valloc (kva=0x%jx)", kva,0,0,0);
    634 		return(kva);
    635 	}
    636 
    637 	/*
    638 	 * recover object offset from virtual address
    639 	 */
    640 
    641 	offset = kva - vm_map_min(kernel_map);
    642 	UVMHIST_LOG(maphist, "  kva=0x%jx, offset=0x%jx", kva, offset,0,0);
    643 
    644 	/*
    645 	 * now allocate and map in the memory... note that we are the only ones
    646 	 * whom should ever get a handle on this area of VM.
    647 	 */
    648 
    649 	loopva = kva;
    650 	loopsize = size;
    651 
    652 	pgaflags = UVM_FLAG_COLORMATCH;
    653 	if (flags & UVM_KMF_NOWAIT)
    654 		pgaflags |= UVM_PGA_USERESERVE;
    655 	if (flags & UVM_KMF_ZERO)
    656 		pgaflags |= UVM_PGA_ZERO;
    657 	prot = VM_PROT_READ | VM_PROT_WRITE;
    658 	if (flags & UVM_KMF_EXEC)
    659 		prot |= VM_PROT_EXECUTE;
    660 	while (loopsize) {
    661 		KASSERTMSG(!pmap_extract(pmap_kernel(), loopva, NULL),
    662 		    "loopva=%#"PRIxVADDR, loopva);
    663 
    664 		pg = uvm_pagealloc_strat(NULL, offset, NULL, pgaflags,
    665 #ifdef UVM_KM_VMFREELIST
    666 		   UVM_PGA_STRAT_ONLY, UVM_KM_VMFREELIST
    667 #else
    668 		   UVM_PGA_STRAT_NORMAL, 0
    669 #endif
    670 		   );
    671 
    672 		/*
    673 		 * out of memory?
    674 		 */
    675 
    676 		if (__predict_false(pg == NULL)) {
    677 			if ((flags & UVM_KMF_NOWAIT) ||
    678 			    ((flags & UVM_KMF_CANFAIL) && !uvm_reclaimable())) {
    679 				/* free everything! */
    680 				uvm_km_free(map, kva, size,
    681 				    flags & UVM_KMF_TYPEMASK);
    682 				return (0);
    683 			} else {
    684 				uvm_wait("km_getwait2");	/* sleep here */
    685 				continue;
    686 			}
    687 		}
    688 
    689 		pg->flags &= ~PG_BUSY;	/* new page */
    690 		UVM_PAGE_OWN(pg, NULL);
    691 
    692 		/*
    693 		 * map it in
    694 		 */
    695 
    696 		pmap_kenter_pa(loopva, VM_PAGE_TO_PHYS(pg),
    697 		    prot, PMAP_KMPAGE);
    698 		loopva += PAGE_SIZE;
    699 		offset += PAGE_SIZE;
    700 		loopsize -= PAGE_SIZE;
    701 	}
    702 
    703 	pmap_update(pmap_kernel());
    704 
    705 	if ((flags & UVM_KMF_ZERO) == 0) {
    706 		kleak_fill_area((void *)kva, size);
    707 		kmsan_orig((void *)kva, size, KMSAN_TYPE_UVM, __RET_ADDR);
    708 		kmsan_mark((void *)kva, size, KMSAN_STATE_UNINIT);
    709 	}
    710 
    711 	UVMHIST_LOG(maphist,"<- done (kva=0x%jx)", kva,0,0,0);
    712 	return(kva);
    713 }
    714 
    715 /*
    716  * uvm_km_protect: change the protection of an allocated area
    717  */
    718 
    719 int
    720 uvm_km_protect(struct vm_map *map, vaddr_t addr, vsize_t size, vm_prot_t prot)
    721 {
    722 	return uvm_map_protect(map, addr, addr + round_page(size), prot, false);
    723 }
    724 
    725 /*
    726  * uvm_km_free: free an area of kernel memory
    727  */
    728 
    729 void
    730 uvm_km_free(struct vm_map *map, vaddr_t addr, vsize_t size, uvm_flag_t flags)
    731 {
    732 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
    733 
    734 	KASSERT((flags & UVM_KMF_TYPEMASK) == UVM_KMF_WIRED ||
    735 		(flags & UVM_KMF_TYPEMASK) == UVM_KMF_PAGEABLE ||
    736 		(flags & UVM_KMF_TYPEMASK) == UVM_KMF_VAONLY);
    737 	KASSERT((addr & PAGE_MASK) == 0);
    738 	KASSERT(vm_map_pmap(map) == pmap_kernel());
    739 
    740 	size = round_page(size);
    741 
    742 	if (flags & UVM_KMF_PAGEABLE) {
    743 		uvm_km_pgremove(addr, addr + size);
    744 	} else if (flags & UVM_KMF_WIRED) {
    745 		/*
    746 		 * Note: uvm_km_pgremove_intrsafe() extracts mapping, thus
    747 		 * remove it after.  See comment below about KVA visibility.
    748 		 */
    749 		uvm_km_pgremove_intrsafe(map, addr, addr + size);
    750 	}
    751 
    752 	/*
    753 	 * Note: uvm_unmap_remove() calls pmap_update() for us, before
    754 	 * KVA becomes globally available.
    755 	 */
    756 
    757 	uvm_unmap1(map, addr, addr + size, UVM_FLAG_VAONLY);
    758 }
    759 
    760 /* Sanity; must specify both or none. */
    761 #if (defined(PMAP_MAP_POOLPAGE) || defined(PMAP_UNMAP_POOLPAGE)) && \
    762     (!defined(PMAP_MAP_POOLPAGE) || !defined(PMAP_UNMAP_POOLPAGE))
    763 #error Must specify MAP and UNMAP together.
    764 #endif
    765 
    766 int
    767 uvm_km_kmem_alloc(vmem_t *vm, vmem_size_t size, vm_flag_t flags,
    768     vmem_addr_t *addr)
    769 {
    770 	struct vm_page *pg;
    771 	vmem_addr_t va;
    772 	int rc;
    773 	vaddr_t loopva;
    774 	vsize_t loopsize;
    775 
    776 	size = round_page(size);
    777 
    778 #if defined(PMAP_MAP_POOLPAGE)
    779 	if (size == PAGE_SIZE) {
    780 again:
    781 #ifdef PMAP_ALLOC_POOLPAGE
    782 		pg = PMAP_ALLOC_POOLPAGE((flags & VM_SLEEP) ?
    783 		   0 : UVM_PGA_USERESERVE);
    784 #else
    785 		pg = uvm_pagealloc(NULL, 0, NULL,
    786 		   (flags & VM_SLEEP) ? 0 : UVM_PGA_USERESERVE);
    787 #endif /* PMAP_ALLOC_POOLPAGE */
    788 		if (__predict_false(pg == NULL)) {
    789 			if (flags & VM_SLEEP) {
    790 				uvm_wait("plpg");
    791 				goto again;
    792 			}
    793 			return ENOMEM;
    794 		}
    795 		va = PMAP_MAP_POOLPAGE(VM_PAGE_TO_PHYS(pg));
    796 		KASSERT(va != 0);
    797 		*addr = va;
    798 		return 0;
    799 	}
    800 #endif /* PMAP_MAP_POOLPAGE */
    801 
    802 	rc = vmem_alloc(vm, size, flags, &va);
    803 	if (rc != 0)
    804 		return rc;
    805 
    806 #ifdef PMAP_GROWKERNEL
    807 	/*
    808 	 * These VA allocations happen independently of uvm_map
    809 	 * so this allocation must not extend beyond the current limit.
    810 	 */
    811 	KASSERTMSG(uvm_maxkaddr >= va + size,
    812 	    "%#"PRIxVADDR" %#"PRIxPTR" %#zx",
    813 	    uvm_maxkaddr, va, size);
    814 #endif
    815 
    816 	loopva = va;
    817 	loopsize = size;
    818 
    819 	while (loopsize) {
    820 		paddr_t pa __diagused;
    821 		KASSERTMSG(!pmap_extract(pmap_kernel(), loopva, &pa),
    822 		    "loopva=%#"PRIxVADDR" loopsize=%#"PRIxVSIZE
    823 		    " pa=%#"PRIxPADDR" vmem=%p",
    824 		    loopva, loopsize, pa, vm);
    825 
    826 		pg = uvm_pagealloc(NULL, loopva, NULL,
    827 		    UVM_FLAG_COLORMATCH
    828 		    | ((flags & VM_SLEEP) ? 0 : UVM_PGA_USERESERVE));
    829 		if (__predict_false(pg == NULL)) {
    830 			if (flags & VM_SLEEP) {
    831 				uvm_wait("plpg");
    832 				continue;
    833 			} else {
    834 				uvm_km_pgremove_intrsafe(kernel_map, va,
    835 				    va + size);
    836 				vmem_free(vm, va, size);
    837 				return ENOMEM;
    838 			}
    839 		}
    840 
    841 		pg->flags &= ~PG_BUSY;	/* new page */
    842 		UVM_PAGE_OWN(pg, NULL);
    843 		pmap_kenter_pa(loopva, VM_PAGE_TO_PHYS(pg),
    844 		    VM_PROT_READ|VM_PROT_WRITE, PMAP_KMPAGE);
    845 
    846 		loopva += PAGE_SIZE;
    847 		loopsize -= PAGE_SIZE;
    848 	}
    849 	pmap_update(pmap_kernel());
    850 
    851 	*addr = va;
    852 
    853 	return 0;
    854 }
    855 
    856 void
    857 uvm_km_kmem_free(vmem_t *vm, vmem_addr_t addr, size_t size)
    858 {
    859 
    860 	size = round_page(size);
    861 #if defined(PMAP_UNMAP_POOLPAGE)
    862 	if (size == PAGE_SIZE) {
    863 		paddr_t pa;
    864 
    865 		pa = PMAP_UNMAP_POOLPAGE(addr);
    866 		uvm_pagefree(PHYS_TO_VM_PAGE(pa));
    867 		return;
    868 	}
    869 #endif /* PMAP_UNMAP_POOLPAGE */
    870 	uvm_km_pgremove_intrsafe(kernel_map, addr, addr + size);
    871 	pmap_update(pmap_kernel());
    872 
    873 	vmem_free(vm, addr, size);
    874 }
    875 
    876 bool
    877 uvm_km_va_starved_p(void)
    878 {
    879 	vmem_size_t total;
    880 	vmem_size_t free;
    881 
    882 	if (kmem_arena == NULL)
    883 		return false;
    884 
    885 	total = vmem_size(kmem_arena, VMEM_ALLOC|VMEM_FREE);
    886 	free = vmem_size(kmem_arena, VMEM_FREE);
    887 
    888 	return (free < (total / 10));
    889 }
    890