Home | History | Annotate | Line # | Download | only in uvm
uvm_km.c revision 1.126
      1 /*	$NetBSD: uvm_km.c,v 1.126 2012/06/02 08:42:37 para 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 a fixed map entry
     93  * within the kernel_map and 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  * kmem_arena: main arena controlling the kernel kva used by other arenas.
    126  * kmem_va_arena: it utilizes quantum caching for fast allocations and to
    127  *   lower fragmentation. the pool and kmem allocate from this arena
    128  *   except for some pool meta-data.
    129  *
    130  * arenas for metadata allocations used by vmem(9) and pool(9)
    131  * note: these arenas can't use quantum caching, the kmem_va_meta_arena
    132  *   compensates for this by importing larger chunks from kmem_arena.
    133  *
    134  * kmem_va_meta_arena: space for metadata is allocated from this arena.
    135  * kmem_meta_arena: imports from kmem_va_meta_arena.
    136  *   allocations from this arena are backed with vm_pages.
    137  *
    138  * arena stacking:
    139  * kmem_arena
    140  *   kmem_va_arena
    141  *   kmem_va_meta_arena
    142  *     kmem_meta_arena
    143  *
    144  */
    145 
    146 #include <sys/cdefs.h>
    147 __KERNEL_RCSID(0, "$NetBSD: uvm_km.c,v 1.126 2012/06/02 08:42:37 para Exp $");
    148 
    149 #include "opt_uvmhist.h"
    150 
    151 #include "opt_kmempages.h"
    152 
    153 #ifndef NKMEMPAGES
    154 #define NKMEMPAGES 0
    155 #endif
    156 
    157 /*
    158  * Defaults for lower and upper-bounds for the kmem_arena page count.
    159  * Can be overridden by kernel config options.
    160  */
    161 #ifndef NKMEMPAGES_MIN
    162 #define NKMEMPAGES_MIN NKMEMPAGES_MIN_DEFAULT
    163 #endif
    164 
    165 #ifndef NKMEMPAGES_MAX
    166 #define NKMEMPAGES_MAX NKMEMPAGES_MAX_DEFAULT
    167 #endif
    168 
    169 
    170 #include <sys/param.h>
    171 #include <sys/systm.h>
    172 #include <sys/proc.h>
    173 #include <sys/pool.h>
    174 #include <sys/vmem.h>
    175 #include <sys/kmem.h>
    176 
    177 #include <uvm/uvm.h>
    178 
    179 /*
    180  * global data structures
    181  */
    182 
    183 struct vm_map *kernel_map = NULL;
    184 
    185 /*
    186  * local data structues
    187  */
    188 
    189 static struct vm_map		kernel_map_store;
    190 static struct vm_map_entry	kernel_image_mapent_store;
    191 static struct vm_map_entry	kernel_kmem_mapent_store;
    192 
    193 int nkmempages = 0;
    194 vaddr_t kmembase;
    195 vsize_t kmemsize;
    196 
    197 vmem_t *kmem_arena;
    198 vmem_t *kmem_va_arena;
    199 
    200 /*
    201  * kmeminit_nkmempages: calculate the size of kmem_arena.
    202  */
    203 void
    204 kmeminit_nkmempages(void)
    205 {
    206 	int npages;
    207 
    208 	if (nkmempages != 0) {
    209 		/*
    210 		 * It's already been set (by us being here before)
    211 		 * bail out now;
    212 		 */
    213 		return;
    214 	}
    215 
    216 #if defined(PMAP_MAP_POOLPAGE)
    217 	npages = (physmem / 4);
    218 #else
    219 	npages = (physmem / 3) * 2;
    220 #endif /* defined(PMAP_MAP_POOLPAGE) */
    221 
    222 #ifndef NKMEMPAGES_MAX_UNLIMITED
    223 	if (npages > NKMEMPAGES_MAX)
    224 		npages = NKMEMPAGES_MAX;
    225 #endif
    226 
    227 	if (npages < NKMEMPAGES_MIN)
    228 		npages = NKMEMPAGES_MIN;
    229 
    230 	nkmempages = npages;
    231 }
    232 
    233 /*
    234  * uvm_km_bootstrap: init kernel maps and objects to reflect reality (i.e.
    235  * KVM already allocated for text, data, bss, and static data structures).
    236  *
    237  * => KVM is defined by VM_MIN_KERNEL_ADDRESS/VM_MAX_KERNEL_ADDRESS.
    238  *    we assume that [vmin -> start] has already been allocated and that
    239  *    "end" is the end.
    240  */
    241 
    242 void
    243 uvm_km_bootstrap(vaddr_t start, vaddr_t end)
    244 {
    245 	bool kmem_arena_small;
    246 	vaddr_t base = VM_MIN_KERNEL_ADDRESS;
    247 	struct uvm_map_args args;
    248 	int error;
    249 
    250 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
    251 	UVMHIST_LOG(maphist, "start=%"PRIxVADDR" end=%#"PRIxVADDR,
    252 	    start, end, 0,0);
    253 
    254 	kmeminit_nkmempages();
    255 	kmemsize = (vsize_t)nkmempages * PAGE_SIZE;
    256 	kmem_arena_small = kmemsize < 64 * 1024 * 1024;
    257 
    258 	UVMHIST_LOG(maphist, "kmemsize=%#"PRIxVSIZE, kmemsize, 0,0,0);
    259 
    260 	/*
    261 	 * next, init kernel memory objects.
    262 	 */
    263 
    264 	/* kernel_object: for pageable anonymous kernel memory */
    265 	uvm_kernel_object = uao_create(VM_MAX_KERNEL_ADDRESS -
    266 				VM_MIN_KERNEL_ADDRESS, UAO_FLAG_KERNOBJ);
    267 
    268 	/*
    269 	 * init the map and reserve any space that might already
    270 	 * have been allocated kernel space before installing.
    271 	 */
    272 
    273 	uvm_map_setup(&kernel_map_store, base, end, VM_MAP_PAGEABLE);
    274 	kernel_map_store.pmap = pmap_kernel();
    275 	if (start != base) {
    276 		error = uvm_map_prepare(&kernel_map_store,
    277 		    base, start - base,
    278 		    NULL, UVM_UNKNOWN_OFFSET, 0,
    279 		    UVM_MAPFLAG(UVM_PROT_ALL, UVM_PROT_ALL, UVM_INH_NONE,
    280 		    		UVM_ADV_RANDOM, UVM_FLAG_FIXED), &args);
    281 		if (!error) {
    282 			kernel_image_mapent_store.flags =
    283 			    UVM_MAP_KERNEL | UVM_MAP_STATIC | UVM_MAP_NOMERGE;
    284 			error = uvm_map_enter(&kernel_map_store, &args,
    285 			    &kernel_image_mapent_store);
    286 		}
    287 
    288 		if (error)
    289 			panic(
    290 			    "uvm_km_bootstrap: could not reserve space for kernel");
    291 
    292 		kmembase = args.uma_start + args.uma_size;
    293 	} else {
    294 		kmembase = base;
    295 	}
    296 
    297 	error = uvm_map_prepare(&kernel_map_store,
    298 	    kmembase, kmemsize,
    299 	    NULL, UVM_UNKNOWN_OFFSET, 0,
    300 	    UVM_MAPFLAG(UVM_PROT_ALL, UVM_PROT_ALL, UVM_INH_NONE,
    301 	    		UVM_ADV_RANDOM, UVM_FLAG_FIXED), &args);
    302 	if (!error) {
    303 		kernel_kmem_mapent_store.flags =
    304 		    UVM_MAP_KERNEL | UVM_MAP_STATIC | UVM_MAP_NOMERGE;
    305 		error = uvm_map_enter(&kernel_map_store, &args,
    306 		    &kernel_kmem_mapent_store);
    307 	}
    308 
    309 	if (error)
    310 		panic("uvm_km_bootstrap: could not reserve kernel kmem");
    311 
    312 	/*
    313 	 * install!
    314 	 */
    315 
    316 	kernel_map = &kernel_map_store;
    317 
    318 	pool_subsystem_init();
    319 	vmem_bootstrap();
    320 
    321 	kmem_arena = vmem_create("kmem", kmembase, kmemsize, PAGE_SIZE,
    322 	    NULL, NULL, NULL,
    323 	    0, VM_NOSLEEP | VM_BOOTSTRAP, IPL_VM);
    324 
    325 	vmem_init(kmem_arena);
    326 
    327 	UVMHIST_LOG(maphist, "kmem vmem created (base=%#"PRIxVADDR
    328 	    ", size=%#"PRIxVSIZE, kmembase, kmemsize, 0,0);
    329 
    330 	kmem_va_arena = vmem_create("kva", 0, 0, PAGE_SIZE,
    331 	    vmem_alloc, vmem_free, kmem_arena,
    332 	    (kmem_arena_small ? 4 : 8) * PAGE_SIZE,
    333 	    VM_NOSLEEP | VM_BOOTSTRAP, IPL_VM);
    334 
    335 	UVMHIST_LOG(maphist, "<- done", 0,0,0,0);
    336 }
    337 
    338 /*
    339  * uvm_km_init: init the kernel maps virtual memory caches
    340  * and start the pool/kmem allocator.
    341  */
    342 void
    343 uvm_km_init(void)
    344 {
    345 
    346 	kmem_init();
    347 
    348 	kmeminit(); // killme
    349 }
    350 
    351 /*
    352  * uvm_km_suballoc: allocate a submap in the kernel map.   once a submap
    353  * is allocated all references to that area of VM must go through it.  this
    354  * allows the locking of VAs in kernel_map to be broken up into regions.
    355  *
    356  * => if `fixed' is true, *vmin specifies where the region described
    357  *   pager_map => used to map "buf" structures into kernel space
    358  *      by the submap must start
    359  * => if submap is non NULL we use that as the submap, otherwise we
    360  *	alloc a new map
    361  */
    362 
    363 struct vm_map *
    364 uvm_km_suballoc(struct vm_map *map, vaddr_t *vmin /* IN/OUT */,
    365     vaddr_t *vmax /* OUT */, vsize_t size, int flags, bool fixed,
    366     struct vm_map *submap)
    367 {
    368 	int mapflags = UVM_FLAG_NOMERGE | (fixed ? UVM_FLAG_FIXED : 0);
    369 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
    370 
    371 	KASSERT(vm_map_pmap(map) == pmap_kernel());
    372 
    373 	size = round_page(size);	/* round up to pagesize */
    374 
    375 	/*
    376 	 * first allocate a blank spot in the parent map
    377 	 */
    378 
    379 	if (uvm_map(map, vmin, size, NULL, UVM_UNKNOWN_OFFSET, 0,
    380 	    UVM_MAPFLAG(UVM_PROT_ALL, UVM_PROT_ALL, UVM_INH_NONE,
    381 	    UVM_ADV_RANDOM, mapflags)) != 0) {
    382 		panic("%s: unable to allocate space in parent map", __func__);
    383 	}
    384 
    385 	/*
    386 	 * set VM bounds (vmin is filled in by uvm_map)
    387 	 */
    388 
    389 	*vmax = *vmin + size;
    390 
    391 	/*
    392 	 * add references to pmap and create or init the submap
    393 	 */
    394 
    395 	pmap_reference(vm_map_pmap(map));
    396 	if (submap == NULL) {
    397 		submap = kmem_alloc(sizeof(*submap), KM_SLEEP);
    398 		if (submap == NULL)
    399 			panic("uvm_km_suballoc: unable to create submap");
    400 	}
    401 	uvm_map_setup(submap, *vmin, *vmax, flags);
    402 	submap->pmap = vm_map_pmap(map);
    403 
    404 	/*
    405 	 * now let uvm_map_submap plug in it...
    406 	 */
    407 
    408 	if (uvm_map_submap(map, *vmin, *vmax, submap) != 0)
    409 		panic("uvm_km_suballoc: submap allocation failed");
    410 
    411 	return(submap);
    412 }
    413 
    414 /*
    415  * uvm_km_pgremove: remove pages from a kernel uvm_object and KVA.
    416  */
    417 
    418 void
    419 uvm_km_pgremove(vaddr_t startva, vaddr_t endva)
    420 {
    421 	struct uvm_object * const uobj = uvm_kernel_object;
    422 	const voff_t start = startva - vm_map_min(kernel_map);
    423 	const voff_t end = endva - vm_map_min(kernel_map);
    424 	struct vm_page *pg;
    425 	voff_t curoff, nextoff;
    426 	int swpgonlydelta = 0;
    427 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
    428 
    429 	KASSERT(VM_MIN_KERNEL_ADDRESS <= startva);
    430 	KASSERT(startva < endva);
    431 	KASSERT(endva <= VM_MAX_KERNEL_ADDRESS);
    432 
    433 	mutex_enter(uobj->vmobjlock);
    434 	pmap_remove(pmap_kernel(), startva, endva);
    435 	for (curoff = start; curoff < end; curoff = nextoff) {
    436 		nextoff = curoff + PAGE_SIZE;
    437 		pg = uvm_pagelookup(uobj, curoff);
    438 		if (pg != NULL && pg->flags & PG_BUSY) {
    439 			pg->flags |= PG_WANTED;
    440 			UVM_UNLOCK_AND_WAIT(pg, uobj->vmobjlock, 0,
    441 				    "km_pgrm", 0);
    442 			mutex_enter(uobj->vmobjlock);
    443 			nextoff = curoff;
    444 			continue;
    445 		}
    446 
    447 		/*
    448 		 * free the swap slot, then the page.
    449 		 */
    450 
    451 		if (pg == NULL &&
    452 		    uao_find_swslot(uobj, curoff >> PAGE_SHIFT) > 0) {
    453 			swpgonlydelta++;
    454 		}
    455 		uao_dropswap(uobj, curoff >> PAGE_SHIFT);
    456 		if (pg != NULL) {
    457 			mutex_enter(&uvm_pageqlock);
    458 			uvm_pagefree(pg);
    459 			mutex_exit(&uvm_pageqlock);
    460 		}
    461 	}
    462 	mutex_exit(uobj->vmobjlock);
    463 
    464 	if (swpgonlydelta > 0) {
    465 		mutex_enter(&uvm_swap_data_lock);
    466 		KASSERT(uvmexp.swpgonly >= swpgonlydelta);
    467 		uvmexp.swpgonly -= swpgonlydelta;
    468 		mutex_exit(&uvm_swap_data_lock);
    469 	}
    470 }
    471 
    472 
    473 /*
    474  * uvm_km_pgremove_intrsafe: like uvm_km_pgremove(), but for non object backed
    475  *    regions.
    476  *
    477  * => when you unmap a part of anonymous kernel memory you want to toss
    478  *    the pages right away.    (this is called from uvm_unmap_...).
    479  * => none of the pages will ever be busy, and none of them will ever
    480  *    be on the active or inactive queues (because they have no object).
    481  */
    482 
    483 void
    484 uvm_km_pgremove_intrsafe(struct vm_map *map, vaddr_t start, vaddr_t end)
    485 {
    486 #define __PGRM_BATCH 16
    487 	struct vm_page *pg;
    488 	paddr_t pa[__PGRM_BATCH];
    489 	int npgrm, i;
    490 	vaddr_t va, batch_vastart;
    491 
    492 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
    493 
    494 	KASSERT(VM_MAP_IS_KERNEL(map));
    495 	KASSERT(vm_map_min(map) <= start);
    496 	KASSERT(start < end);
    497 	KASSERT(end <= vm_map_max(map));
    498 
    499 	for (va = start; va < end;) {
    500 		batch_vastart = va;
    501 		/* create a batch of at most __PGRM_BATCH pages to free */
    502 		for (i = 0;
    503 		     i < __PGRM_BATCH && va < end;
    504 		     va += PAGE_SIZE) {
    505 			if (!pmap_extract(pmap_kernel(), va, &pa[i])) {
    506 				continue;
    507 			}
    508 			i++;
    509 		}
    510 		npgrm = i;
    511 		/* now remove the mappings */
    512 		pmap_kremove(batch_vastart, va - batch_vastart);
    513 		/* and free the pages */
    514 		for (i = 0; i < npgrm; i++) {
    515 			pg = PHYS_TO_VM_PAGE(pa[i]);
    516 			KASSERT(pg);
    517 			KASSERT(pg->uobject == NULL && pg->uanon == NULL);
    518 			KASSERT((pg->flags & PG_BUSY) == 0);
    519 			uvm_pagefree(pg);
    520 		}
    521 	}
    522 #undef __PGRM_BATCH
    523 }
    524 
    525 #if defined(DEBUG)
    526 void
    527 uvm_km_check_empty(struct vm_map *map, vaddr_t start, vaddr_t end)
    528 {
    529 	struct vm_page *pg;
    530 	vaddr_t va;
    531 	paddr_t pa;
    532 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
    533 
    534 	KDASSERT(VM_MAP_IS_KERNEL(map));
    535 	KDASSERT(vm_map_min(map) <= start);
    536 	KDASSERT(start < end);
    537 	KDASSERT(end <= vm_map_max(map));
    538 
    539 	for (va = start; va < end; va += PAGE_SIZE) {
    540 		if (pmap_extract(pmap_kernel(), va, &pa)) {
    541 			panic("uvm_km_check_empty: va %p has pa 0x%llx",
    542 			    (void *)va, (long long)pa);
    543 		}
    544 		mutex_enter(uvm_kernel_object->vmobjlock);
    545 		pg = uvm_pagelookup(uvm_kernel_object,
    546 		    va - vm_map_min(kernel_map));
    547 		mutex_exit(uvm_kernel_object->vmobjlock);
    548 		if (pg) {
    549 			panic("uvm_km_check_empty: "
    550 			    "has page hashed at %p", (const void *)va);
    551 		}
    552 	}
    553 }
    554 #endif /* defined(DEBUG) */
    555 
    556 /*
    557  * uvm_km_alloc: allocate an area of kernel memory.
    558  *
    559  * => NOTE: we can return 0 even if we can wait if there is not enough
    560  *	free VM space in the map... caller should be prepared to handle
    561  *	this case.
    562  * => we return KVA of memory allocated
    563  */
    564 
    565 vaddr_t
    566 uvm_km_alloc(struct vm_map *map, vsize_t size, vsize_t align, uvm_flag_t flags)
    567 {
    568 	vaddr_t kva, loopva;
    569 	vaddr_t offset;
    570 	vsize_t loopsize;
    571 	struct vm_page *pg;
    572 	struct uvm_object *obj;
    573 	int pgaflags;
    574 	vm_prot_t prot;
    575 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
    576 
    577 	KASSERT(vm_map_pmap(map) == pmap_kernel());
    578 	KASSERT((flags & UVM_KMF_TYPEMASK) == UVM_KMF_WIRED ||
    579 		(flags & UVM_KMF_TYPEMASK) == UVM_KMF_PAGEABLE ||
    580 		(flags & UVM_KMF_TYPEMASK) == UVM_KMF_VAONLY);
    581 	KASSERT((flags & UVM_KMF_VAONLY) != 0 || (flags & UVM_KMF_COLORMATCH) == 0);
    582 	KASSERT((flags & UVM_KMF_COLORMATCH) == 0 || (flags & UVM_KMF_VAONLY) != 0);
    583 
    584 	/*
    585 	 * setup for call
    586 	 */
    587 
    588 	kva = vm_map_min(map);	/* hint */
    589 	size = round_page(size);
    590 	obj = (flags & UVM_KMF_PAGEABLE) ? uvm_kernel_object : NULL;
    591 	UVMHIST_LOG(maphist,"  (map=0x%x, obj=0x%x, size=0x%x, flags=%d)",
    592 		    map, obj, size, flags);
    593 
    594 	/*
    595 	 * allocate some virtual space
    596 	 */
    597 
    598 	if (__predict_false(uvm_map(map, &kva, size, obj, UVM_UNKNOWN_OFFSET,
    599 	    align, UVM_MAPFLAG(UVM_PROT_ALL, UVM_PROT_ALL, UVM_INH_NONE,
    600 	    UVM_ADV_RANDOM,
    601 	    (flags & (UVM_KMF_TRYLOCK | UVM_KMF_NOWAIT | UVM_KMF_WAITVA
    602 	     | UVM_KMF_COLORMATCH)))) != 0)) {
    603 		UVMHIST_LOG(maphist, "<- done (no VM)",0,0,0,0);
    604 		return(0);
    605 	}
    606 
    607 	/*
    608 	 * if all we wanted was VA, return now
    609 	 */
    610 
    611 	if (flags & (UVM_KMF_VAONLY | UVM_KMF_PAGEABLE)) {
    612 		UVMHIST_LOG(maphist,"<- done valloc (kva=0x%x)", kva,0,0,0);
    613 		return(kva);
    614 	}
    615 
    616 	/*
    617 	 * recover object offset from virtual address
    618 	 */
    619 
    620 	offset = kva - vm_map_min(kernel_map);
    621 	UVMHIST_LOG(maphist, "  kva=0x%x, offset=0x%x", kva, offset,0,0);
    622 
    623 	/*
    624 	 * now allocate and map in the memory... note that we are the only ones
    625 	 * whom should ever get a handle on this area of VM.
    626 	 */
    627 
    628 	loopva = kva;
    629 	loopsize = size;
    630 
    631 	pgaflags = UVM_FLAG_COLORMATCH;
    632 	if (flags & UVM_KMF_NOWAIT)
    633 		pgaflags |= UVM_PGA_USERESERVE;
    634 	if (flags & UVM_KMF_ZERO)
    635 		pgaflags |= UVM_PGA_ZERO;
    636 	prot = VM_PROT_READ | VM_PROT_WRITE;
    637 	if (flags & UVM_KMF_EXEC)
    638 		prot |= VM_PROT_EXECUTE;
    639 	while (loopsize) {
    640 		KASSERTMSG(!pmap_extract(pmap_kernel(), loopva, NULL),
    641 		    "loopva=%#"PRIxVADDR, loopva);
    642 
    643 		pg = uvm_pagealloc_strat(NULL, offset, NULL, pgaflags,
    644 #ifdef UVM_KM_VMFREELIST
    645 		   UVM_PGA_STRAT_ONLY, UVM_KM_VMFREELIST
    646 #else
    647 		   UVM_PGA_STRAT_NORMAL, 0
    648 #endif
    649 		   );
    650 
    651 		/*
    652 		 * out of memory?
    653 		 */
    654 
    655 		if (__predict_false(pg == NULL)) {
    656 			if ((flags & UVM_KMF_NOWAIT) ||
    657 			    ((flags & UVM_KMF_CANFAIL) && !uvm_reclaimable())) {
    658 				/* free everything! */
    659 				uvm_km_free(map, kva, size,
    660 				    flags & UVM_KMF_TYPEMASK);
    661 				return (0);
    662 			} else {
    663 				uvm_wait("km_getwait2");	/* sleep here */
    664 				continue;
    665 			}
    666 		}
    667 
    668 		pg->flags &= ~PG_BUSY;	/* new page */
    669 		UVM_PAGE_OWN(pg, NULL);
    670 
    671 		/*
    672 		 * map it in
    673 		 */
    674 
    675 		pmap_kenter_pa(loopva, VM_PAGE_TO_PHYS(pg),
    676 		    prot, PMAP_KMPAGE);
    677 		loopva += PAGE_SIZE;
    678 		offset += PAGE_SIZE;
    679 		loopsize -= PAGE_SIZE;
    680 	}
    681 
    682 	pmap_update(pmap_kernel());
    683 
    684 	UVMHIST_LOG(maphist,"<- done (kva=0x%x)", kva,0,0,0);
    685 	return(kva);
    686 }
    687 
    688 /*
    689  * uvm_km_free: free an area of kernel memory
    690  */
    691 
    692 void
    693 uvm_km_free(struct vm_map *map, vaddr_t addr, vsize_t size, uvm_flag_t flags)
    694 {
    695 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
    696 
    697 	KASSERT((flags & UVM_KMF_TYPEMASK) == UVM_KMF_WIRED ||
    698 		(flags & UVM_KMF_TYPEMASK) == UVM_KMF_PAGEABLE ||
    699 		(flags & UVM_KMF_TYPEMASK) == UVM_KMF_VAONLY);
    700 	KASSERT((addr & PAGE_MASK) == 0);
    701 	KASSERT(vm_map_pmap(map) == pmap_kernel());
    702 
    703 	size = round_page(size);
    704 
    705 	if (flags & UVM_KMF_PAGEABLE) {
    706 		uvm_km_pgremove(addr, addr + size);
    707 	} else if (flags & UVM_KMF_WIRED) {
    708 		/*
    709 		 * Note: uvm_km_pgremove_intrsafe() extracts mapping, thus
    710 		 * remove it after.  See comment below about KVA visibility.
    711 		 */
    712 		uvm_km_pgremove_intrsafe(map, addr, addr + size);
    713 	}
    714 
    715 	/*
    716 	 * Note: uvm_unmap_remove() calls pmap_update() for us, before
    717 	 * KVA becomes globally available.
    718 	 */
    719 
    720 	uvm_unmap1(map, addr, addr + size, UVM_FLAG_VAONLY);
    721 }
    722 
    723 /* Sanity; must specify both or none. */
    724 #if (defined(PMAP_MAP_POOLPAGE) || defined(PMAP_UNMAP_POOLPAGE)) && \
    725     (!defined(PMAP_MAP_POOLPAGE) || !defined(PMAP_UNMAP_POOLPAGE))
    726 #error Must specify MAP and UNMAP together.
    727 #endif
    728 
    729 int
    730 uvm_km_kmem_alloc(vmem_t *vm, vmem_size_t size, vm_flag_t flags,
    731     vmem_addr_t *addr)
    732 {
    733 	struct vm_page *pg;
    734 	vmem_addr_t va;
    735 	int rc;
    736 	vaddr_t loopva;
    737 	vsize_t loopsize;
    738 
    739 	size = round_page(size);
    740 
    741 #if defined(PMAP_MAP_POOLPAGE)
    742 	if (size == PAGE_SIZE) {
    743 again:
    744 #ifdef PMAP_ALLOC_POOLPAGE
    745 		pg = PMAP_ALLOC_POOLPAGE((flags & VM_SLEEP) ?
    746 		   0 : UVM_PGA_USERESERVE);
    747 #else
    748 		pg = uvm_pagealloc(NULL, 0, NULL,
    749 		   (flags & VM_SLEEP) ? 0 : UVM_PGA_USERESERVE);
    750 #endif /* PMAP_ALLOC_POOLPAGE */
    751 		if (__predict_false(pg == NULL)) {
    752 			if (flags & VM_SLEEP) {
    753 				uvm_wait("plpg");
    754 				goto again;
    755 			}
    756 			return ENOMEM;
    757 		}
    758 		va = PMAP_MAP_POOLPAGE(VM_PAGE_TO_PHYS(pg));
    759 		if (__predict_false(va == 0)) {
    760 			uvm_pagefree(pg);
    761 			return ENOMEM;
    762 		}
    763 		*addr = va;
    764 		return 0;
    765 	}
    766 #endif /* PMAP_MAP_POOLPAGE */
    767 
    768 	rc = vmem_alloc(vm, size, flags, &va);
    769 	if (rc != 0)
    770 		return rc;
    771 
    772 	loopva = va;
    773 	loopsize = size;
    774 
    775 	while (loopsize) {
    776 		KASSERTMSG(!pmap_extract(pmap_kernel(), loopva, NULL),
    777 		    "loopva=%#"PRIxVADDR" loopsize=%#"PRIxVSIZE" vmem=%p",
    778 		    loopva, loopsize, vm);
    779 
    780 		pg = uvm_pagealloc(NULL, loopva, NULL,
    781 		    UVM_FLAG_COLORMATCH
    782 		    | ((flags & VM_SLEEP) ? 0 : UVM_PGA_USERESERVE));
    783 		if (__predict_false(pg == NULL)) {
    784 			if (flags & VM_SLEEP) {
    785 				uvm_wait("plpg");
    786 				continue;
    787 			} else {
    788 				uvm_km_pgremove_intrsafe(kernel_map, va,
    789 				    va + size);
    790 				vmem_free(vm, va, size);
    791 				return ENOMEM;
    792 			}
    793 		}
    794 
    795 		pg->flags &= ~PG_BUSY;	/* new page */
    796 		UVM_PAGE_OWN(pg, NULL);
    797 		pmap_kenter_pa(loopva, VM_PAGE_TO_PHYS(pg),
    798 		    VM_PROT_READ|VM_PROT_WRITE, PMAP_KMPAGE);
    799 
    800 		loopva += PAGE_SIZE;
    801 		loopsize -= PAGE_SIZE;
    802 	}
    803 	pmap_update(pmap_kernel());
    804 
    805 	*addr = va;
    806 
    807 	return 0;
    808 }
    809 
    810 void
    811 uvm_km_kmem_free(vmem_t *vm, vmem_addr_t addr, size_t size)
    812 {
    813 
    814 	size = round_page(size);
    815 #if defined(PMAP_UNMAP_POOLPAGE)
    816 	if (size == PAGE_SIZE) {
    817 		paddr_t pa;
    818 
    819 		pa = PMAP_UNMAP_POOLPAGE(addr);
    820 		uvm_pagefree(PHYS_TO_VM_PAGE(pa));
    821 		return;
    822 	}
    823 #endif /* PMAP_UNMAP_POOLPAGE */
    824 	uvm_km_pgremove_intrsafe(kernel_map, addr, addr + size);
    825 	pmap_update(pmap_kernel());
    826 
    827 	vmem_free(vm, addr, size);
    828 }
    829 
    830 bool
    831 uvm_km_va_starved_p(void)
    832 {
    833 	vmem_size_t total;
    834 	vmem_size_t free;
    835 
    836 	total = vmem_size(kmem_arena, VMEM_ALLOC|VMEM_FREE);
    837 	free = vmem_size(kmem_arena, VMEM_FREE);
    838 
    839 	return (free < (total / 10));
    840 }
    841