Home | History | Annotate | Line # | Download | only in uvm
uvm_map.c revision 1.272
      1 /*	$NetBSD: uvm_map.c,v 1.272 2009/08/01 15:30:33 yamt 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. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *	This product includes software developed by Charles D. Cranor,
     23  *      Washington University, the University of California, Berkeley and
     24  *      its contributors.
     25  * 4. Neither the name of the University nor the names of its contributors
     26  *    may be used to endorse or promote products derived from this software
     27  *    without specific prior written permission.
     28  *
     29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     39  * SUCH DAMAGE.
     40  *
     41  *	@(#)vm_map.c    8.3 (Berkeley) 1/12/94
     42  * from: Id: uvm_map.c,v 1.1.2.27 1998/02/07 01:16:54 chs Exp
     43  *
     44  *
     45  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
     46  * All rights reserved.
     47  *
     48  * Permission to use, copy, modify and distribute this software and
     49  * its documentation is hereby granted, provided that both the copyright
     50  * notice and this permission notice appear in all copies of the
     51  * software, derivative works or modified versions, and any portions
     52  * thereof, and that both notices appear in supporting documentation.
     53  *
     54  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
     55  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
     56  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
     57  *
     58  * Carnegie Mellon requests users of this software to return to
     59  *
     60  *  Software Distribution Coordinator  or  Software.Distribution (at) CS.CMU.EDU
     61  *  School of Computer Science
     62  *  Carnegie Mellon University
     63  *  Pittsburgh PA 15213-3890
     64  *
     65  * any improvements or extensions that they make and grant Carnegie the
     66  * rights to redistribute these changes.
     67  */
     68 
     69 /*
     70  * uvm_map.c: uvm map operations
     71  */
     72 
     73 #include <sys/cdefs.h>
     74 __KERNEL_RCSID(0, "$NetBSD: uvm_map.c,v 1.272 2009/08/01 15:30:33 yamt Exp $");
     75 
     76 #include "opt_ddb.h"
     77 #include "opt_uvmhist.h"
     78 #include "opt_uvm.h"
     79 #include "opt_sysv.h"
     80 
     81 #include <sys/param.h>
     82 #include <sys/systm.h>
     83 #include <sys/mman.h>
     84 #include <sys/proc.h>
     85 #include <sys/malloc.h>
     86 #include <sys/pool.h>
     87 #include <sys/kernel.h>
     88 #include <sys/mount.h>
     89 #include <sys/vnode.h>
     90 #include <sys/lockdebug.h>
     91 #include <sys/atomic.h>
     92 
     93 #ifdef SYSVSHM
     94 #include <sys/shm.h>
     95 #endif
     96 
     97 #include <uvm/uvm.h>
     98 #include <uvm/uvm_readahead.h>
     99 
    100 #if defined(DDB) || defined(DEBUGPRINT)
    101 #include <uvm/uvm_ddb.h>
    102 #endif
    103 
    104 #if !defined(UVMMAP_COUNTERS)
    105 
    106 #define	UVMMAP_EVCNT_DEFINE(name)	/* nothing */
    107 #define UVMMAP_EVCNT_INCR(ev)		/* nothing */
    108 #define UVMMAP_EVCNT_DECR(ev)		/* nothing */
    109 
    110 #else /* defined(UVMMAP_NOCOUNTERS) */
    111 
    112 #include <sys/evcnt.h>
    113 #define	UVMMAP_EVCNT_DEFINE(name) \
    114 struct evcnt uvmmap_evcnt_##name = EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, \
    115     "uvmmap", #name); \
    116 EVCNT_ATTACH_STATIC(uvmmap_evcnt_##name);
    117 #define	UVMMAP_EVCNT_INCR(ev)		uvmmap_evcnt_##ev.ev_count++
    118 #define	UVMMAP_EVCNT_DECR(ev)		uvmmap_evcnt_##ev.ev_count--
    119 
    120 #endif /* defined(UVMMAP_NOCOUNTERS) */
    121 
    122 UVMMAP_EVCNT_DEFINE(ubackmerge)
    123 UVMMAP_EVCNT_DEFINE(uforwmerge)
    124 UVMMAP_EVCNT_DEFINE(ubimerge)
    125 UVMMAP_EVCNT_DEFINE(unomerge)
    126 UVMMAP_EVCNT_DEFINE(kbackmerge)
    127 UVMMAP_EVCNT_DEFINE(kforwmerge)
    128 UVMMAP_EVCNT_DEFINE(kbimerge)
    129 UVMMAP_EVCNT_DEFINE(knomerge)
    130 UVMMAP_EVCNT_DEFINE(map_call)
    131 UVMMAP_EVCNT_DEFINE(mlk_call)
    132 UVMMAP_EVCNT_DEFINE(mlk_hint)
    133 UVMMAP_EVCNT_DEFINE(mlk_list)
    134 UVMMAP_EVCNT_DEFINE(mlk_tree)
    135 UVMMAP_EVCNT_DEFINE(mlk_treeloop)
    136 UVMMAP_EVCNT_DEFINE(mlk_listloop)
    137 
    138 UVMMAP_EVCNT_DEFINE(uke_alloc)
    139 UVMMAP_EVCNT_DEFINE(uke_free)
    140 UVMMAP_EVCNT_DEFINE(ukh_alloc)
    141 UVMMAP_EVCNT_DEFINE(ukh_free)
    142 
    143 const char vmmapbsy[] = "vmmapbsy";
    144 
    145 /*
    146  * cache for vmspace structures.
    147  */
    148 
    149 static struct pool_cache uvm_vmspace_cache;
    150 
    151 /*
    152  * cache for dynamically-allocated map entries.
    153  */
    154 
    155 static struct pool_cache uvm_map_entry_cache;
    156 
    157 MALLOC_DEFINE(M_VMMAP, "VM map", "VM map structures");
    158 MALLOC_DEFINE(M_VMPMAP, "VM pmap", "VM pmap");
    159 
    160 #ifdef PMAP_GROWKERNEL
    161 /*
    162  * This global represents the end of the kernel virtual address
    163  * space.  If we want to exceed this, we must grow the kernel
    164  * virtual address space dynamically.
    165  *
    166  * Note, this variable is locked by kernel_map's lock.
    167  */
    168 vaddr_t uvm_maxkaddr;
    169 #endif
    170 
    171 /*
    172  * macros
    173  */
    174 
    175 /*
    176  * VM_MAP_USE_KMAPENT: determine if uvm_kmapent_alloc/free is used
    177  * for the vm_map.
    178  */
    179 extern struct vm_map *pager_map; /* XXX */
    180 #define	VM_MAP_USE_KMAPENT_FLAGS(flags) \
    181 	(((flags) & VM_MAP_INTRSAFE) != 0)
    182 #define	VM_MAP_USE_KMAPENT(map) \
    183 	(VM_MAP_USE_KMAPENT_FLAGS((map)->flags) || (map) == kernel_map)
    184 
    185 /*
    186  * UVM_ET_ISCOMPATIBLE: check some requirements for map entry merging
    187  */
    188 
    189 #define	UVM_ET_ISCOMPATIBLE(ent, type, uobj, meflags, \
    190     prot, maxprot, inh, adv, wire) \
    191 	((ent)->etype == (type) && \
    192 	(((ent)->flags ^ (meflags)) & (UVM_MAP_NOMERGE | UVM_MAP_QUANTUM)) \
    193 	== 0 && \
    194 	(ent)->object.uvm_obj == (uobj) && \
    195 	(ent)->protection == (prot) && \
    196 	(ent)->max_protection == (maxprot) && \
    197 	(ent)->inheritance == (inh) && \
    198 	(ent)->advice == (adv) && \
    199 	(ent)->wired_count == (wire))
    200 
    201 /*
    202  * uvm_map_entry_link: insert entry into a map
    203  *
    204  * => map must be locked
    205  */
    206 #define uvm_map_entry_link(map, after_where, entry) do { \
    207 	uvm_mapent_check(entry); \
    208 	(map)->nentries++; \
    209 	(entry)->prev = (after_where); \
    210 	(entry)->next = (after_where)->next; \
    211 	(entry)->prev->next = (entry); \
    212 	(entry)->next->prev = (entry); \
    213 	uvm_rb_insert((map), (entry)); \
    214 } while (/*CONSTCOND*/ 0)
    215 
    216 /*
    217  * uvm_map_entry_unlink: remove entry from a map
    218  *
    219  * => map must be locked
    220  */
    221 #define uvm_map_entry_unlink(map, entry) do { \
    222 	KASSERT((entry) != (map)->first_free); \
    223 	KASSERT((entry) != (map)->hint); \
    224 	uvm_mapent_check(entry); \
    225 	(map)->nentries--; \
    226 	(entry)->next->prev = (entry)->prev; \
    227 	(entry)->prev->next = (entry)->next; \
    228 	uvm_rb_remove((map), (entry)); \
    229 } while (/*CONSTCOND*/ 0)
    230 
    231 /*
    232  * SAVE_HINT: saves the specified entry as the hint for future lookups.
    233  *
    234  * => map need not be locked.
    235  */
    236 #define SAVE_HINT(map, check, value) do { \
    237 	if ((map)->hint == (check)) \
    238 		(map)->hint = (value); \
    239 } while (/*CONSTCOND*/ 0)
    240 
    241 /*
    242  * clear_hints: ensure that hints don't point to the entry.
    243  *
    244  * => map must be write-locked.
    245  */
    246 static void
    247 clear_hints(struct vm_map *map, struct vm_map_entry *ent)
    248 {
    249 
    250 	SAVE_HINT(map, ent, ent->prev);
    251 	if (map->first_free == ent) {
    252 		map->first_free = ent->prev;
    253 	}
    254 }
    255 
    256 /*
    257  * VM_MAP_RANGE_CHECK: check and correct range
    258  *
    259  * => map must at least be read locked
    260  */
    261 
    262 #define VM_MAP_RANGE_CHECK(map, start, end) do { \
    263 	if (start < vm_map_min(map))		\
    264 		start = vm_map_min(map);	\
    265 	if (end > vm_map_max(map))		\
    266 		end = vm_map_max(map);		\
    267 	if (start > end)			\
    268 		start = end;			\
    269 } while (/*CONSTCOND*/ 0)
    270 
    271 /*
    272  * local prototypes
    273  */
    274 
    275 static struct vm_map_entry *
    276 		uvm_mapent_alloc(struct vm_map *, int);
    277 static struct vm_map_entry *
    278 		uvm_mapent_alloc_split(struct vm_map *,
    279 		    const struct vm_map_entry *, int,
    280 		    struct uvm_mapent_reservation *);
    281 static void	uvm_mapent_copy(struct vm_map_entry *, struct vm_map_entry *);
    282 static void	uvm_mapent_free(struct vm_map_entry *);
    283 #if defined(DEBUG)
    284 static void	_uvm_mapent_check(const struct vm_map_entry *, const char *,
    285 		    int);
    286 #define	uvm_mapent_check(map)	_uvm_mapent_check(map, __FILE__, __LINE__)
    287 #else /* defined(DEBUG) */
    288 #define	uvm_mapent_check(e)	/* nothing */
    289 #endif /* defined(DEBUG) */
    290 static struct vm_map_entry *
    291 		uvm_kmapent_alloc(struct vm_map *, int);
    292 static void	uvm_kmapent_free(struct vm_map_entry *);
    293 static vsize_t	uvm_kmapent_overhead(vsize_t);
    294 
    295 static void	uvm_map_entry_unwire(struct vm_map *, struct vm_map_entry *);
    296 static void	uvm_map_reference_amap(struct vm_map_entry *, int);
    297 static int	uvm_map_space_avail(vaddr_t *, vsize_t, voff_t, vsize_t, int,
    298 		    struct vm_map_entry *);
    299 static void	uvm_map_unreference_amap(struct vm_map_entry *, int);
    300 
    301 int _uvm_map_sanity(struct vm_map *);
    302 int _uvm_tree_sanity(struct vm_map *);
    303 static vsize_t uvm_rb_maxgap(const struct vm_map_entry *);
    304 
    305 CTASSERT(offsetof(struct vm_map_entry, rb_node) == 0);
    306 #define	ROOT_ENTRY(map)		((struct vm_map_entry *)(map)->rb_tree.rbt_root)
    307 #define	LEFT_ENTRY(entry)	((struct vm_map_entry *)(entry)->rb_node.rb_left)
    308 #define	RIGHT_ENTRY(entry)	((struct vm_map_entry *)(entry)->rb_node.rb_right)
    309 #define	PARENT_ENTRY(map, entry) \
    310 	(ROOT_ENTRY(map) == (entry) \
    311 	    ? NULL \
    312 	    : (struct vm_map_entry *)RB_FATHER(&(entry)->rb_node))
    313 
    314 static int
    315 uvm_map_compare_nodes(const struct rb_node *nparent,
    316 	const struct rb_node *nkey)
    317 {
    318 	const struct vm_map_entry *eparent = (const void *) nparent;
    319 	const struct vm_map_entry *ekey = (const void *) nkey;
    320 
    321 	KASSERT(eparent->start < ekey->start || eparent->start >= ekey->end);
    322 	KASSERT(ekey->start < eparent->start || ekey->start >= eparent->end);
    323 
    324 	if (ekey->start < eparent->start)
    325 		return -1;
    326 	if (ekey->start >= eparent->end)
    327 		return 1;
    328 	return 0;
    329 }
    330 
    331 static int
    332 uvm_map_compare_key(const struct rb_node *nparent, const void *vkey)
    333 {
    334 	const struct vm_map_entry *eparent = (const void *) nparent;
    335 	const vaddr_t va = *(const vaddr_t *) vkey;
    336 
    337 	if (va < eparent->start)
    338 		return -1;
    339 	if (va >= eparent->end)
    340 		return 1;
    341 	return 0;
    342 }
    343 
    344 static const struct rb_tree_ops uvm_map_tree_ops = {
    345 	.rbto_compare_nodes = uvm_map_compare_nodes,
    346 	.rbto_compare_key = uvm_map_compare_key,
    347 };
    348 
    349 static inline vsize_t
    350 uvm_rb_gap(const struct vm_map_entry *entry)
    351 {
    352 	KASSERT(entry->next != NULL);
    353 	return entry->next->start - entry->end;
    354 }
    355 
    356 static vsize_t
    357 uvm_rb_maxgap(const struct vm_map_entry *entry)
    358 {
    359 	struct vm_map_entry *child;
    360 	vsize_t maxgap = entry->gap;
    361 
    362 	/*
    363 	 * We need maxgap to be the largest gap of us or any of our
    364 	 * descendents.  Since each of our children's maxgap is the
    365 	 * cached value of their largest gap of themselves or their
    366 	 * descendents, we can just use that value and avoid recursing
    367 	 * down the tree to calculate it.
    368 	 */
    369 	if ((child = LEFT_ENTRY(entry)) != NULL && maxgap < child->maxgap)
    370 		maxgap = child->maxgap;
    371 
    372 	if ((child = RIGHT_ENTRY(entry)) != NULL && maxgap < child->maxgap)
    373 		maxgap = child->maxgap;
    374 
    375 	return maxgap;
    376 }
    377 
    378 static void
    379 uvm_rb_fixup(struct vm_map *map, struct vm_map_entry *entry)
    380 {
    381 	struct vm_map_entry *parent;
    382 
    383 	KASSERT(entry->gap == uvm_rb_gap(entry));
    384 	entry->maxgap = uvm_rb_maxgap(entry);
    385 
    386 	while ((parent = PARENT_ENTRY(map, entry)) != NULL) {
    387 		struct vm_map_entry *brother;
    388 		vsize_t maxgap = parent->gap;
    389 
    390 		KDASSERT(parent->gap == uvm_rb_gap(parent));
    391 		if (maxgap < entry->maxgap)
    392 			maxgap = entry->maxgap;
    393 		/*
    394 		 * Since we work our towards the root, we know entry's maxgap
    395 		 * value is ok but its brothers may now be out-of-date due
    396 		 * rebalancing.  So refresh it.
    397 		 */
    398 		brother = (struct vm_map_entry *)parent->rb_node.rb_nodes[RB_POSITION(&entry->rb_node) ^ RB_DIR_OTHER];
    399 		if (brother != NULL) {
    400 			KDASSERT(brother->gap == uvm_rb_gap(brother));
    401 			brother->maxgap = uvm_rb_maxgap(brother);
    402 			if (maxgap < brother->maxgap)
    403 				maxgap = brother->maxgap;
    404 		}
    405 
    406 		parent->maxgap = maxgap;
    407 		entry = parent;
    408 	}
    409 }
    410 
    411 static void
    412 uvm_rb_insert(struct vm_map *map, struct vm_map_entry *entry)
    413 {
    414 	entry->gap = entry->maxgap = uvm_rb_gap(entry);
    415 	if (entry->prev != &map->header)
    416 		entry->prev->gap = uvm_rb_gap(entry->prev);
    417 
    418 	if (!rb_tree_insert_node(&map->rb_tree, &entry->rb_node))
    419 		panic("uvm_rb_insert: map %p: duplicate entry?", map);
    420 
    421 	/*
    422 	 * If the previous entry is not our immediate left child, then it's an
    423 	 * ancestor and will be fixed up on the way to the root.  We don't
    424 	 * have to check entry->prev against &map->header since &map->header
    425 	 * will never be in the tree.
    426 	 */
    427 	uvm_rb_fixup(map,
    428 	    LEFT_ENTRY(entry) == entry->prev ? entry->prev : entry);
    429 }
    430 
    431 static void
    432 uvm_rb_remove(struct vm_map *map, struct vm_map_entry *entry)
    433 {
    434 	struct vm_map_entry *prev_parent = NULL, *next_parent = NULL;
    435 
    436 	/*
    437 	 * If we are removing an interior node, then an adjacent node will
    438 	 * be used to replace its position in the tree.  Therefore we will
    439 	 * need to fixup the tree starting at the parent of the replacement
    440 	 * node.  So record their parents for later use.
    441 	 */
    442 	if (entry->prev != &map->header)
    443 		prev_parent = PARENT_ENTRY(map, entry->prev);
    444 	if (entry->next != &map->header)
    445 		next_parent = PARENT_ENTRY(map, entry->next);
    446 
    447 	rb_tree_remove_node(&map->rb_tree, &entry->rb_node);
    448 
    449 	/*
    450 	 * If the previous node has a new parent, fixup the tree starting
    451 	 * at the previous node's old parent.
    452 	 */
    453 	if (entry->prev != &map->header) {
    454 		/*
    455 		 * Update the previous entry's gap due to our absence.
    456 		 */
    457 		entry->prev->gap = uvm_rb_gap(entry->prev);
    458 		uvm_rb_fixup(map, entry->prev);
    459 		if (prev_parent != NULL
    460 		    && prev_parent != entry
    461 		    && prev_parent != PARENT_ENTRY(map, entry->prev))
    462 			uvm_rb_fixup(map, prev_parent);
    463 	}
    464 
    465 	/*
    466 	 * If the next node has a new parent, fixup the tree starting
    467 	 * at the next node's old parent.
    468 	 */
    469 	if (entry->next != &map->header) {
    470 		uvm_rb_fixup(map, entry->next);
    471 		if (next_parent != NULL
    472 		    && next_parent != entry
    473 		    && next_parent != PARENT_ENTRY(map, entry->next))
    474 			uvm_rb_fixup(map, next_parent);
    475 	}
    476 }
    477 
    478 #if defined(DEBUG)
    479 int uvm_debug_check_map = 0;
    480 int uvm_debug_check_rbtree = 0;
    481 #define uvm_map_check(map, name) \
    482 	_uvm_map_check((map), (name), __FILE__, __LINE__)
    483 static void
    484 _uvm_map_check(struct vm_map *map, const char *name,
    485     const char *file, int line)
    486 {
    487 
    488 	if ((uvm_debug_check_map && _uvm_map_sanity(map)) ||
    489 	    (uvm_debug_check_rbtree && _uvm_tree_sanity(map))) {
    490 		panic("uvm_map_check failed: \"%s\" map=%p (%s:%d)",
    491 		    name, map, file, line);
    492 	}
    493 }
    494 #else /* defined(DEBUG) */
    495 #define uvm_map_check(map, name)	/* nothing */
    496 #endif /* defined(DEBUG) */
    497 
    498 #if defined(DEBUG) || defined(DDB)
    499 int
    500 _uvm_map_sanity(struct vm_map *map)
    501 {
    502 	bool first_free_found = false;
    503 	bool hint_found = false;
    504 	const struct vm_map_entry *e;
    505 	struct vm_map_entry *hint = map->hint;
    506 
    507 	e = &map->header;
    508 	for (;;) {
    509 		if (map->first_free == e) {
    510 			first_free_found = true;
    511 		} else if (!first_free_found && e->next->start > e->end) {
    512 			printf("first_free %p should be %p\n",
    513 			    map->first_free, e);
    514 			return -1;
    515 		}
    516 		if (hint == e) {
    517 			hint_found = true;
    518 		}
    519 
    520 		e = e->next;
    521 		if (e == &map->header) {
    522 			break;
    523 		}
    524 	}
    525 	if (!first_free_found) {
    526 		printf("stale first_free\n");
    527 		return -1;
    528 	}
    529 	if (!hint_found) {
    530 		printf("stale hint\n");
    531 		return -1;
    532 	}
    533 	return 0;
    534 }
    535 
    536 int
    537 _uvm_tree_sanity(struct vm_map *map)
    538 {
    539 	struct vm_map_entry *tmp, *trtmp;
    540 	int n = 0, i = 1;
    541 
    542 	for (tmp = map->header.next; tmp != &map->header; tmp = tmp->next) {
    543 		if (tmp->gap != uvm_rb_gap(tmp)) {
    544 			printf("%d/%d gap %lx != %lx %s\n",
    545 			    n + 1, map->nentries,
    546 			    (ulong)tmp->gap, (ulong)uvm_rb_gap(tmp),
    547 			    tmp->next == &map->header ? "(last)" : "");
    548 			goto error;
    549 		}
    550 		/*
    551 		 * If any entries are out of order, tmp->gap will be unsigned
    552 		 * and will likely exceed the size of the map.
    553 		 */
    554 		KASSERT(tmp->gap < map->size);
    555 		n++;
    556 	}
    557 
    558 	if (n != map->nentries) {
    559 		printf("nentries: %d vs %d\n", n, map->nentries);
    560 		goto error;
    561 	}
    562 
    563 	trtmp = NULL;
    564 	for (tmp = map->header.next; tmp != &map->header; tmp = tmp->next) {
    565 		if (tmp->maxgap != uvm_rb_maxgap(tmp)) {
    566 			printf("maxgap %lx != %lx\n",
    567 			    (ulong)tmp->maxgap,
    568 			    (ulong)uvm_rb_maxgap(tmp));
    569 			goto error;
    570 		}
    571 		if (trtmp != NULL && trtmp->start >= tmp->start) {
    572 			printf("corrupt: 0x%lx >= 0x%lx\n",
    573 			    trtmp->start, tmp->start);
    574 			goto error;
    575 		}
    576 
    577 		trtmp = tmp;
    578 	}
    579 
    580 	for (tmp = map->header.next; tmp != &map->header;
    581 	    tmp = tmp->next, i++) {
    582 		trtmp = (void *) rb_tree_iterate(&map->rb_tree, &tmp->rb_node,
    583 		    RB_DIR_LEFT);
    584 		if (trtmp == NULL)
    585 			trtmp = &map->header;
    586 		if (tmp->prev != trtmp) {
    587 			printf("lookup: %d: %p->prev=%p: %p\n",
    588 			    i, tmp, tmp->prev, trtmp);
    589 			goto error;
    590 		}
    591 		trtmp = (void *) rb_tree_iterate(&map->rb_tree, &tmp->rb_node,
    592 		    RB_DIR_RIGHT);
    593 		if (trtmp == NULL)
    594 			trtmp = &map->header;
    595 		if (tmp->next != trtmp) {
    596 			printf("lookup: %d: %p->next=%p: %p\n",
    597 			    i, tmp, tmp->next, trtmp);
    598 			goto error;
    599 		}
    600 		trtmp = (void *)rb_tree_find_node(&map->rb_tree, &tmp->start);
    601 		if (trtmp != tmp) {
    602 			printf("lookup: %d: %p - %p: %p\n", i, tmp, trtmp,
    603 			    PARENT_ENTRY(map, tmp));
    604 			goto error;
    605 		}
    606 	}
    607 
    608 	return (0);
    609  error:
    610 	return (-1);
    611 }
    612 #endif /* defined(DEBUG) || defined(DDB) */
    613 
    614 #ifdef DIAGNOSTIC
    615 static struct vm_map *uvm_kmapent_map(struct vm_map_entry *);
    616 #endif
    617 
    618 /*
    619  * vm_map_lock: acquire an exclusive (write) lock on a map.
    620  *
    621  * => Note that "intrsafe" maps use only exclusive, spin locks.
    622  *
    623  * => The locking protocol provides for guaranteed upgrade from shared ->
    624  *    exclusive by whichever thread currently has the map marked busy.
    625  *    See "LOCKING PROTOCOL NOTES" in uvm_map.h.  This is horrible; among
    626  *    other problems, it defeats any fairness guarantees provided by RW
    627  *    locks.
    628  */
    629 
    630 void
    631 vm_map_lock(struct vm_map *map)
    632 {
    633 
    634 	if ((map->flags & VM_MAP_INTRSAFE) != 0) {
    635 		mutex_spin_enter(&map->mutex);
    636 		return;
    637 	}
    638 
    639 	for (;;) {
    640 		rw_enter(&map->lock, RW_WRITER);
    641 		if (map->busy == NULL)
    642 			break;
    643 		if (map->busy == curlwp)
    644 			break;
    645 		mutex_enter(&map->misc_lock);
    646 		rw_exit(&map->lock);
    647 		if (map->busy != NULL)
    648 			cv_wait(&map->cv, &map->misc_lock);
    649 		mutex_exit(&map->misc_lock);
    650 	}
    651 
    652 	map->timestamp++;
    653 }
    654 
    655 /*
    656  * vm_map_lock_try: try to lock a map, failing if it is already locked.
    657  */
    658 
    659 bool
    660 vm_map_lock_try(struct vm_map *map)
    661 {
    662 
    663 	if ((map->flags & VM_MAP_INTRSAFE) != 0)
    664 		return mutex_tryenter(&map->mutex);
    665 	if (!rw_tryenter(&map->lock, RW_WRITER))
    666 		return false;
    667 	if (map->busy != NULL) {
    668 		rw_exit(&map->lock);
    669 		return false;
    670 	}
    671 
    672 	map->timestamp++;
    673 	return true;
    674 }
    675 
    676 /*
    677  * vm_map_unlock: release an exclusive lock on a map.
    678  */
    679 
    680 void
    681 vm_map_unlock(struct vm_map *map)
    682 {
    683 
    684 	if ((map->flags & VM_MAP_INTRSAFE) != 0)
    685 		mutex_spin_exit(&map->mutex);
    686 	else {
    687 		KASSERT(rw_write_held(&map->lock));
    688 		KASSERT(map->busy == NULL || map->busy == curlwp);
    689 		rw_exit(&map->lock);
    690 	}
    691 }
    692 
    693 /*
    694  * vm_map_unbusy: mark the map as unbusy, and wake any waiters that
    695  *     want an exclusive lock.
    696  */
    697 
    698 void
    699 vm_map_unbusy(struct vm_map *map)
    700 {
    701 
    702 	KASSERT(map->busy == curlwp);
    703 
    704 	/*
    705 	 * Safe to clear 'busy' and 'waiters' with only a read lock held:
    706 	 *
    707 	 * o they can only be set with a write lock held
    708 	 * o writers are blocked out with a read or write hold
    709 	 * o at any time, only one thread owns the set of values
    710 	 */
    711 	mutex_enter(&map->misc_lock);
    712 	map->busy = NULL;
    713 	cv_broadcast(&map->cv);
    714 	mutex_exit(&map->misc_lock);
    715 }
    716 
    717 /*
    718  * vm_map_lock_read: acquire a shared (read) lock on a map.
    719  */
    720 
    721 void
    722 vm_map_lock_read(struct vm_map *map)
    723 {
    724 
    725 	KASSERT((map->flags & VM_MAP_INTRSAFE) == 0);
    726 
    727 	rw_enter(&map->lock, RW_READER);
    728 }
    729 
    730 /*
    731  * vm_map_unlock_read: release a shared lock on a map.
    732  */
    733 
    734 void
    735 vm_map_unlock_read(struct vm_map *map)
    736 {
    737 
    738 	KASSERT((map->flags & VM_MAP_INTRSAFE) == 0);
    739 
    740 	rw_exit(&map->lock);
    741 }
    742 
    743 /*
    744  * vm_map_busy: mark a map as busy.
    745  *
    746  * => the caller must hold the map write locked
    747  */
    748 
    749 void
    750 vm_map_busy(struct vm_map *map)
    751 {
    752 
    753 	KASSERT(rw_write_held(&map->lock));
    754 	KASSERT(map->busy == NULL);
    755 
    756 	map->busy = curlwp;
    757 }
    758 
    759 /*
    760  * vm_map_locked_p: return true if the map is write locked.
    761  *
    762  * => only for debug purposes like KASSERTs.
    763  * => should not be used to verify that a map is not locked.
    764  */
    765 
    766 bool
    767 vm_map_locked_p(struct vm_map *map)
    768 {
    769 
    770 	if ((map->flags & VM_MAP_INTRSAFE) != 0) {
    771 		return mutex_owned(&map->mutex);
    772 	} else {
    773 		return rw_write_held(&map->lock);
    774 	}
    775 }
    776 
    777 /*
    778  * uvm_mapent_alloc: allocate a map entry
    779  */
    780 
    781 static struct vm_map_entry *
    782 uvm_mapent_alloc(struct vm_map *map, int flags)
    783 {
    784 	struct vm_map_entry *me;
    785 	int pflags = (flags & UVM_FLAG_NOWAIT) ? PR_NOWAIT : PR_WAITOK;
    786 	UVMHIST_FUNC("uvm_mapent_alloc"); UVMHIST_CALLED(maphist);
    787 
    788 	if (VM_MAP_USE_KMAPENT(map)) {
    789 		me = uvm_kmapent_alloc(map, flags);
    790 	} else {
    791 		me = pool_cache_get(&uvm_map_entry_cache, pflags);
    792 		if (__predict_false(me == NULL))
    793 			return NULL;
    794 		me->flags = 0;
    795 	}
    796 
    797 	UVMHIST_LOG(maphist, "<- new entry=0x%x [kentry=%d]", me,
    798 	    ((map->flags & VM_MAP_INTRSAFE) != 0 || map == kernel_map), 0, 0);
    799 	return (me);
    800 }
    801 
    802 /*
    803  * uvm_mapent_alloc_split: allocate a map entry for clipping.
    804  *
    805  * => map must be locked by caller if UVM_MAP_QUANTUM is set.
    806  */
    807 
    808 static struct vm_map_entry *
    809 uvm_mapent_alloc_split(struct vm_map *map,
    810     const struct vm_map_entry *old_entry, int flags,
    811     struct uvm_mapent_reservation *umr)
    812 {
    813 	struct vm_map_entry *me;
    814 
    815 	KASSERT(!VM_MAP_USE_KMAPENT(map) ||
    816 	    (old_entry->flags & UVM_MAP_QUANTUM) || !UMR_EMPTY(umr));
    817 
    818 	if (old_entry->flags & UVM_MAP_QUANTUM) {
    819 		struct vm_map_kernel *vmk = vm_map_to_kernel(map);
    820 
    821 		KASSERT(vm_map_locked_p(map));
    822 		me = vmk->vmk_merged_entries;
    823 		KASSERT(me);
    824 		vmk->vmk_merged_entries = me->next;
    825 		KASSERT(me->flags & UVM_MAP_QUANTUM);
    826 	} else {
    827 		me = uvm_mapent_alloc(map, flags);
    828 	}
    829 
    830 	return me;
    831 }
    832 
    833 /*
    834  * uvm_mapent_free: free map entry
    835  */
    836 
    837 static void
    838 uvm_mapent_free(struct vm_map_entry *me)
    839 {
    840 	UVMHIST_FUNC("uvm_mapent_free"); UVMHIST_CALLED(maphist);
    841 
    842 	UVMHIST_LOG(maphist,"<- freeing map entry=0x%x [flags=%d]",
    843 		me, me->flags, 0, 0);
    844 	if (me->flags & UVM_MAP_KERNEL) {
    845 		uvm_kmapent_free(me);
    846 	} else {
    847 		pool_cache_put(&uvm_map_entry_cache, me);
    848 	}
    849 }
    850 
    851 /*
    852  * uvm_mapent_free_merged: free merged map entry
    853  *
    854  * => keep the entry if needed.
    855  * => caller shouldn't hold map locked if VM_MAP_USE_KMAPENT(map) is true.
    856  * => map should be locked if UVM_MAP_QUANTUM is set.
    857  */
    858 
    859 static void
    860 uvm_mapent_free_merged(struct vm_map *map, struct vm_map_entry *me)
    861 {
    862 
    863 	KASSERT(!(me->flags & UVM_MAP_KERNEL) || uvm_kmapent_map(me) == map);
    864 
    865 	if (me->flags & UVM_MAP_QUANTUM) {
    866 		/*
    867 		 * keep this entry for later splitting.
    868 		 */
    869 		struct vm_map_kernel *vmk;
    870 
    871 		KASSERT(vm_map_locked_p(map));
    872 		KASSERT(VM_MAP_IS_KERNEL(map));
    873 		KASSERT(!VM_MAP_USE_KMAPENT(map) ||
    874 		    (me->flags & UVM_MAP_KERNEL));
    875 
    876 		vmk = vm_map_to_kernel(map);
    877 		me->next = vmk->vmk_merged_entries;
    878 		vmk->vmk_merged_entries = me;
    879 	} else {
    880 		uvm_mapent_free(me);
    881 	}
    882 }
    883 
    884 /*
    885  * uvm_mapent_copy: copy a map entry, preserving flags
    886  */
    887 
    888 static inline void
    889 uvm_mapent_copy(struct vm_map_entry *src, struct vm_map_entry *dst)
    890 {
    891 
    892 	memcpy(dst, src, ((char *)&src->uvm_map_entry_stop_copy) -
    893 	    ((char *)src));
    894 }
    895 
    896 /*
    897  * uvm_mapent_overhead: calculate maximum kva overhead necessary for
    898  * map entries.
    899  *
    900  * => size and flags are the same as uvm_km_suballoc's ones.
    901  */
    902 
    903 vsize_t
    904 uvm_mapent_overhead(vsize_t size, int flags)
    905 {
    906 
    907 	if (VM_MAP_USE_KMAPENT_FLAGS(flags)) {
    908 		return uvm_kmapent_overhead(size);
    909 	}
    910 	return 0;
    911 }
    912 
    913 #if defined(DEBUG)
    914 static void
    915 _uvm_mapent_check(const struct vm_map_entry *entry, const char *file, int line)
    916 {
    917 
    918 	if (entry->start >= entry->end) {
    919 		goto bad;
    920 	}
    921 	if (UVM_ET_ISOBJ(entry)) {
    922 		if (entry->object.uvm_obj == NULL) {
    923 			goto bad;
    924 		}
    925 	} else if (UVM_ET_ISSUBMAP(entry)) {
    926 		if (entry->object.sub_map == NULL) {
    927 			goto bad;
    928 		}
    929 	} else {
    930 		if (entry->object.uvm_obj != NULL ||
    931 		    entry->object.sub_map != NULL) {
    932 			goto bad;
    933 		}
    934 	}
    935 	if (!UVM_ET_ISOBJ(entry)) {
    936 		if (entry->offset != 0) {
    937 			goto bad;
    938 		}
    939 	}
    940 
    941 	return;
    942 
    943 bad:
    944 	panic("%s: bad entry %p (%s:%d)", __func__, entry, file, line);
    945 }
    946 #endif /* defined(DEBUG) */
    947 
    948 /*
    949  * uvm_map_entry_unwire: unwire a map entry
    950  *
    951  * => map should be locked by caller
    952  */
    953 
    954 static inline void
    955 uvm_map_entry_unwire(struct vm_map *map, struct vm_map_entry *entry)
    956 {
    957 
    958 	entry->wired_count = 0;
    959 	uvm_fault_unwire_locked(map, entry->start, entry->end);
    960 }
    961 
    962 
    963 /*
    964  * wrapper for calling amap_ref()
    965  */
    966 static inline void
    967 uvm_map_reference_amap(struct vm_map_entry *entry, int flags)
    968 {
    969 
    970 	amap_ref(entry->aref.ar_amap, entry->aref.ar_pageoff,
    971 	    (entry->end - entry->start) >> PAGE_SHIFT, flags);
    972 }
    973 
    974 
    975 /*
    976  * wrapper for calling amap_unref()
    977  */
    978 static inline void
    979 uvm_map_unreference_amap(struct vm_map_entry *entry, int flags)
    980 {
    981 
    982 	amap_unref(entry->aref.ar_amap, entry->aref.ar_pageoff,
    983 	    (entry->end - entry->start) >> PAGE_SHIFT, flags);
    984 }
    985 
    986 
    987 /*
    988  * uvm_map_init: init mapping system at boot time.
    989  */
    990 
    991 void
    992 uvm_map_init(void)
    993 {
    994 #if defined(UVMHIST)
    995 	static struct uvm_history_ent maphistbuf[100];
    996 	static struct uvm_history_ent pdhistbuf[100];
    997 #endif
    998 
    999 	/*
   1000 	 * first, init logging system.
   1001 	 */
   1002 
   1003 	UVMHIST_FUNC("uvm_map_init");
   1004 	UVMHIST_INIT_STATIC(maphist, maphistbuf);
   1005 	UVMHIST_INIT_STATIC(pdhist, pdhistbuf);
   1006 	UVMHIST_CALLED(maphist);
   1007 	UVMHIST_LOG(maphist,"<starting uvm map system>", 0, 0, 0, 0);
   1008 
   1009 	/*
   1010 	 * initialize the global lock for kernel map entry.
   1011 	 */
   1012 
   1013 	mutex_init(&uvm_kentry_lock, MUTEX_DRIVER, IPL_VM);
   1014 
   1015 	/*
   1016 	 * initialize caches.
   1017 	 */
   1018 
   1019 	pool_cache_bootstrap(&uvm_map_entry_cache, sizeof(struct vm_map_entry),
   1020 	    0, 0, 0, "vmmpepl", NULL, IPL_NONE, NULL, NULL, NULL);
   1021 	pool_cache_bootstrap(&uvm_vmspace_cache, sizeof(struct vmspace),
   1022 	    0, 0, 0, "vmsppl", NULL, IPL_NONE, NULL, NULL, NULL);
   1023 }
   1024 
   1025 /*
   1026  * clippers
   1027  */
   1028 
   1029 /*
   1030  * uvm_mapent_splitadj: adjust map entries for splitting, after uvm_mapent_copy.
   1031  */
   1032 
   1033 static void
   1034 uvm_mapent_splitadj(struct vm_map_entry *entry1, struct vm_map_entry *entry2,
   1035     vaddr_t splitat)
   1036 {
   1037 	vaddr_t adj;
   1038 
   1039 	KASSERT(entry1->start < splitat);
   1040 	KASSERT(splitat < entry1->end);
   1041 
   1042 	adj = splitat - entry1->start;
   1043 	entry1->end = entry2->start = splitat;
   1044 
   1045 	if (entry1->aref.ar_amap) {
   1046 		amap_splitref(&entry1->aref, &entry2->aref, adj);
   1047 	}
   1048 	if (UVM_ET_ISSUBMAP(entry1)) {
   1049 		/* ... unlikely to happen, but play it safe */
   1050 		 uvm_map_reference(entry1->object.sub_map);
   1051 	} else if (UVM_ET_ISOBJ(entry1)) {
   1052 		KASSERT(entry1->object.uvm_obj != NULL); /* suppress coverity */
   1053 		entry2->offset += adj;
   1054 		if (entry1->object.uvm_obj->pgops &&
   1055 		    entry1->object.uvm_obj->pgops->pgo_reference)
   1056 			entry1->object.uvm_obj->pgops->pgo_reference(
   1057 			    entry1->object.uvm_obj);
   1058 	}
   1059 }
   1060 
   1061 /*
   1062  * uvm_map_clip_start: ensure that the entry begins at or after
   1063  *	the starting address, if it doesn't we split the entry.
   1064  *
   1065  * => caller should use UVM_MAP_CLIP_START macro rather than calling
   1066  *    this directly
   1067  * => map must be locked by caller
   1068  */
   1069 
   1070 void
   1071 uvm_map_clip_start(struct vm_map *map, struct vm_map_entry *entry,
   1072     vaddr_t start, struct uvm_mapent_reservation *umr)
   1073 {
   1074 	struct vm_map_entry *new_entry;
   1075 
   1076 	/* uvm_map_simplify_entry(map, entry); */ /* XXX */
   1077 
   1078 	uvm_map_check(map, "clip_start entry");
   1079 	uvm_mapent_check(entry);
   1080 
   1081 	/*
   1082 	 * Split off the front portion.  note that we must insert the new
   1083 	 * entry BEFORE this one, so that this entry has the specified
   1084 	 * starting address.
   1085 	 */
   1086 	new_entry = uvm_mapent_alloc_split(map, entry, 0, umr);
   1087 	uvm_mapent_copy(entry, new_entry); /* entry -> new_entry */
   1088 	uvm_mapent_splitadj(new_entry, entry, start);
   1089 	uvm_map_entry_link(map, entry->prev, new_entry);
   1090 
   1091 	uvm_map_check(map, "clip_start leave");
   1092 }
   1093 
   1094 /*
   1095  * uvm_map_clip_end: ensure that the entry ends at or before
   1096  *	the ending address, if it does't we split the reference
   1097  *
   1098  * => caller should use UVM_MAP_CLIP_END macro rather than calling
   1099  *    this directly
   1100  * => map must be locked by caller
   1101  */
   1102 
   1103 void
   1104 uvm_map_clip_end(struct vm_map *map, struct vm_map_entry *entry, vaddr_t end,
   1105     struct uvm_mapent_reservation *umr)
   1106 {
   1107 	struct vm_map_entry *new_entry;
   1108 
   1109 	uvm_map_check(map, "clip_end entry");
   1110 	uvm_mapent_check(entry);
   1111 
   1112 	/*
   1113 	 *	Create a new entry and insert it
   1114 	 *	AFTER the specified entry
   1115 	 */
   1116 	new_entry = uvm_mapent_alloc_split(map, entry, 0, umr);
   1117 	uvm_mapent_copy(entry, new_entry); /* entry -> new_entry */
   1118 	uvm_mapent_splitadj(entry, new_entry, end);
   1119 	uvm_map_entry_link(map, entry, new_entry);
   1120 
   1121 	uvm_map_check(map, "clip_end leave");
   1122 }
   1123 
   1124 static void
   1125 vm_map_drain(struct vm_map *map, uvm_flag_t flags)
   1126 {
   1127 
   1128 	if (!VM_MAP_IS_KERNEL(map)) {
   1129 		return;
   1130 	}
   1131 
   1132 	uvm_km_va_drain(map, flags);
   1133 }
   1134 
   1135 /*
   1136  *   M A P   -   m a i n   e n t r y   p o i n t
   1137  */
   1138 /*
   1139  * uvm_map: establish a valid mapping in a map
   1140  *
   1141  * => assume startp is page aligned.
   1142  * => assume size is a multiple of PAGE_SIZE.
   1143  * => assume sys_mmap provides enough of a "hint" to have us skip
   1144  *	over text/data/bss area.
   1145  * => map must be unlocked (we will lock it)
   1146  * => <uobj,uoffset> value meanings (4 cases):
   1147  *	 [1] <NULL,uoffset>		== uoffset is a hint for PMAP_PREFER
   1148  *	 [2] <NULL,UVM_UNKNOWN_OFFSET>	== don't PMAP_PREFER
   1149  *	 [3] <uobj,uoffset>		== normal mapping
   1150  *	 [4] <uobj,UVM_UNKNOWN_OFFSET>	== uvm_map finds offset based on VA
   1151  *
   1152  *    case [4] is for kernel mappings where we don't know the offset until
   1153  *    we've found a virtual address.   note that kernel object offsets are
   1154  *    always relative to vm_map_min(kernel_map).
   1155  *
   1156  * => if `align' is non-zero, we align the virtual address to the specified
   1157  *	alignment.
   1158  *	this is provided as a mechanism for large pages.
   1159  *
   1160  * => XXXCDC: need way to map in external amap?
   1161  */
   1162 
   1163 int
   1164 uvm_map(struct vm_map *map, vaddr_t *startp /* IN/OUT */, vsize_t size,
   1165     struct uvm_object *uobj, voff_t uoffset, vsize_t align, uvm_flag_t flags)
   1166 {
   1167 	struct uvm_map_args args;
   1168 	struct vm_map_entry *new_entry;
   1169 	int error;
   1170 
   1171 	KASSERT((flags & UVM_FLAG_QUANTUM) == 0 || VM_MAP_IS_KERNEL(map));
   1172 	KASSERT((size & PAGE_MASK) == 0);
   1173 
   1174 	/*
   1175 	 * for pager_map, allocate the new entry first to avoid sleeping
   1176 	 * for memory while we have the map locked.
   1177 	 *
   1178 	 * Also, because we allocate entries for in-kernel maps
   1179 	 * a bit differently (cf. uvm_kmapent_alloc/free), we need to
   1180 	 * allocate them before locking the map.
   1181 	 */
   1182 
   1183 	new_entry = NULL;
   1184 	if (VM_MAP_USE_KMAPENT(map) || (flags & UVM_FLAG_QUANTUM) ||
   1185 	    map == pager_map) {
   1186 		new_entry = uvm_mapent_alloc(map, (flags & UVM_FLAG_NOWAIT));
   1187 		if (__predict_false(new_entry == NULL))
   1188 			return ENOMEM;
   1189 		if (flags & UVM_FLAG_QUANTUM)
   1190 			new_entry->flags |= UVM_MAP_QUANTUM;
   1191 	}
   1192 	if (map == pager_map)
   1193 		flags |= UVM_FLAG_NOMERGE;
   1194 
   1195 	error = uvm_map_prepare(map, *startp, size, uobj, uoffset, align,
   1196 	    flags, &args);
   1197 	if (!error) {
   1198 		error = uvm_map_enter(map, &args, new_entry);
   1199 		*startp = args.uma_start;
   1200 	} else if (new_entry) {
   1201 		uvm_mapent_free(new_entry);
   1202 	}
   1203 
   1204 #if defined(DEBUG)
   1205 	if (!error && VM_MAP_IS_KERNEL(map)) {
   1206 		uvm_km_check_empty(map, *startp, *startp + size);
   1207 	}
   1208 #endif /* defined(DEBUG) */
   1209 
   1210 	return error;
   1211 }
   1212 
   1213 int
   1214 uvm_map_prepare(struct vm_map *map, vaddr_t start, vsize_t size,
   1215     struct uvm_object *uobj, voff_t uoffset, vsize_t align, uvm_flag_t flags,
   1216     struct uvm_map_args *args)
   1217 {
   1218 	struct vm_map_entry *prev_entry;
   1219 	vm_prot_t prot = UVM_PROTECTION(flags);
   1220 	vm_prot_t maxprot = UVM_MAXPROTECTION(flags);
   1221 
   1222 	UVMHIST_FUNC("uvm_map_prepare");
   1223 	UVMHIST_CALLED(maphist);
   1224 
   1225 	UVMHIST_LOG(maphist, "(map=0x%x, start=0x%x, size=%d, flags=0x%x)",
   1226 	    map, start, size, flags);
   1227 	UVMHIST_LOG(maphist, "  uobj/offset 0x%x/%d", uobj, uoffset,0,0);
   1228 
   1229 	/*
   1230 	 * detect a popular device driver bug.
   1231 	 */
   1232 
   1233 	KASSERT(doing_shutdown || curlwp != NULL ||
   1234 	    (map->flags & VM_MAP_INTRSAFE));
   1235 
   1236 	/*
   1237 	 * zero-sized mapping doesn't make any sense.
   1238 	 */
   1239 	KASSERT(size > 0);
   1240 
   1241 	KASSERT((~flags & (UVM_FLAG_NOWAIT | UVM_FLAG_WAITVA)) != 0);
   1242 
   1243 	uvm_map_check(map, "map entry");
   1244 
   1245 	/*
   1246 	 * check sanity of protection code
   1247 	 */
   1248 
   1249 	if ((prot & maxprot) != prot) {
   1250 		UVMHIST_LOG(maphist, "<- prot. failure:  prot=0x%x, max=0x%x",
   1251 		prot, maxprot,0,0);
   1252 		return EACCES;
   1253 	}
   1254 
   1255 	/*
   1256 	 * figure out where to put new VM range
   1257 	 */
   1258 
   1259 retry:
   1260 	if (vm_map_lock_try(map) == false) {
   1261 		if ((flags & UVM_FLAG_TRYLOCK) != 0 &&
   1262 		    (map->flags & VM_MAP_INTRSAFE) == 0) {
   1263 			return EAGAIN;
   1264 		}
   1265 		vm_map_lock(map); /* could sleep here */
   1266 	}
   1267 	prev_entry = uvm_map_findspace(map, start, size, &start,
   1268 	    uobj, uoffset, align, flags);
   1269 	if (prev_entry == NULL) {
   1270 		unsigned int timestamp;
   1271 
   1272 		timestamp = map->timestamp;
   1273 		UVMHIST_LOG(maphist,"waiting va timestamp=0x%x",
   1274 			    timestamp,0,0,0);
   1275 		map->flags |= VM_MAP_WANTVA;
   1276 		vm_map_unlock(map);
   1277 
   1278 		/*
   1279 		 * try to reclaim kva and wait until someone does unmap.
   1280 		 * fragile locking here, so we awaken every second to
   1281 		 * recheck the condition.
   1282 		 */
   1283 
   1284 		vm_map_drain(map, flags);
   1285 
   1286 		mutex_enter(&map->misc_lock);
   1287 		while ((map->flags & VM_MAP_WANTVA) != 0 &&
   1288 		   map->timestamp == timestamp) {
   1289 			if ((flags & UVM_FLAG_WAITVA) == 0) {
   1290 				mutex_exit(&map->misc_lock);
   1291 				UVMHIST_LOG(maphist,
   1292 				    "<- uvm_map_findspace failed!", 0,0,0,0);
   1293 				return ENOMEM;
   1294 			} else {
   1295 				cv_timedwait(&map->cv, &map->misc_lock, hz);
   1296 			}
   1297 		}
   1298 		mutex_exit(&map->misc_lock);
   1299 		goto retry;
   1300 	}
   1301 
   1302 #ifdef PMAP_GROWKERNEL
   1303 	/*
   1304 	 * If the kernel pmap can't map the requested space,
   1305 	 * then allocate more resources for it.
   1306 	 */
   1307 	if (map == kernel_map && uvm_maxkaddr < (start + size))
   1308 		uvm_maxkaddr = pmap_growkernel(start + size);
   1309 #endif
   1310 
   1311 	UVMMAP_EVCNT_INCR(map_call);
   1312 
   1313 	/*
   1314 	 * if uobj is null, then uoffset is either a VAC hint for PMAP_PREFER
   1315 	 * [typically from uvm_map_reserve] or it is UVM_UNKNOWN_OFFSET.   in
   1316 	 * either case we want to zero it  before storing it in the map entry
   1317 	 * (because it looks strange and confusing when debugging...)
   1318 	 *
   1319 	 * if uobj is not null
   1320 	 *   if uoffset is not UVM_UNKNOWN_OFFSET then we have a normal mapping
   1321 	 *      and we do not need to change uoffset.
   1322 	 *   if uoffset is UVM_UNKNOWN_OFFSET then we need to find the offset
   1323 	 *      now (based on the starting address of the map).   this case is
   1324 	 *      for kernel object mappings where we don't know the offset until
   1325 	 *      the virtual address is found (with uvm_map_findspace).   the
   1326 	 *      offset is the distance we are from the start of the map.
   1327 	 */
   1328 
   1329 	if (uobj == NULL) {
   1330 		uoffset = 0;
   1331 	} else {
   1332 		if (uoffset == UVM_UNKNOWN_OFFSET) {
   1333 			KASSERT(UVM_OBJ_IS_KERN_OBJECT(uobj));
   1334 			uoffset = start - vm_map_min(kernel_map);
   1335 		}
   1336 	}
   1337 
   1338 	args->uma_flags = flags;
   1339 	args->uma_prev = prev_entry;
   1340 	args->uma_start = start;
   1341 	args->uma_size = size;
   1342 	args->uma_uobj = uobj;
   1343 	args->uma_uoffset = uoffset;
   1344 
   1345 	return 0;
   1346 }
   1347 
   1348 int
   1349 uvm_map_enter(struct vm_map *map, const struct uvm_map_args *args,
   1350     struct vm_map_entry *new_entry)
   1351 {
   1352 	struct vm_map_entry *prev_entry = args->uma_prev;
   1353 	struct vm_map_entry *dead = NULL;
   1354 
   1355 	const uvm_flag_t flags = args->uma_flags;
   1356 	const vm_prot_t prot = UVM_PROTECTION(flags);
   1357 	const vm_prot_t maxprot = UVM_MAXPROTECTION(flags);
   1358 	const vm_inherit_t inherit = UVM_INHERIT(flags);
   1359 	const int amapwaitflag = (flags & UVM_FLAG_NOWAIT) ?
   1360 	    AMAP_EXTEND_NOWAIT : 0;
   1361 	const int advice = UVM_ADVICE(flags);
   1362 	const int meflagval = (flags & UVM_FLAG_QUANTUM) ?
   1363 	    UVM_MAP_QUANTUM : 0;
   1364 
   1365 	vaddr_t start = args->uma_start;
   1366 	vsize_t size = args->uma_size;
   1367 	struct uvm_object *uobj = args->uma_uobj;
   1368 	voff_t uoffset = args->uma_uoffset;
   1369 
   1370 	const int kmap = (vm_map_pmap(map) == pmap_kernel());
   1371 	int merged = 0;
   1372 	int error;
   1373 	int newetype;
   1374 
   1375 	UVMHIST_FUNC("uvm_map_enter");
   1376 	UVMHIST_CALLED(maphist);
   1377 
   1378 	UVMHIST_LOG(maphist, "(map=0x%x, start=0x%x, size=%d, flags=0x%x)",
   1379 	    map, start, size, flags);
   1380 	UVMHIST_LOG(maphist, "  uobj/offset 0x%x/%d", uobj, uoffset,0,0);
   1381 
   1382 	KASSERT(map->hint == prev_entry); /* bimerge case assumes this */
   1383 
   1384 	if (flags & UVM_FLAG_QUANTUM) {
   1385 		KASSERT(new_entry);
   1386 		KASSERT(new_entry->flags & UVM_MAP_QUANTUM);
   1387 	}
   1388 
   1389 	if (uobj)
   1390 		newetype = UVM_ET_OBJ;
   1391 	else
   1392 		newetype = 0;
   1393 
   1394 	if (flags & UVM_FLAG_COPYONW) {
   1395 		newetype |= UVM_ET_COPYONWRITE;
   1396 		if ((flags & UVM_FLAG_OVERLAY) == 0)
   1397 			newetype |= UVM_ET_NEEDSCOPY;
   1398 	}
   1399 
   1400 	/*
   1401 	 * try and insert in map by extending previous entry, if possible.
   1402 	 * XXX: we don't try and pull back the next entry.   might be useful
   1403 	 * for a stack, but we are currently allocating our stack in advance.
   1404 	 */
   1405 
   1406 	if (flags & UVM_FLAG_NOMERGE)
   1407 		goto nomerge;
   1408 
   1409 	if (prev_entry->end == start &&
   1410 	    prev_entry != &map->header &&
   1411 	    UVM_ET_ISCOMPATIBLE(prev_entry, newetype, uobj, meflagval,
   1412 	    prot, maxprot, inherit, advice, 0)) {
   1413 
   1414 		if (uobj && prev_entry->offset +
   1415 		    (prev_entry->end - prev_entry->start) != uoffset)
   1416 			goto forwardmerge;
   1417 
   1418 		/*
   1419 		 * can't extend a shared amap.  note: no need to lock amap to
   1420 		 * look at refs since we don't care about its exact value.
   1421 		 * if it is one (i.e. we have only reference) it will stay there
   1422 		 */
   1423 
   1424 		if (prev_entry->aref.ar_amap &&
   1425 		    amap_refs(prev_entry->aref.ar_amap) != 1) {
   1426 			goto forwardmerge;
   1427 		}
   1428 
   1429 		if (prev_entry->aref.ar_amap) {
   1430 			error = amap_extend(prev_entry, size,
   1431 			    amapwaitflag | AMAP_EXTEND_FORWARDS);
   1432 			if (error)
   1433 				goto nomerge;
   1434 		}
   1435 
   1436 		if (kmap) {
   1437 			UVMMAP_EVCNT_INCR(kbackmerge);
   1438 		} else {
   1439 			UVMMAP_EVCNT_INCR(ubackmerge);
   1440 		}
   1441 		UVMHIST_LOG(maphist,"  starting back merge", 0, 0, 0, 0);
   1442 
   1443 		/*
   1444 		 * drop our reference to uobj since we are extending a reference
   1445 		 * that we already have (the ref count can not drop to zero).
   1446 		 */
   1447 
   1448 		if (uobj && uobj->pgops->pgo_detach)
   1449 			uobj->pgops->pgo_detach(uobj);
   1450 
   1451 		/*
   1452 		 * Now that we've merged the entries, note that we've grown
   1453 		 * and our gap has shrunk.  Then fix the tree.
   1454 		 */
   1455 		prev_entry->end += size;
   1456 		prev_entry->gap -= size;
   1457 		uvm_rb_fixup(map, prev_entry);
   1458 
   1459 		uvm_map_check(map, "map backmerged");
   1460 
   1461 		UVMHIST_LOG(maphist,"<- done (via backmerge)!", 0, 0, 0, 0);
   1462 		merged++;
   1463 	}
   1464 
   1465 forwardmerge:
   1466 	if (prev_entry->next->start == (start + size) &&
   1467 	    prev_entry->next != &map->header &&
   1468 	    UVM_ET_ISCOMPATIBLE(prev_entry->next, newetype, uobj, meflagval,
   1469 	    prot, maxprot, inherit, advice, 0)) {
   1470 
   1471 		if (uobj && prev_entry->next->offset != uoffset + size)
   1472 			goto nomerge;
   1473 
   1474 		/*
   1475 		 * can't extend a shared amap.  note: no need to lock amap to
   1476 		 * look at refs since we don't care about its exact value.
   1477 		 * if it is one (i.e. we have only reference) it will stay there.
   1478 		 *
   1479 		 * note that we also can't merge two amaps, so if we
   1480 		 * merged with the previous entry which has an amap,
   1481 		 * and the next entry also has an amap, we give up.
   1482 		 *
   1483 		 * Interesting cases:
   1484 		 * amap, new, amap -> give up second merge (single fwd extend)
   1485 		 * amap, new, none -> double forward extend (extend again here)
   1486 		 * none, new, amap -> double backward extend (done here)
   1487 		 * uobj, new, amap -> single backward extend (done here)
   1488 		 *
   1489 		 * XXX should we attempt to deal with someone refilling
   1490 		 * the deallocated region between two entries that are
   1491 		 * backed by the same amap (ie, arefs is 2, "prev" and
   1492 		 * "next" refer to it, and adding this allocation will
   1493 		 * close the hole, thus restoring arefs to 1 and
   1494 		 * deallocating the "next" vm_map_entry)?  -- @@@
   1495 		 */
   1496 
   1497 		if (prev_entry->next->aref.ar_amap &&
   1498 		    (amap_refs(prev_entry->next->aref.ar_amap) != 1 ||
   1499 		     (merged && prev_entry->aref.ar_amap))) {
   1500 			goto nomerge;
   1501 		}
   1502 
   1503 		if (merged) {
   1504 			/*
   1505 			 * Try to extend the amap of the previous entry to
   1506 			 * cover the next entry as well.  If it doesn't work
   1507 			 * just skip on, don't actually give up, since we've
   1508 			 * already completed the back merge.
   1509 			 */
   1510 			if (prev_entry->aref.ar_amap) {
   1511 				if (amap_extend(prev_entry,
   1512 				    prev_entry->next->end -
   1513 				    prev_entry->next->start,
   1514 				    amapwaitflag | AMAP_EXTEND_FORWARDS))
   1515 					goto nomerge;
   1516 			}
   1517 
   1518 			/*
   1519 			 * Try to extend the amap of the *next* entry
   1520 			 * back to cover the new allocation *and* the
   1521 			 * previous entry as well (the previous merge
   1522 			 * didn't have an amap already otherwise we
   1523 			 * wouldn't be checking here for an amap).  If
   1524 			 * it doesn't work just skip on, again, don't
   1525 			 * actually give up, since we've already
   1526 			 * completed the back merge.
   1527 			 */
   1528 			else if (prev_entry->next->aref.ar_amap) {
   1529 				if (amap_extend(prev_entry->next,
   1530 				    prev_entry->end -
   1531 				    prev_entry->start,
   1532 				    amapwaitflag | AMAP_EXTEND_BACKWARDS))
   1533 					goto nomerge;
   1534 			}
   1535 		} else {
   1536 			/*
   1537 			 * Pull the next entry's amap backwards to cover this
   1538 			 * new allocation.
   1539 			 */
   1540 			if (prev_entry->next->aref.ar_amap) {
   1541 				error = amap_extend(prev_entry->next, size,
   1542 				    amapwaitflag | AMAP_EXTEND_BACKWARDS);
   1543 				if (error)
   1544 					goto nomerge;
   1545 			}
   1546 		}
   1547 
   1548 		if (merged) {
   1549 			if (kmap) {
   1550 				UVMMAP_EVCNT_DECR(kbackmerge);
   1551 				UVMMAP_EVCNT_INCR(kbimerge);
   1552 			} else {
   1553 				UVMMAP_EVCNT_DECR(ubackmerge);
   1554 				UVMMAP_EVCNT_INCR(ubimerge);
   1555 			}
   1556 		} else {
   1557 			if (kmap) {
   1558 				UVMMAP_EVCNT_INCR(kforwmerge);
   1559 			} else {
   1560 				UVMMAP_EVCNT_INCR(uforwmerge);
   1561 			}
   1562 		}
   1563 		UVMHIST_LOG(maphist,"  starting forward merge", 0, 0, 0, 0);
   1564 
   1565 		/*
   1566 		 * drop our reference to uobj since we are extending a reference
   1567 		 * that we already have (the ref count can not drop to zero).
   1568 		 * (if merged, we've already detached)
   1569 		 */
   1570 		if (uobj && uobj->pgops->pgo_detach && !merged)
   1571 			uobj->pgops->pgo_detach(uobj);
   1572 
   1573 		if (merged) {
   1574 			dead = prev_entry->next;
   1575 			prev_entry->end = dead->end;
   1576 			uvm_map_entry_unlink(map, dead);
   1577 			if (dead->aref.ar_amap != NULL) {
   1578 				prev_entry->aref = dead->aref;
   1579 				dead->aref.ar_amap = NULL;
   1580 			}
   1581 		} else {
   1582 			prev_entry->next->start -= size;
   1583 			if (prev_entry != &map->header) {
   1584 				prev_entry->gap -= size;
   1585 				KASSERT(prev_entry->gap == uvm_rb_gap(prev_entry));
   1586 				uvm_rb_fixup(map, prev_entry);
   1587 			}
   1588 			if (uobj)
   1589 				prev_entry->next->offset = uoffset;
   1590 		}
   1591 
   1592 		uvm_map_check(map, "map forwardmerged");
   1593 
   1594 		UVMHIST_LOG(maphist,"<- done forwardmerge", 0, 0, 0, 0);
   1595 		merged++;
   1596 	}
   1597 
   1598 nomerge:
   1599 	if (!merged) {
   1600 		UVMHIST_LOG(maphist,"  allocating new map entry", 0, 0, 0, 0);
   1601 		if (kmap) {
   1602 			UVMMAP_EVCNT_INCR(knomerge);
   1603 		} else {
   1604 			UVMMAP_EVCNT_INCR(unomerge);
   1605 		}
   1606 
   1607 		/*
   1608 		 * allocate new entry and link it in.
   1609 		 */
   1610 
   1611 		if (new_entry == NULL) {
   1612 			new_entry = uvm_mapent_alloc(map,
   1613 				(flags & UVM_FLAG_NOWAIT));
   1614 			if (__predict_false(new_entry == NULL)) {
   1615 				error = ENOMEM;
   1616 				goto done;
   1617 			}
   1618 		}
   1619 		new_entry->start = start;
   1620 		new_entry->end = new_entry->start + size;
   1621 		new_entry->object.uvm_obj = uobj;
   1622 		new_entry->offset = uoffset;
   1623 
   1624 		new_entry->etype = newetype;
   1625 
   1626 		if (flags & UVM_FLAG_NOMERGE) {
   1627 			new_entry->flags |= UVM_MAP_NOMERGE;
   1628 		}
   1629 
   1630 		new_entry->protection = prot;
   1631 		new_entry->max_protection = maxprot;
   1632 		new_entry->inheritance = inherit;
   1633 		new_entry->wired_count = 0;
   1634 		new_entry->advice = advice;
   1635 		if (flags & UVM_FLAG_OVERLAY) {
   1636 
   1637 			/*
   1638 			 * to_add: for BSS we overallocate a little since we
   1639 			 * are likely to extend
   1640 			 */
   1641 
   1642 			vaddr_t to_add = (flags & UVM_FLAG_AMAPPAD) ?
   1643 				UVM_AMAP_CHUNK << PAGE_SHIFT : 0;
   1644 			struct vm_amap *amap = amap_alloc(size, to_add,
   1645 			    (flags & UVM_FLAG_NOWAIT));
   1646 			if (__predict_false(amap == NULL)) {
   1647 				error = ENOMEM;
   1648 				goto done;
   1649 			}
   1650 			new_entry->aref.ar_pageoff = 0;
   1651 			new_entry->aref.ar_amap = amap;
   1652 		} else {
   1653 			new_entry->aref.ar_pageoff = 0;
   1654 			new_entry->aref.ar_amap = NULL;
   1655 		}
   1656 		uvm_map_entry_link(map, prev_entry, new_entry);
   1657 
   1658 		/*
   1659 		 * Update the free space hint
   1660 		 */
   1661 
   1662 		if ((map->first_free == prev_entry) &&
   1663 		    (prev_entry->end >= new_entry->start))
   1664 			map->first_free = new_entry;
   1665 
   1666 		new_entry = NULL;
   1667 	}
   1668 
   1669 	map->size += size;
   1670 
   1671 	UVMHIST_LOG(maphist,"<- done!", 0, 0, 0, 0);
   1672 
   1673 	error = 0;
   1674 done:
   1675 	if ((flags & UVM_FLAG_QUANTUM) == 0) {
   1676 		/*
   1677 		 * vmk_merged_entries is locked by the map's lock.
   1678 		 */
   1679 		vm_map_unlock(map);
   1680 	}
   1681 	if (new_entry && error == 0) {
   1682 		KDASSERT(merged);
   1683 		uvm_mapent_free_merged(map, new_entry);
   1684 		new_entry = NULL;
   1685 	}
   1686 	if (dead) {
   1687 		KDASSERT(merged);
   1688 		uvm_mapent_free_merged(map, dead);
   1689 	}
   1690 	if ((flags & UVM_FLAG_QUANTUM) != 0) {
   1691 		vm_map_unlock(map);
   1692 	}
   1693 	if (new_entry != NULL) {
   1694 		uvm_mapent_free(new_entry);
   1695 	}
   1696 	return error;
   1697 }
   1698 
   1699 /*
   1700  * uvm_map_lookup_entry_bytree: lookup an entry in tree
   1701  */
   1702 
   1703 static inline bool
   1704 uvm_map_lookup_entry_bytree(struct vm_map *map, vaddr_t address,
   1705     struct vm_map_entry **entry	/* OUT */)
   1706 {
   1707 	struct vm_map_entry *prev = &map->header;
   1708 	struct vm_map_entry *cur = ROOT_ENTRY(map);
   1709 
   1710 	while (cur) {
   1711 		UVMMAP_EVCNT_INCR(mlk_treeloop);
   1712 		if (address >= cur->start) {
   1713 			if (address < cur->end) {
   1714 				*entry = cur;
   1715 				return true;
   1716 			}
   1717 			prev = cur;
   1718 			cur = RIGHT_ENTRY(cur);
   1719 		} else
   1720 			cur = LEFT_ENTRY(cur);
   1721 	}
   1722 	*entry = prev;
   1723 	return false;
   1724 }
   1725 
   1726 /*
   1727  * uvm_map_lookup_entry: find map entry at or before an address
   1728  *
   1729  * => map must at least be read-locked by caller
   1730  * => entry is returned in "entry"
   1731  * => return value is true if address is in the returned entry
   1732  */
   1733 
   1734 bool
   1735 uvm_map_lookup_entry(struct vm_map *map, vaddr_t address,
   1736     struct vm_map_entry **entry	/* OUT */)
   1737 {
   1738 	struct vm_map_entry *cur;
   1739 	bool use_tree = false;
   1740 	UVMHIST_FUNC("uvm_map_lookup_entry");
   1741 	UVMHIST_CALLED(maphist);
   1742 
   1743 	UVMHIST_LOG(maphist,"(map=0x%x,addr=0x%x,ent=0x%x)",
   1744 	    map, address, entry, 0);
   1745 
   1746 	/*
   1747 	 * start looking either from the head of the
   1748 	 * list, or from the hint.
   1749 	 */
   1750 
   1751 	cur = map->hint;
   1752 
   1753 	if (cur == &map->header)
   1754 		cur = cur->next;
   1755 
   1756 	UVMMAP_EVCNT_INCR(mlk_call);
   1757 	if (address >= cur->start) {
   1758 
   1759 		/*
   1760 		 * go from hint to end of list.
   1761 		 *
   1762 		 * but first, make a quick check to see if
   1763 		 * we are already looking at the entry we
   1764 		 * want (which is usually the case).
   1765 		 * note also that we don't need to save the hint
   1766 		 * here... it is the same hint (unless we are
   1767 		 * at the header, in which case the hint didn't
   1768 		 * buy us anything anyway).
   1769 		 */
   1770 
   1771 		if (cur != &map->header && cur->end > address) {
   1772 			UVMMAP_EVCNT_INCR(mlk_hint);
   1773 			*entry = cur;
   1774 			UVMHIST_LOG(maphist,"<- got it via hint (0x%x)",
   1775 			    cur, 0, 0, 0);
   1776 			uvm_mapent_check(*entry);
   1777 			return (true);
   1778 		}
   1779 
   1780 		if (map->nentries > 15)
   1781 			use_tree = true;
   1782 	} else {
   1783 
   1784 		/*
   1785 		 * invalid hint.  use tree.
   1786 		 */
   1787 		use_tree = true;
   1788 	}
   1789 
   1790 	uvm_map_check(map, __func__);
   1791 
   1792 	if (use_tree) {
   1793 		/*
   1794 		 * Simple lookup in the tree.  Happens when the hint is
   1795 		 * invalid, or nentries reach a threshold.
   1796 		 */
   1797 		UVMMAP_EVCNT_INCR(mlk_tree);
   1798 		if (uvm_map_lookup_entry_bytree(map, address, entry)) {
   1799 			goto got;
   1800 		} else {
   1801 			goto failed;
   1802 		}
   1803 	}
   1804 
   1805 	/*
   1806 	 * search linearly
   1807 	 */
   1808 
   1809 	UVMMAP_EVCNT_INCR(mlk_list);
   1810 	while (cur != &map->header) {
   1811 		UVMMAP_EVCNT_INCR(mlk_listloop);
   1812 		if (cur->end > address) {
   1813 			if (address >= cur->start) {
   1814 				/*
   1815 				 * save this lookup for future
   1816 				 * hints, and return
   1817 				 */
   1818 
   1819 				*entry = cur;
   1820 got:
   1821 				SAVE_HINT(map, map->hint, *entry);
   1822 				UVMHIST_LOG(maphist,"<- search got it (0x%x)",
   1823 					cur, 0, 0, 0);
   1824 				KDASSERT((*entry)->start <= address);
   1825 				KDASSERT(address < (*entry)->end);
   1826 				uvm_mapent_check(*entry);
   1827 				return (true);
   1828 			}
   1829 			break;
   1830 		}
   1831 		cur = cur->next;
   1832 	}
   1833 	*entry = cur->prev;
   1834 failed:
   1835 	SAVE_HINT(map, map->hint, *entry);
   1836 	UVMHIST_LOG(maphist,"<- failed!",0,0,0,0);
   1837 	KDASSERT((*entry) == &map->header || (*entry)->end <= address);
   1838 	KDASSERT((*entry)->next == &map->header ||
   1839 	    address < (*entry)->next->start);
   1840 	return (false);
   1841 }
   1842 
   1843 /*
   1844  * See if the range between start and start + length fits in the gap
   1845  * entry->next->start and entry->end.  Returns 1 if fits, 0 if doesn't
   1846  * fit, and -1 address wraps around.
   1847  */
   1848 static int
   1849 uvm_map_space_avail(vaddr_t *start, vsize_t length, voff_t uoffset,
   1850     vsize_t align, int topdown, struct vm_map_entry *entry)
   1851 {
   1852 	vaddr_t end;
   1853 
   1854 #ifdef PMAP_PREFER
   1855 	/*
   1856 	 * push start address forward as needed to avoid VAC alias problems.
   1857 	 * we only do this if a valid offset is specified.
   1858 	 */
   1859 
   1860 	if (uoffset != UVM_UNKNOWN_OFFSET)
   1861 		PMAP_PREFER(uoffset, start, length, topdown);
   1862 #endif
   1863 	if (align != 0) {
   1864 		if ((*start & (align - 1)) != 0) {
   1865 			if (topdown)
   1866 				*start &= ~(align - 1);
   1867 			else
   1868 				*start = roundup(*start, align);
   1869 		}
   1870 		/*
   1871 		 * XXX Should we PMAP_PREFER() here again?
   1872 		 * eh...i think we're okay
   1873 		 */
   1874 	}
   1875 
   1876 	/*
   1877 	 * Find the end of the proposed new region.  Be sure we didn't
   1878 	 * wrap around the address; if so, we lose.  Otherwise, if the
   1879 	 * proposed new region fits before the next entry, we win.
   1880 	 */
   1881 
   1882 	end = *start + length;
   1883 	if (end < *start)
   1884 		return (-1);
   1885 
   1886 	if (entry->next->start >= end && *start >= entry->end)
   1887 		return (1);
   1888 
   1889 	return (0);
   1890 }
   1891 
   1892 /*
   1893  * uvm_map_findspace: find "length" sized space in "map".
   1894  *
   1895  * => "hint" is a hint about where we want it, unless UVM_FLAG_FIXED is
   1896  *	set in "flags" (in which case we insist on using "hint").
   1897  * => "result" is VA returned
   1898  * => uobj/uoffset are to be used to handle VAC alignment, if required
   1899  * => if "align" is non-zero, we attempt to align to that value.
   1900  * => caller must at least have read-locked map
   1901  * => returns NULL on failure, or pointer to prev. map entry if success
   1902  * => note this is a cross between the old vm_map_findspace and vm_map_find
   1903  */
   1904 
   1905 struct vm_map_entry *
   1906 uvm_map_findspace(struct vm_map *map, vaddr_t hint, vsize_t length,
   1907     vaddr_t *result /* OUT */, struct uvm_object *uobj, voff_t uoffset,
   1908     vsize_t align, int flags)
   1909 {
   1910 	struct vm_map_entry *entry;
   1911 	struct vm_map_entry *child, *prev, *tmp;
   1912 	vaddr_t orig_hint;
   1913 	const int topdown = map->flags & VM_MAP_TOPDOWN;
   1914 	UVMHIST_FUNC("uvm_map_findspace");
   1915 	UVMHIST_CALLED(maphist);
   1916 
   1917 	UVMHIST_LOG(maphist, "(map=0x%x, hint=0x%x, len=%d, flags=0x%x)",
   1918 	    map, hint, length, flags);
   1919 	KASSERT((align & (align - 1)) == 0);
   1920 	KASSERT((flags & UVM_FLAG_FIXED) == 0 || align == 0);
   1921 
   1922 	uvm_map_check(map, "map_findspace entry");
   1923 
   1924 	/*
   1925 	 * remember the original hint.  if we are aligning, then we
   1926 	 * may have to try again with no alignment constraint if
   1927 	 * we fail the first time.
   1928 	 */
   1929 
   1930 	orig_hint = hint;
   1931 	if (hint < vm_map_min(map)) {	/* check ranges ... */
   1932 		if (flags & UVM_FLAG_FIXED) {
   1933 			UVMHIST_LOG(maphist,"<- VA below map range",0,0,0,0);
   1934 			return (NULL);
   1935 		}
   1936 		hint = vm_map_min(map);
   1937 	}
   1938 	if (hint > vm_map_max(map)) {
   1939 		UVMHIST_LOG(maphist,"<- VA 0x%x > range [0x%x->0x%x]",
   1940 		    hint, vm_map_min(map), vm_map_max(map), 0);
   1941 		return (NULL);
   1942 	}
   1943 
   1944 	/*
   1945 	 * Look for the first possible address; if there's already
   1946 	 * something at this address, we have to start after it.
   1947 	 */
   1948 
   1949 	/*
   1950 	 * @@@: there are four, no, eight cases to consider.
   1951 	 *
   1952 	 * 0: found,     fixed,     bottom up -> fail
   1953 	 * 1: found,     fixed,     top down  -> fail
   1954 	 * 2: found,     not fixed, bottom up -> start after entry->end,
   1955 	 *                                       loop up
   1956 	 * 3: found,     not fixed, top down  -> start before entry->start,
   1957 	 *                                       loop down
   1958 	 * 4: not found, fixed,     bottom up -> check entry->next->start, fail
   1959 	 * 5: not found, fixed,     top down  -> check entry->next->start, fail
   1960 	 * 6: not found, not fixed, bottom up -> check entry->next->start,
   1961 	 *                                       loop up
   1962 	 * 7: not found, not fixed, top down  -> check entry->next->start,
   1963 	 *                                       loop down
   1964 	 *
   1965 	 * as you can see, it reduces to roughly five cases, and that
   1966 	 * adding top down mapping only adds one unique case (without
   1967 	 * it, there would be four cases).
   1968 	 */
   1969 
   1970 	if ((flags & UVM_FLAG_FIXED) == 0 && hint == vm_map_min(map)) {
   1971 		entry = map->first_free;
   1972 	} else {
   1973 		if (uvm_map_lookup_entry(map, hint, &entry)) {
   1974 			/* "hint" address already in use ... */
   1975 			if (flags & UVM_FLAG_FIXED) {
   1976 				UVMHIST_LOG(maphist, "<- fixed & VA in use",
   1977 				    0, 0, 0, 0);
   1978 				return (NULL);
   1979 			}
   1980 			if (topdown)
   1981 				/* Start from lower gap. */
   1982 				entry = entry->prev;
   1983 		} else if (flags & UVM_FLAG_FIXED) {
   1984 			if (entry->next->start >= hint + length &&
   1985 			    hint + length > hint)
   1986 				goto found;
   1987 
   1988 			/* "hint" address is gap but too small */
   1989 			UVMHIST_LOG(maphist, "<- fixed mapping failed",
   1990 			    0, 0, 0, 0);
   1991 			return (NULL); /* only one shot at it ... */
   1992 		} else {
   1993 			/*
   1994 			 * See if given hint fits in this gap.
   1995 			 */
   1996 			switch (uvm_map_space_avail(&hint, length,
   1997 			    uoffset, align, topdown, entry)) {
   1998 			case 1:
   1999 				goto found;
   2000 			case -1:
   2001 				goto wraparound;
   2002 			}
   2003 
   2004 			if (topdown) {
   2005 				/*
   2006 				 * Still there is a chance to fit
   2007 				 * if hint > entry->end.
   2008 				 */
   2009 			} else {
   2010 				/* Start from higher gap. */
   2011 				entry = entry->next;
   2012 				if (entry == &map->header)
   2013 					goto notfound;
   2014 				goto nextgap;
   2015 			}
   2016 		}
   2017 	}
   2018 
   2019 	/*
   2020 	 * Note that all UVM_FLAGS_FIXED case is already handled.
   2021 	 */
   2022 	KDASSERT((flags & UVM_FLAG_FIXED) == 0);
   2023 
   2024 	/* Try to find the space in the red-black tree */
   2025 
   2026 	/* Check slot before any entry */
   2027 	hint = topdown ? entry->next->start - length : entry->end;
   2028 	switch (uvm_map_space_avail(&hint, length, uoffset, align,
   2029 	    topdown, entry)) {
   2030 	case 1:
   2031 		goto found;
   2032 	case -1:
   2033 		goto wraparound;
   2034 	}
   2035 
   2036 nextgap:
   2037 	KDASSERT((flags & UVM_FLAG_FIXED) == 0);
   2038 	/* If there is not enough space in the whole tree, we fail */
   2039 	tmp = ROOT_ENTRY(map);
   2040 	if (tmp == NULL || tmp->maxgap < length)
   2041 		goto notfound;
   2042 
   2043 	prev = NULL; /* previous candidate */
   2044 
   2045 	/* Find an entry close to hint that has enough space */
   2046 	for (; tmp;) {
   2047 		KASSERT(tmp->next->start == tmp->end + tmp->gap);
   2048 		if (topdown) {
   2049 			if (tmp->next->start < hint + length &&
   2050 			    (prev == NULL || tmp->end > prev->end)) {
   2051 				if (tmp->gap >= length)
   2052 					prev = tmp;
   2053 				else if ((child = LEFT_ENTRY(tmp)) != NULL
   2054 				    && child->maxgap >= length)
   2055 					prev = tmp;
   2056 			}
   2057 		} else {
   2058 			if (tmp->end >= hint &&
   2059 			    (prev == NULL || tmp->end < prev->end)) {
   2060 				if (tmp->gap >= length)
   2061 					prev = tmp;
   2062 				else if ((child = RIGHT_ENTRY(tmp)) != NULL
   2063 				    && child->maxgap >= length)
   2064 					prev = tmp;
   2065 			}
   2066 		}
   2067 		if (tmp->next->start < hint + length)
   2068 			child = RIGHT_ENTRY(tmp);
   2069 		else if (tmp->end > hint)
   2070 			child = LEFT_ENTRY(tmp);
   2071 		else {
   2072 			if (tmp->gap >= length)
   2073 				break;
   2074 			if (topdown)
   2075 				child = LEFT_ENTRY(tmp);
   2076 			else
   2077 				child = RIGHT_ENTRY(tmp);
   2078 		}
   2079 		if (child == NULL || child->maxgap < length)
   2080 			break;
   2081 		tmp = child;
   2082 	}
   2083 
   2084 	if (tmp != NULL && tmp->start < hint && hint < tmp->next->start) {
   2085 		/*
   2086 		 * Check if the entry that we found satifies the
   2087 		 * space requirement
   2088 		 */
   2089 		if (topdown) {
   2090 			if (hint > tmp->next->start - length)
   2091 				hint = tmp->next->start - length;
   2092 		} else {
   2093 			if (hint < tmp->end)
   2094 				hint = tmp->end;
   2095 		}
   2096 		switch (uvm_map_space_avail(&hint, length, uoffset, align,
   2097 		    topdown, tmp)) {
   2098 		case 1:
   2099 			entry = tmp;
   2100 			goto found;
   2101 		case -1:
   2102 			goto wraparound;
   2103 		}
   2104 		if (tmp->gap >= length)
   2105 			goto listsearch;
   2106 	}
   2107 	if (prev == NULL)
   2108 		goto notfound;
   2109 
   2110 	if (topdown) {
   2111 		KASSERT(orig_hint >= prev->next->start - length ||
   2112 		    prev->next->start - length > prev->next->start);
   2113 		hint = prev->next->start - length;
   2114 	} else {
   2115 		KASSERT(orig_hint <= prev->end);
   2116 		hint = prev->end;
   2117 	}
   2118 	switch (uvm_map_space_avail(&hint, length, uoffset, align,
   2119 	    topdown, prev)) {
   2120 	case 1:
   2121 		entry = prev;
   2122 		goto found;
   2123 	case -1:
   2124 		goto wraparound;
   2125 	}
   2126 	if (prev->gap >= length)
   2127 		goto listsearch;
   2128 
   2129 	if (topdown)
   2130 		tmp = LEFT_ENTRY(prev);
   2131 	else
   2132 		tmp = RIGHT_ENTRY(prev);
   2133 	for (;;) {
   2134 		KASSERT(tmp && tmp->maxgap >= length);
   2135 		if (topdown)
   2136 			child = RIGHT_ENTRY(tmp);
   2137 		else
   2138 			child = LEFT_ENTRY(tmp);
   2139 		if (child && child->maxgap >= length) {
   2140 			tmp = child;
   2141 			continue;
   2142 		}
   2143 		if (tmp->gap >= length)
   2144 			break;
   2145 		if (topdown)
   2146 			tmp = LEFT_ENTRY(tmp);
   2147 		else
   2148 			tmp = RIGHT_ENTRY(tmp);
   2149 	}
   2150 
   2151 	if (topdown) {
   2152 		KASSERT(orig_hint >= tmp->next->start - length ||
   2153 		    tmp->next->start - length > tmp->next->start);
   2154 		hint = tmp->next->start - length;
   2155 	} else {
   2156 		KASSERT(orig_hint <= tmp->end);
   2157 		hint = tmp->end;
   2158 	}
   2159 	switch (uvm_map_space_avail(&hint, length, uoffset, align,
   2160 	    topdown, tmp)) {
   2161 	case 1:
   2162 		entry = tmp;
   2163 		goto found;
   2164 	case -1:
   2165 		goto wraparound;
   2166 	}
   2167 
   2168 	/*
   2169 	 * The tree fails to find an entry because of offset or alignment
   2170 	 * restrictions.  Search the list instead.
   2171 	 */
   2172  listsearch:
   2173 	/*
   2174 	 * Look through the rest of the map, trying to fit a new region in
   2175 	 * the gap between existing regions, or after the very last region.
   2176 	 * note: entry->end = base VA of current gap,
   2177 	 *	 entry->next->start = VA of end of current gap
   2178 	 */
   2179 
   2180 	for (;;) {
   2181 		/* Update hint for current gap. */
   2182 		hint = topdown ? entry->next->start - length : entry->end;
   2183 
   2184 		/* See if it fits. */
   2185 		switch (uvm_map_space_avail(&hint, length, uoffset, align,
   2186 		    topdown, entry)) {
   2187 		case 1:
   2188 			goto found;
   2189 		case -1:
   2190 			goto wraparound;
   2191 		}
   2192 
   2193 		/* Advance to next/previous gap */
   2194 		if (topdown) {
   2195 			if (entry == &map->header) {
   2196 				UVMHIST_LOG(maphist, "<- failed (off start)",
   2197 				    0,0,0,0);
   2198 				goto notfound;
   2199 			}
   2200 			entry = entry->prev;
   2201 		} else {
   2202 			entry = entry->next;
   2203 			if (entry == &map->header) {
   2204 				UVMHIST_LOG(maphist, "<- failed (off end)",
   2205 				    0,0,0,0);
   2206 				goto notfound;
   2207 			}
   2208 		}
   2209 	}
   2210 
   2211  found:
   2212 	SAVE_HINT(map, map->hint, entry);
   2213 	*result = hint;
   2214 	UVMHIST_LOG(maphist,"<- got it!  (result=0x%x)", hint, 0,0,0);
   2215 	KASSERT( topdown || hint >= orig_hint);
   2216 	KASSERT(!topdown || hint <= orig_hint);
   2217 	KASSERT(entry->end <= hint);
   2218 	KASSERT(hint + length <= entry->next->start);
   2219 	return (entry);
   2220 
   2221  wraparound:
   2222 	UVMHIST_LOG(maphist, "<- failed (wrap around)", 0,0,0,0);
   2223 
   2224 	return (NULL);
   2225 
   2226  notfound:
   2227 	UVMHIST_LOG(maphist, "<- failed (notfound)", 0,0,0,0);
   2228 
   2229 	return (NULL);
   2230 }
   2231 
   2232 /*
   2233  *   U N M A P   -   m a i n   h e l p e r   f u n c t i o n s
   2234  */
   2235 
   2236 /*
   2237  * uvm_unmap_remove: remove mappings from a vm_map (from "start" up to "stop")
   2238  *
   2239  * => caller must check alignment and size
   2240  * => map must be locked by caller
   2241  * => we return a list of map entries that we've remove from the map
   2242  *    in "entry_list"
   2243  */
   2244 
   2245 void
   2246 uvm_unmap_remove(struct vm_map *map, vaddr_t start, vaddr_t end,
   2247     struct vm_map_entry **entry_list /* OUT */,
   2248     struct uvm_mapent_reservation *umr, int flags)
   2249 {
   2250 	struct vm_map_entry *entry, *first_entry, *next;
   2251 	vaddr_t len;
   2252 	UVMHIST_FUNC("uvm_unmap_remove"); UVMHIST_CALLED(maphist);
   2253 
   2254 	UVMHIST_LOG(maphist,"(map=0x%x, start=0x%x, end=0x%x)",
   2255 	    map, start, end, 0);
   2256 	VM_MAP_RANGE_CHECK(map, start, end);
   2257 
   2258 	uvm_map_check(map, "unmap_remove entry");
   2259 
   2260 	/*
   2261 	 * find first entry
   2262 	 */
   2263 
   2264 	if (uvm_map_lookup_entry(map, start, &first_entry) == true) {
   2265 		/* clip and go... */
   2266 		entry = first_entry;
   2267 		UVM_MAP_CLIP_START(map, entry, start, umr);
   2268 		/* critical!  prevents stale hint */
   2269 		SAVE_HINT(map, entry, entry->prev);
   2270 	} else {
   2271 		entry = first_entry->next;
   2272 	}
   2273 
   2274 	/*
   2275 	 * Save the free space hint
   2276 	 */
   2277 
   2278 	if (map->first_free != &map->header && map->first_free->start >= start)
   2279 		map->first_free = entry->prev;
   2280 
   2281 	/*
   2282 	 * note: we now re-use first_entry for a different task.  we remove
   2283 	 * a number of map entries from the map and save them in a linked
   2284 	 * list headed by "first_entry".  once we remove them from the map
   2285 	 * the caller should unlock the map and drop the references to the
   2286 	 * backing objects [c.f. uvm_unmap_detach].  the object is to
   2287 	 * separate unmapping from reference dropping.  why?
   2288 	 *   [1] the map has to be locked for unmapping
   2289 	 *   [2] the map need not be locked for reference dropping
   2290 	 *   [3] dropping references may trigger pager I/O, and if we hit
   2291 	 *       a pager that does synchronous I/O we may have to wait for it.
   2292 	 *   [4] we would like all waiting for I/O to occur with maps unlocked
   2293 	 *       so that we don't block other threads.
   2294 	 */
   2295 
   2296 	first_entry = NULL;
   2297 	*entry_list = NULL;
   2298 
   2299 	/*
   2300 	 * break up the area into map entry sized regions and unmap.  note
   2301 	 * that all mappings have to be removed before we can even consider
   2302 	 * dropping references to amaps or VM objects (otherwise we could end
   2303 	 * up with a mapping to a page on the free list which would be very bad)
   2304 	 */
   2305 
   2306 	while ((entry != &map->header) && (entry->start < end)) {
   2307 		KASSERT((entry->flags & UVM_MAP_FIRST) == 0);
   2308 
   2309 		UVM_MAP_CLIP_END(map, entry, end, umr);
   2310 		next = entry->next;
   2311 		len = entry->end - entry->start;
   2312 
   2313 		/*
   2314 		 * unwire before removing addresses from the pmap; otherwise
   2315 		 * unwiring will put the entries back into the pmap (XXX).
   2316 		 */
   2317 
   2318 		if (VM_MAPENT_ISWIRED(entry)) {
   2319 			uvm_map_entry_unwire(map, entry);
   2320 		}
   2321 		if (flags & UVM_FLAG_VAONLY) {
   2322 
   2323 			/* nothing */
   2324 
   2325 		} else if ((map->flags & VM_MAP_PAGEABLE) == 0) {
   2326 
   2327 			/*
   2328 			 * if the map is non-pageable, any pages mapped there
   2329 			 * must be wired and entered with pmap_kenter_pa(),
   2330 			 * and we should free any such pages immediately.
   2331 			 * this is mostly used for kmem_map and mb_map.
   2332 			 */
   2333 
   2334 			if ((entry->flags & UVM_MAP_KMAPENT) == 0) {
   2335 				uvm_km_pgremove_intrsafe(map, entry->start,
   2336 				    entry->end);
   2337 				pmap_kremove(entry->start, len);
   2338 			}
   2339 		} else if (UVM_ET_ISOBJ(entry) &&
   2340 			   UVM_OBJ_IS_KERN_OBJECT(entry->object.uvm_obj)) {
   2341 			KASSERT(vm_map_pmap(map) == pmap_kernel());
   2342 
   2343 			/*
   2344 			 * note: kernel object mappings are currently used in
   2345 			 * two ways:
   2346 			 *  [1] "normal" mappings of pages in the kernel object
   2347 			 *  [2] uvm_km_valloc'd allocations in which we
   2348 			 *      pmap_enter in some non-kernel-object page
   2349 			 *      (e.g. vmapbuf).
   2350 			 *
   2351 			 * for case [1], we need to remove the mapping from
   2352 			 * the pmap and then remove the page from the kernel
   2353 			 * object (because, once pages in a kernel object are
   2354 			 * unmapped they are no longer needed, unlike, say,
   2355 			 * a vnode where you might want the data to persist
   2356 			 * until flushed out of a queue).
   2357 			 *
   2358 			 * for case [2], we need to remove the mapping from
   2359 			 * the pmap.  there shouldn't be any pages at the
   2360 			 * specified offset in the kernel object [but it
   2361 			 * doesn't hurt to call uvm_km_pgremove just to be
   2362 			 * safe?]
   2363 			 *
   2364 			 * uvm_km_pgremove currently does the following:
   2365 			 *   for pages in the kernel object in range:
   2366 			 *     - drops the swap slot
   2367 			 *     - uvm_pagefree the page
   2368 			 */
   2369 
   2370 			/*
   2371 			 * remove mappings from pmap and drop the pages
   2372 			 * from the object.  offsets are always relative
   2373 			 * to vm_map_min(kernel_map).
   2374 			 */
   2375 
   2376 			pmap_remove(pmap_kernel(), entry->start,
   2377 			    entry->start + len);
   2378 			uvm_km_pgremove(entry->start, entry->end);
   2379 
   2380 			/*
   2381 			 * null out kernel_object reference, we've just
   2382 			 * dropped it
   2383 			 */
   2384 
   2385 			entry->etype &= ~UVM_ET_OBJ;
   2386 			entry->object.uvm_obj = NULL;
   2387 		} else if (UVM_ET_ISOBJ(entry) || entry->aref.ar_amap) {
   2388 
   2389 			/*
   2390 			 * remove mappings the standard way.
   2391 			 */
   2392 
   2393 			pmap_remove(map->pmap, entry->start, entry->end);
   2394 		}
   2395 
   2396 #if defined(DEBUG)
   2397 		if ((entry->flags & UVM_MAP_KMAPENT) == 0) {
   2398 
   2399 			/*
   2400 			 * check if there's remaining mapping,
   2401 			 * which is a bug in caller.
   2402 			 */
   2403 
   2404 			vaddr_t va;
   2405 			for (va = entry->start; va < entry->end;
   2406 			    va += PAGE_SIZE) {
   2407 				if (pmap_extract(vm_map_pmap(map), va, NULL)) {
   2408 					panic("uvm_unmap_remove: has mapping");
   2409 				}
   2410 			}
   2411 
   2412 			if (VM_MAP_IS_KERNEL(map)) {
   2413 				uvm_km_check_empty(map, entry->start,
   2414 				    entry->end);
   2415 			}
   2416 		}
   2417 #endif /* defined(DEBUG) */
   2418 
   2419 		/*
   2420 		 * remove entry from map and put it on our list of entries
   2421 		 * that we've nuked.  then go to next entry.
   2422 		 */
   2423 
   2424 		UVMHIST_LOG(maphist, "  removed map entry 0x%x", entry, 0, 0,0);
   2425 
   2426 		/* critical!  prevents stale hint */
   2427 		SAVE_HINT(map, entry, entry->prev);
   2428 
   2429 		uvm_map_entry_unlink(map, entry);
   2430 		KASSERT(map->size >= len);
   2431 		map->size -= len;
   2432 		entry->prev = NULL;
   2433 		entry->next = first_entry;
   2434 		first_entry = entry;
   2435 		entry = next;
   2436 	}
   2437 	if ((map->flags & VM_MAP_DYING) == 0) {
   2438 		pmap_update(vm_map_pmap(map));
   2439 	}
   2440 
   2441 	uvm_map_check(map, "unmap_remove leave");
   2442 
   2443 	/*
   2444 	 * now we've cleaned up the map and are ready for the caller to drop
   2445 	 * references to the mapped objects.
   2446 	 */
   2447 
   2448 	*entry_list = first_entry;
   2449 	UVMHIST_LOG(maphist,"<- done!", 0, 0, 0, 0);
   2450 
   2451 	if (map->flags & VM_MAP_WANTVA) {
   2452 		mutex_enter(&map->misc_lock);
   2453 		map->flags &= ~VM_MAP_WANTVA;
   2454 		cv_broadcast(&map->cv);
   2455 		mutex_exit(&map->misc_lock);
   2456 	}
   2457 }
   2458 
   2459 /*
   2460  * uvm_unmap_detach: drop references in a chain of map entries
   2461  *
   2462  * => we will free the map entries as we traverse the list.
   2463  */
   2464 
   2465 void
   2466 uvm_unmap_detach(struct vm_map_entry *first_entry, int flags)
   2467 {
   2468 	struct vm_map_entry *next_entry;
   2469 	UVMHIST_FUNC("uvm_unmap_detach"); UVMHIST_CALLED(maphist);
   2470 
   2471 	while (first_entry) {
   2472 		KASSERT(!VM_MAPENT_ISWIRED(first_entry));
   2473 		UVMHIST_LOG(maphist,
   2474 		    "  detach 0x%x: amap=0x%x, obj=0x%x, submap?=%d",
   2475 		    first_entry, first_entry->aref.ar_amap,
   2476 		    first_entry->object.uvm_obj,
   2477 		    UVM_ET_ISSUBMAP(first_entry));
   2478 
   2479 		/*
   2480 		 * drop reference to amap, if we've got one
   2481 		 */
   2482 
   2483 		if (first_entry->aref.ar_amap)
   2484 			uvm_map_unreference_amap(first_entry, flags);
   2485 
   2486 		/*
   2487 		 * drop reference to our backing object, if we've got one
   2488 		 */
   2489 
   2490 		KASSERT(!UVM_ET_ISSUBMAP(first_entry));
   2491 		if (UVM_ET_ISOBJ(first_entry) &&
   2492 		    first_entry->object.uvm_obj->pgops->pgo_detach) {
   2493 			(*first_entry->object.uvm_obj->pgops->pgo_detach)
   2494 				(first_entry->object.uvm_obj);
   2495 		}
   2496 		next_entry = first_entry->next;
   2497 		uvm_mapent_free(first_entry);
   2498 		first_entry = next_entry;
   2499 	}
   2500 	UVMHIST_LOG(maphist, "<- done", 0,0,0,0);
   2501 }
   2502 
   2503 /*
   2504  *   E X T R A C T I O N   F U N C T I O N S
   2505  */
   2506 
   2507 /*
   2508  * uvm_map_reserve: reserve space in a vm_map for future use.
   2509  *
   2510  * => we reserve space in a map by putting a dummy map entry in the
   2511  *    map (dummy means obj=NULL, amap=NULL, prot=VM_PROT_NONE)
   2512  * => map should be unlocked (we will write lock it)
   2513  * => we return true if we were able to reserve space
   2514  * => XXXCDC: should be inline?
   2515  */
   2516 
   2517 int
   2518 uvm_map_reserve(struct vm_map *map, vsize_t size,
   2519     vaddr_t offset	/* hint for pmap_prefer */,
   2520     vsize_t align	/* alignment */,
   2521     vaddr_t *raddr	/* IN:hint, OUT: reserved VA */,
   2522     uvm_flag_t flags	/* UVM_FLAG_FIXED or 0 */)
   2523 {
   2524 	UVMHIST_FUNC("uvm_map_reserve"); UVMHIST_CALLED(maphist);
   2525 
   2526 	UVMHIST_LOG(maphist, "(map=0x%x, size=0x%x, offset=0x%x,addr=0x%x)",
   2527 	    map,size,offset,raddr);
   2528 
   2529 	size = round_page(size);
   2530 
   2531 	/*
   2532 	 * reserve some virtual space.
   2533 	 */
   2534 
   2535 	if (uvm_map(map, raddr, size, NULL, offset, align,
   2536 	    UVM_MAPFLAG(UVM_PROT_NONE, UVM_PROT_NONE, UVM_INH_NONE,
   2537 	    UVM_ADV_RANDOM, UVM_FLAG_NOMERGE|flags)) != 0) {
   2538 	    UVMHIST_LOG(maphist, "<- done (no VM)", 0,0,0,0);
   2539 		return (false);
   2540 	}
   2541 
   2542 	UVMHIST_LOG(maphist, "<- done (*raddr=0x%x)", *raddr,0,0,0);
   2543 	return (true);
   2544 }
   2545 
   2546 /*
   2547  * uvm_map_replace: replace a reserved (blank) area of memory with
   2548  * real mappings.
   2549  *
   2550  * => caller must WRITE-LOCK the map
   2551  * => we return true if replacement was a success
   2552  * => we expect the newents chain to have nnewents entrys on it and
   2553  *    we expect newents->prev to point to the last entry on the list
   2554  * => note newents is allowed to be NULL
   2555  */
   2556 
   2557 int
   2558 uvm_map_replace(struct vm_map *map, vaddr_t start, vaddr_t end,
   2559     struct vm_map_entry *newents, int nnewents, struct vm_map_entry **oldentryp)
   2560 {
   2561 	struct vm_map_entry *oldent, *last;
   2562 
   2563 	uvm_map_check(map, "map_replace entry");
   2564 
   2565 	/*
   2566 	 * first find the blank map entry at the specified address
   2567 	 */
   2568 
   2569 	if (!uvm_map_lookup_entry(map, start, &oldent)) {
   2570 		return (false);
   2571 	}
   2572 
   2573 	/*
   2574 	 * check to make sure we have a proper blank entry
   2575 	 */
   2576 
   2577 	if (end < oldent->end && !VM_MAP_USE_KMAPENT(map)) {
   2578 		UVM_MAP_CLIP_END(map, oldent, end, NULL);
   2579 	}
   2580 	if (oldent->start != start || oldent->end != end ||
   2581 	    oldent->object.uvm_obj != NULL || oldent->aref.ar_amap != NULL) {
   2582 		return (false);
   2583 	}
   2584 
   2585 #ifdef DIAGNOSTIC
   2586 
   2587 	/*
   2588 	 * sanity check the newents chain
   2589 	 */
   2590 
   2591 	{
   2592 		struct vm_map_entry *tmpent = newents;
   2593 		int nent = 0;
   2594 		vaddr_t cur = start;
   2595 
   2596 		while (tmpent) {
   2597 			nent++;
   2598 			if (tmpent->start < cur)
   2599 				panic("uvm_map_replace1");
   2600 			if (tmpent->start > tmpent->end || tmpent->end > end) {
   2601 		printf("tmpent->start=0x%lx, tmpent->end=0x%lx, end=0x%lx\n",
   2602 			    tmpent->start, tmpent->end, end);
   2603 				panic("uvm_map_replace2");
   2604 			}
   2605 			cur = tmpent->end;
   2606 			if (tmpent->next) {
   2607 				if (tmpent->next->prev != tmpent)
   2608 					panic("uvm_map_replace3");
   2609 			} else {
   2610 				if (newents->prev != tmpent)
   2611 					panic("uvm_map_replace4");
   2612 			}
   2613 			tmpent = tmpent->next;
   2614 		}
   2615 		if (nent != nnewents)
   2616 			panic("uvm_map_replace5");
   2617 	}
   2618 #endif
   2619 
   2620 	/*
   2621 	 * map entry is a valid blank!   replace it.   (this does all the
   2622 	 * work of map entry link/unlink...).
   2623 	 */
   2624 
   2625 	if (newents) {
   2626 		last = newents->prev;
   2627 
   2628 		/* critical: flush stale hints out of map */
   2629 		SAVE_HINT(map, map->hint, newents);
   2630 		if (map->first_free == oldent)
   2631 			map->first_free = last;
   2632 
   2633 		last->next = oldent->next;
   2634 		last->next->prev = last;
   2635 
   2636 		/* Fix RB tree */
   2637 		uvm_rb_remove(map, oldent);
   2638 
   2639 		newents->prev = oldent->prev;
   2640 		newents->prev->next = newents;
   2641 		map->nentries = map->nentries + (nnewents - 1);
   2642 
   2643 		/* Fixup the RB tree */
   2644 		{
   2645 			int i;
   2646 			struct vm_map_entry *tmp;
   2647 
   2648 			tmp = newents;
   2649 			for (i = 0; i < nnewents && tmp; i++) {
   2650 				uvm_rb_insert(map, tmp);
   2651 				tmp = tmp->next;
   2652 			}
   2653 		}
   2654 	} else {
   2655 		/* NULL list of new entries: just remove the old one */
   2656 		clear_hints(map, oldent);
   2657 		uvm_map_entry_unlink(map, oldent);
   2658 	}
   2659 
   2660 	uvm_map_check(map, "map_replace leave");
   2661 
   2662 	/*
   2663 	 * now we can free the old blank entry and return.
   2664 	 */
   2665 
   2666 	*oldentryp = oldent;
   2667 	return (true);
   2668 }
   2669 
   2670 /*
   2671  * uvm_map_extract: extract a mapping from a map and put it somewhere
   2672  *	(maybe removing the old mapping)
   2673  *
   2674  * => maps should be unlocked (we will write lock them)
   2675  * => returns 0 on success, error code otherwise
   2676  * => start must be page aligned
   2677  * => len must be page sized
   2678  * => flags:
   2679  *      UVM_EXTRACT_REMOVE: remove mappings from srcmap
   2680  *      UVM_EXTRACT_CONTIG: abort if unmapped area (advisory only)
   2681  *      UVM_EXTRACT_QREF: for a temporary extraction do quick obj refs
   2682  *      UVM_EXTRACT_FIXPROT: set prot to maxprot as we go
   2683  *    >>>NOTE: if you set REMOVE, you are not allowed to use CONTIG or QREF!<<<
   2684  *    >>>NOTE: QREF's must be unmapped via the QREF path, thus should only
   2685  *             be used from within the kernel in a kernel level map <<<
   2686  */
   2687 
   2688 int
   2689 uvm_map_extract(struct vm_map *srcmap, vaddr_t start, vsize_t len,
   2690     struct vm_map *dstmap, vaddr_t *dstaddrp, int flags)
   2691 {
   2692 	vaddr_t dstaddr, end, newend, oldoffset, fudge, orig_fudge;
   2693 	struct vm_map_entry *chain, *endchain, *entry, *orig_entry, *newentry,
   2694 	    *deadentry, *oldentry;
   2695 	struct vm_map_entry *resentry = NULL; /* a dummy reservation entry */
   2696 	vsize_t elen;
   2697 	int nchain, error, copy_ok;
   2698 	UVMHIST_FUNC("uvm_map_extract"); UVMHIST_CALLED(maphist);
   2699 
   2700 	UVMHIST_LOG(maphist,"(srcmap=0x%x,start=0x%x, len=0x%x", srcmap, start,
   2701 	    len,0);
   2702 	UVMHIST_LOG(maphist," ...,dstmap=0x%x, flags=0x%x)", dstmap,flags,0,0);
   2703 
   2704 	uvm_map_check(srcmap, "map_extract src enter");
   2705 	uvm_map_check(dstmap, "map_extract dst enter");
   2706 
   2707 	/*
   2708 	 * step 0: sanity check: start must be on a page boundary, length
   2709 	 * must be page sized.  can't ask for CONTIG/QREF if you asked for
   2710 	 * REMOVE.
   2711 	 */
   2712 
   2713 	KASSERT((start & PAGE_MASK) == 0 && (len & PAGE_MASK) == 0);
   2714 	KASSERT((flags & UVM_EXTRACT_REMOVE) == 0 ||
   2715 		(flags & (UVM_EXTRACT_CONTIG|UVM_EXTRACT_QREF)) == 0);
   2716 
   2717 	/*
   2718 	 * step 1: reserve space in the target map for the extracted area
   2719 	 */
   2720 
   2721 	if ((flags & UVM_EXTRACT_RESERVED) == 0) {
   2722 		dstaddr = vm_map_min(dstmap);
   2723 		if (!uvm_map_reserve(dstmap, len, start, 0, &dstaddr, 0))
   2724 			return (ENOMEM);
   2725 		*dstaddrp = dstaddr;	/* pass address back to caller */
   2726 		UVMHIST_LOG(maphist, "  dstaddr=0x%x", dstaddr,0,0,0);
   2727 	} else {
   2728 		dstaddr = *dstaddrp;
   2729 	}
   2730 
   2731 	/*
   2732 	 * step 2: setup for the extraction process loop by init'ing the
   2733 	 * map entry chain, locking src map, and looking up the first useful
   2734 	 * entry in the map.
   2735 	 */
   2736 
   2737 	end = start + len;
   2738 	newend = dstaddr + len;
   2739 	chain = endchain = NULL;
   2740 	nchain = 0;
   2741 	vm_map_lock(srcmap);
   2742 
   2743 	if (uvm_map_lookup_entry(srcmap, start, &entry)) {
   2744 
   2745 		/* "start" is within an entry */
   2746 		if (flags & UVM_EXTRACT_QREF) {
   2747 
   2748 			/*
   2749 			 * for quick references we don't clip the entry, so
   2750 			 * the entry may map space "before" the starting
   2751 			 * virtual address... this is the "fudge" factor
   2752 			 * (which can be non-zero only the first time
   2753 			 * through the "while" loop in step 3).
   2754 			 */
   2755 
   2756 			fudge = start - entry->start;
   2757 		} else {
   2758 
   2759 			/*
   2760 			 * normal reference: we clip the map to fit (thus
   2761 			 * fudge is zero)
   2762 			 */
   2763 
   2764 			UVM_MAP_CLIP_START(srcmap, entry, start, NULL);
   2765 			SAVE_HINT(srcmap, srcmap->hint, entry->prev);
   2766 			fudge = 0;
   2767 		}
   2768 	} else {
   2769 
   2770 		/* "start" is not within an entry ... skip to next entry */
   2771 		if (flags & UVM_EXTRACT_CONTIG) {
   2772 			error = EINVAL;
   2773 			goto bad;    /* definite hole here ... */
   2774 		}
   2775 
   2776 		entry = entry->next;
   2777 		fudge = 0;
   2778 	}
   2779 
   2780 	/* save values from srcmap for step 6 */
   2781 	orig_entry = entry;
   2782 	orig_fudge = fudge;
   2783 
   2784 	/*
   2785 	 * step 3: now start looping through the map entries, extracting
   2786 	 * as we go.
   2787 	 */
   2788 
   2789 	while (entry->start < end && entry != &srcmap->header) {
   2790 
   2791 		/* if we are not doing a quick reference, clip it */
   2792 		if ((flags & UVM_EXTRACT_QREF) == 0)
   2793 			UVM_MAP_CLIP_END(srcmap, entry, end, NULL);
   2794 
   2795 		/* clear needs_copy (allow chunking) */
   2796 		if (UVM_ET_ISNEEDSCOPY(entry)) {
   2797 			amap_copy(srcmap, entry,
   2798 			    AMAP_COPY_NOWAIT|AMAP_COPY_NOMERGE, start, end);
   2799 			if (UVM_ET_ISNEEDSCOPY(entry)) {  /* failed? */
   2800 				error = ENOMEM;
   2801 				goto bad;
   2802 			}
   2803 
   2804 			/* amap_copy could clip (during chunk)!  update fudge */
   2805 			if (fudge) {
   2806 				fudge = start - entry->start;
   2807 				orig_fudge = fudge;
   2808 			}
   2809 		}
   2810 
   2811 		/* calculate the offset of this from "start" */
   2812 		oldoffset = (entry->start + fudge) - start;
   2813 
   2814 		/* allocate a new map entry */
   2815 		newentry = uvm_mapent_alloc(dstmap, 0);
   2816 		if (newentry == NULL) {
   2817 			error = ENOMEM;
   2818 			goto bad;
   2819 		}
   2820 
   2821 		/* set up new map entry */
   2822 		newentry->next = NULL;
   2823 		newentry->prev = endchain;
   2824 		newentry->start = dstaddr + oldoffset;
   2825 		newentry->end =
   2826 		    newentry->start + (entry->end - (entry->start + fudge));
   2827 		if (newentry->end > newend || newentry->end < newentry->start)
   2828 			newentry->end = newend;
   2829 		newentry->object.uvm_obj = entry->object.uvm_obj;
   2830 		if (newentry->object.uvm_obj) {
   2831 			if (newentry->object.uvm_obj->pgops->pgo_reference)
   2832 				newentry->object.uvm_obj->pgops->
   2833 				    pgo_reference(newentry->object.uvm_obj);
   2834 				newentry->offset = entry->offset + fudge;
   2835 		} else {
   2836 			newentry->offset = 0;
   2837 		}
   2838 		newentry->etype = entry->etype;
   2839 		newentry->protection = (flags & UVM_EXTRACT_FIXPROT) ?
   2840 			entry->max_protection : entry->protection;
   2841 		newentry->max_protection = entry->max_protection;
   2842 		newentry->inheritance = entry->inheritance;
   2843 		newentry->wired_count = 0;
   2844 		newentry->aref.ar_amap = entry->aref.ar_amap;
   2845 		if (newentry->aref.ar_amap) {
   2846 			newentry->aref.ar_pageoff =
   2847 			    entry->aref.ar_pageoff + (fudge >> PAGE_SHIFT);
   2848 			uvm_map_reference_amap(newentry, AMAP_SHARED |
   2849 			    ((flags & UVM_EXTRACT_QREF) ? AMAP_REFALL : 0));
   2850 		} else {
   2851 			newentry->aref.ar_pageoff = 0;
   2852 		}
   2853 		newentry->advice = entry->advice;
   2854 		if ((flags & UVM_EXTRACT_QREF) != 0) {
   2855 			newentry->flags |= UVM_MAP_NOMERGE;
   2856 		}
   2857 
   2858 		/* now link it on the chain */
   2859 		nchain++;
   2860 		if (endchain == NULL) {
   2861 			chain = endchain = newentry;
   2862 		} else {
   2863 			endchain->next = newentry;
   2864 			endchain = newentry;
   2865 		}
   2866 
   2867 		/* end of 'while' loop! */
   2868 		if ((flags & UVM_EXTRACT_CONTIG) && entry->end < end &&
   2869 		    (entry->next == &srcmap->header ||
   2870 		    entry->next->start != entry->end)) {
   2871 			error = EINVAL;
   2872 			goto bad;
   2873 		}
   2874 		entry = entry->next;
   2875 		fudge = 0;
   2876 	}
   2877 
   2878 	/*
   2879 	 * step 4: close off chain (in format expected by uvm_map_replace)
   2880 	 */
   2881 
   2882 	if (chain)
   2883 		chain->prev = endchain;
   2884 
   2885 	/*
   2886 	 * step 5: attempt to lock the dest map so we can pmap_copy.
   2887 	 * note usage of copy_ok:
   2888 	 *   1 => dstmap locked, pmap_copy ok, and we "replace" here (step 5)
   2889 	 *   0 => dstmap unlocked, NO pmap_copy, and we will "replace" in step 7
   2890 	 */
   2891 
   2892 	if (srcmap == dstmap || vm_map_lock_try(dstmap) == true) {
   2893 		copy_ok = 1;
   2894 		if (!uvm_map_replace(dstmap, dstaddr, dstaddr+len, chain,
   2895 		    nchain, &resentry)) {
   2896 			if (srcmap != dstmap)
   2897 				vm_map_unlock(dstmap);
   2898 			error = EIO;
   2899 			goto bad;
   2900 		}
   2901 	} else {
   2902 		copy_ok = 0;
   2903 		/* replace defered until step 7 */
   2904 	}
   2905 
   2906 	/*
   2907 	 * step 6: traverse the srcmap a second time to do the following:
   2908 	 *  - if we got a lock on the dstmap do pmap_copy
   2909 	 *  - if UVM_EXTRACT_REMOVE remove the entries
   2910 	 * we make use of orig_entry and orig_fudge (saved in step 2)
   2911 	 */
   2912 
   2913 	if (copy_ok || (flags & UVM_EXTRACT_REMOVE)) {
   2914 
   2915 		/* purge possible stale hints from srcmap */
   2916 		if (flags & UVM_EXTRACT_REMOVE) {
   2917 			SAVE_HINT(srcmap, srcmap->hint, orig_entry->prev);
   2918 			if (srcmap->first_free != &srcmap->header &&
   2919 			    srcmap->first_free->start >= start)
   2920 				srcmap->first_free = orig_entry->prev;
   2921 		}
   2922 
   2923 		entry = orig_entry;
   2924 		fudge = orig_fudge;
   2925 		deadentry = NULL;	/* for UVM_EXTRACT_REMOVE */
   2926 
   2927 		while (entry->start < end && entry != &srcmap->header) {
   2928 			if (copy_ok) {
   2929 				oldoffset = (entry->start + fudge) - start;
   2930 				elen = MIN(end, entry->end) -
   2931 				    (entry->start + fudge);
   2932 				pmap_copy(dstmap->pmap, srcmap->pmap,
   2933 				    dstaddr + oldoffset, elen,
   2934 				    entry->start + fudge);
   2935 			}
   2936 
   2937 			/* we advance "entry" in the following if statement */
   2938 			if (flags & UVM_EXTRACT_REMOVE) {
   2939 				pmap_remove(srcmap->pmap, entry->start,
   2940 						entry->end);
   2941 				oldentry = entry;	/* save entry */
   2942 				entry = entry->next;	/* advance */
   2943 				uvm_map_entry_unlink(srcmap, oldentry);
   2944 							/* add to dead list */
   2945 				oldentry->next = deadentry;
   2946 				deadentry = oldentry;
   2947 			} else {
   2948 				entry = entry->next;		/* advance */
   2949 			}
   2950 
   2951 			/* end of 'while' loop */
   2952 			fudge = 0;
   2953 		}
   2954 		pmap_update(srcmap->pmap);
   2955 
   2956 		/*
   2957 		 * unlock dstmap.  we will dispose of deadentry in
   2958 		 * step 7 if needed
   2959 		 */
   2960 
   2961 		if (copy_ok && srcmap != dstmap)
   2962 			vm_map_unlock(dstmap);
   2963 
   2964 	} else {
   2965 		deadentry = NULL;
   2966 	}
   2967 
   2968 	/*
   2969 	 * step 7: we are done with the source map, unlock.   if copy_ok
   2970 	 * is 0 then we have not replaced the dummy mapping in dstmap yet
   2971 	 * and we need to do so now.
   2972 	 */
   2973 
   2974 	vm_map_unlock(srcmap);
   2975 	if ((flags & UVM_EXTRACT_REMOVE) && deadentry)
   2976 		uvm_unmap_detach(deadentry, 0);   /* dispose of old entries */
   2977 
   2978 	/* now do the replacement if we didn't do it in step 5 */
   2979 	if (copy_ok == 0) {
   2980 		vm_map_lock(dstmap);
   2981 		error = uvm_map_replace(dstmap, dstaddr, dstaddr+len, chain,
   2982 		    nchain, &resentry);
   2983 		vm_map_unlock(dstmap);
   2984 
   2985 		if (error == false) {
   2986 			error = EIO;
   2987 			goto bad2;
   2988 		}
   2989 	}
   2990 
   2991 	if (resentry != NULL)
   2992 		uvm_mapent_free(resentry);
   2993 
   2994 	uvm_map_check(srcmap, "map_extract src leave");
   2995 	uvm_map_check(dstmap, "map_extract dst leave");
   2996 
   2997 	return (0);
   2998 
   2999 	/*
   3000 	 * bad: failure recovery
   3001 	 */
   3002 bad:
   3003 	vm_map_unlock(srcmap);
   3004 bad2:			/* src already unlocked */
   3005 	if (chain)
   3006 		uvm_unmap_detach(chain,
   3007 		    (flags & UVM_EXTRACT_QREF) ? AMAP_REFALL : 0);
   3008 
   3009 	if (resentry != NULL)
   3010 		uvm_mapent_free(resentry);
   3011 
   3012 	uvm_map_check(srcmap, "map_extract src err leave");
   3013 	uvm_map_check(dstmap, "map_extract dst err leave");
   3014 
   3015 	if ((flags & UVM_EXTRACT_RESERVED) == 0) {
   3016 		uvm_unmap(dstmap, dstaddr, dstaddr+len);   /* ??? */
   3017 	}
   3018 	return (error);
   3019 }
   3020 
   3021 /* end of extraction functions */
   3022 
   3023 /*
   3024  * uvm_map_submap: punch down part of a map into a submap
   3025  *
   3026  * => only the kernel_map is allowed to be submapped
   3027  * => the purpose of submapping is to break up the locking granularity
   3028  *	of a larger map
   3029  * => the range specified must have been mapped previously with a uvm_map()
   3030  *	call [with uobj==NULL] to create a blank map entry in the main map.
   3031  *	[And it had better still be blank!]
   3032  * => maps which contain submaps should never be copied or forked.
   3033  * => to remove a submap, use uvm_unmap() on the main map
   3034  *	and then uvm_map_deallocate() the submap.
   3035  * => main map must be unlocked.
   3036  * => submap must have been init'd and have a zero reference count.
   3037  *	[need not be locked as we don't actually reference it]
   3038  */
   3039 
   3040 int
   3041 uvm_map_submap(struct vm_map *map, vaddr_t start, vaddr_t end,
   3042     struct vm_map *submap)
   3043 {
   3044 	struct vm_map_entry *entry;
   3045 	struct uvm_mapent_reservation umr;
   3046 	int error;
   3047 
   3048 	uvm_mapent_reserve(map, &umr, 2, 0);
   3049 
   3050 	vm_map_lock(map);
   3051 	VM_MAP_RANGE_CHECK(map, start, end);
   3052 
   3053 	if (uvm_map_lookup_entry(map, start, &entry)) {
   3054 		UVM_MAP_CLIP_START(map, entry, start, &umr);
   3055 		UVM_MAP_CLIP_END(map, entry, end, &umr);	/* to be safe */
   3056 	} else {
   3057 		entry = NULL;
   3058 	}
   3059 
   3060 	if (entry != NULL &&
   3061 	    entry->start == start && entry->end == end &&
   3062 	    entry->object.uvm_obj == NULL && entry->aref.ar_amap == NULL &&
   3063 	    !UVM_ET_ISCOPYONWRITE(entry) && !UVM_ET_ISNEEDSCOPY(entry)) {
   3064 		entry->etype |= UVM_ET_SUBMAP;
   3065 		entry->object.sub_map = submap;
   3066 		entry->offset = 0;
   3067 		uvm_map_reference(submap);
   3068 		error = 0;
   3069 	} else {
   3070 		error = EINVAL;
   3071 	}
   3072 	vm_map_unlock(map);
   3073 
   3074 	uvm_mapent_unreserve(map, &umr);
   3075 
   3076 	return error;
   3077 }
   3078 
   3079 /*
   3080  * uvm_map_setup_kernel: init in-kernel map
   3081  *
   3082  * => map must not be in service yet.
   3083  */
   3084 
   3085 void
   3086 uvm_map_setup_kernel(struct vm_map_kernel *map,
   3087     vaddr_t vmin, vaddr_t vmax, int flags)
   3088 {
   3089 
   3090 	uvm_map_setup(&map->vmk_map, vmin, vmax, flags);
   3091 	callback_head_init(&map->vmk_reclaim_callback, IPL_VM);
   3092 	LIST_INIT(&map->vmk_kentry_free);
   3093 	map->vmk_merged_entries = NULL;
   3094 }
   3095 
   3096 
   3097 /*
   3098  * uvm_map_protect: change map protection
   3099  *
   3100  * => set_max means set max_protection.
   3101  * => map must be unlocked.
   3102  */
   3103 
   3104 #define MASK(entry)	(UVM_ET_ISCOPYONWRITE(entry) ? \
   3105 			 ~VM_PROT_WRITE : VM_PROT_ALL)
   3106 
   3107 int
   3108 uvm_map_protect(struct vm_map *map, vaddr_t start, vaddr_t end,
   3109     vm_prot_t new_prot, bool set_max)
   3110 {
   3111 	struct vm_map_entry *current, *entry;
   3112 	int error = 0;
   3113 	UVMHIST_FUNC("uvm_map_protect"); UVMHIST_CALLED(maphist);
   3114 	UVMHIST_LOG(maphist,"(map=0x%x,start=0x%x,end=0x%x,new_prot=0x%x)",
   3115 		    map, start, end, new_prot);
   3116 
   3117 	vm_map_lock(map);
   3118 	VM_MAP_RANGE_CHECK(map, start, end);
   3119 	if (uvm_map_lookup_entry(map, start, &entry)) {
   3120 		UVM_MAP_CLIP_START(map, entry, start, NULL);
   3121 	} else {
   3122 		entry = entry->next;
   3123 	}
   3124 
   3125 	/*
   3126 	 * make a first pass to check for protection violations.
   3127 	 */
   3128 
   3129 	current = entry;
   3130 	while ((current != &map->header) && (current->start < end)) {
   3131 		if (UVM_ET_ISSUBMAP(current)) {
   3132 			error = EINVAL;
   3133 			goto out;
   3134 		}
   3135 		if ((new_prot & current->max_protection) != new_prot) {
   3136 			error = EACCES;
   3137 			goto out;
   3138 		}
   3139 		/*
   3140 		 * Don't allow VM_PROT_EXECUTE to be set on entries that
   3141 		 * point to vnodes that are associated with a NOEXEC file
   3142 		 * system.
   3143 		 */
   3144 		if (UVM_ET_ISOBJ(current) &&
   3145 		    UVM_OBJ_IS_VNODE(current->object.uvm_obj)) {
   3146 			struct vnode *vp =
   3147 			    (struct vnode *) current->object.uvm_obj;
   3148 
   3149 			if ((new_prot & VM_PROT_EXECUTE) != 0 &&
   3150 			    (vp->v_mount->mnt_flag & MNT_NOEXEC) != 0) {
   3151 				error = EACCES;
   3152 				goto out;
   3153 			}
   3154 		}
   3155 
   3156 		current = current->next;
   3157 	}
   3158 
   3159 	/* go back and fix up protections (no need to clip this time). */
   3160 
   3161 	current = entry;
   3162 	while ((current != &map->header) && (current->start < end)) {
   3163 		vm_prot_t old_prot;
   3164 
   3165 		UVM_MAP_CLIP_END(map, current, end, NULL);
   3166 		old_prot = current->protection;
   3167 		if (set_max)
   3168 			current->protection =
   3169 			    (current->max_protection = new_prot) & old_prot;
   3170 		else
   3171 			current->protection = new_prot;
   3172 
   3173 		/*
   3174 		 * update physical map if necessary.  worry about copy-on-write
   3175 		 * here -- CHECK THIS XXX
   3176 		 */
   3177 
   3178 		if (current->protection != old_prot) {
   3179 			/* update pmap! */
   3180 			pmap_protect(map->pmap, current->start, current->end,
   3181 			    current->protection & MASK(entry));
   3182 
   3183 			/*
   3184 			 * If this entry points at a vnode, and the
   3185 			 * protection includes VM_PROT_EXECUTE, mark
   3186 			 * the vnode as VEXECMAP.
   3187 			 */
   3188 			if (UVM_ET_ISOBJ(current)) {
   3189 				struct uvm_object *uobj =
   3190 				    current->object.uvm_obj;
   3191 
   3192 				if (UVM_OBJ_IS_VNODE(uobj) &&
   3193 				    (current->protection & VM_PROT_EXECUTE)) {
   3194 					vn_markexec((struct vnode *) uobj);
   3195 				}
   3196 			}
   3197 		}
   3198 
   3199 		/*
   3200 		 * If the map is configured to lock any future mappings,
   3201 		 * wire this entry now if the old protection was VM_PROT_NONE
   3202 		 * and the new protection is not VM_PROT_NONE.
   3203 		 */
   3204 
   3205 		if ((map->flags & VM_MAP_WIREFUTURE) != 0 &&
   3206 		    VM_MAPENT_ISWIRED(entry) == 0 &&
   3207 		    old_prot == VM_PROT_NONE &&
   3208 		    new_prot != VM_PROT_NONE) {
   3209 			if (uvm_map_pageable(map, entry->start,
   3210 			    entry->end, false,
   3211 			    UVM_LK_ENTER|UVM_LK_EXIT) != 0) {
   3212 
   3213 				/*
   3214 				 * If locking the entry fails, remember the
   3215 				 * error if it's the first one.  Note we
   3216 				 * still continue setting the protection in
   3217 				 * the map, but will return the error
   3218 				 * condition regardless.
   3219 				 *
   3220 				 * XXX Ignore what the actual error is,
   3221 				 * XXX just call it a resource shortage
   3222 				 * XXX so that it doesn't get confused
   3223 				 * XXX what uvm_map_protect() itself would
   3224 				 * XXX normally return.
   3225 				 */
   3226 
   3227 				error = ENOMEM;
   3228 			}
   3229 		}
   3230 		current = current->next;
   3231 	}
   3232 	pmap_update(map->pmap);
   3233 
   3234  out:
   3235 	vm_map_unlock(map);
   3236 
   3237 	UVMHIST_LOG(maphist, "<- done, error=%d",error,0,0,0);
   3238 	return error;
   3239 }
   3240 
   3241 #undef  MASK
   3242 
   3243 /*
   3244  * uvm_map_inherit: set inheritance code for range of addrs in map.
   3245  *
   3246  * => map must be unlocked
   3247  * => note that the inherit code is used during a "fork".  see fork
   3248  *	code for details.
   3249  */
   3250 
   3251 int
   3252 uvm_map_inherit(struct vm_map *map, vaddr_t start, vaddr_t end,
   3253     vm_inherit_t new_inheritance)
   3254 {
   3255 	struct vm_map_entry *entry, *temp_entry;
   3256 	UVMHIST_FUNC("uvm_map_inherit"); UVMHIST_CALLED(maphist);
   3257 	UVMHIST_LOG(maphist,"(map=0x%x,start=0x%x,end=0x%x,new_inh=0x%x)",
   3258 	    map, start, end, new_inheritance);
   3259 
   3260 	switch (new_inheritance) {
   3261 	case MAP_INHERIT_NONE:
   3262 	case MAP_INHERIT_COPY:
   3263 	case MAP_INHERIT_SHARE:
   3264 		break;
   3265 	default:
   3266 		UVMHIST_LOG(maphist,"<- done (INVALID ARG)",0,0,0,0);
   3267 		return EINVAL;
   3268 	}
   3269 
   3270 	vm_map_lock(map);
   3271 	VM_MAP_RANGE_CHECK(map, start, end);
   3272 	if (uvm_map_lookup_entry(map, start, &temp_entry)) {
   3273 		entry = temp_entry;
   3274 		UVM_MAP_CLIP_START(map, entry, start, NULL);
   3275 	}  else {
   3276 		entry = temp_entry->next;
   3277 	}
   3278 	while ((entry != &map->header) && (entry->start < end)) {
   3279 		UVM_MAP_CLIP_END(map, entry, end, NULL);
   3280 		entry->inheritance = new_inheritance;
   3281 		entry = entry->next;
   3282 	}
   3283 	vm_map_unlock(map);
   3284 	UVMHIST_LOG(maphist,"<- done (OK)",0,0,0,0);
   3285 	return 0;
   3286 }
   3287 
   3288 /*
   3289  * uvm_map_advice: set advice code for range of addrs in map.
   3290  *
   3291  * => map must be unlocked
   3292  */
   3293 
   3294 int
   3295 uvm_map_advice(struct vm_map *map, vaddr_t start, vaddr_t end, int new_advice)
   3296 {
   3297 	struct vm_map_entry *entry, *temp_entry;
   3298 	UVMHIST_FUNC("uvm_map_advice"); UVMHIST_CALLED(maphist);
   3299 	UVMHIST_LOG(maphist,"(map=0x%x,start=0x%x,end=0x%x,new_adv=0x%x)",
   3300 	    map, start, end, new_advice);
   3301 
   3302 	vm_map_lock(map);
   3303 	VM_MAP_RANGE_CHECK(map, start, end);
   3304 	if (uvm_map_lookup_entry(map, start, &temp_entry)) {
   3305 		entry = temp_entry;
   3306 		UVM_MAP_CLIP_START(map, entry, start, NULL);
   3307 	} else {
   3308 		entry = temp_entry->next;
   3309 	}
   3310 
   3311 	/*
   3312 	 * XXXJRT: disallow holes?
   3313 	 */
   3314 
   3315 	while ((entry != &map->header) && (entry->start < end)) {
   3316 		UVM_MAP_CLIP_END(map, entry, end, NULL);
   3317 
   3318 		switch (new_advice) {
   3319 		case MADV_NORMAL:
   3320 		case MADV_RANDOM:
   3321 		case MADV_SEQUENTIAL:
   3322 			/* nothing special here */
   3323 			break;
   3324 
   3325 		default:
   3326 			vm_map_unlock(map);
   3327 			UVMHIST_LOG(maphist,"<- done (INVALID ARG)",0,0,0,0);
   3328 			return EINVAL;
   3329 		}
   3330 		entry->advice = new_advice;
   3331 		entry = entry->next;
   3332 	}
   3333 
   3334 	vm_map_unlock(map);
   3335 	UVMHIST_LOG(maphist,"<- done (OK)",0,0,0,0);
   3336 	return 0;
   3337 }
   3338 
   3339 /*
   3340  * uvm_map_willneed: apply MADV_WILLNEED
   3341  */
   3342 
   3343 int
   3344 uvm_map_willneed(struct vm_map *map, vaddr_t start, vaddr_t end)
   3345 {
   3346 	struct vm_map_entry *entry;
   3347 	UVMHIST_FUNC("uvm_map_willneed"); UVMHIST_CALLED(maphist);
   3348 	UVMHIST_LOG(maphist,"(map=0x%lx,start=0x%lx,end=0x%lx)",
   3349 	    map, start, end, 0);
   3350 
   3351 	vm_map_lock_read(map);
   3352 	VM_MAP_RANGE_CHECK(map, start, end);
   3353 	if (!uvm_map_lookup_entry(map, start, &entry)) {
   3354 		entry = entry->next;
   3355 	}
   3356 	while (entry->start < end) {
   3357 		struct vm_amap * const amap = entry->aref.ar_amap;
   3358 		struct uvm_object * const uobj = entry->object.uvm_obj;
   3359 
   3360 		KASSERT(entry != &map->header);
   3361 		KASSERT(start < entry->end);
   3362 		/*
   3363 		 * XXX IMPLEMENT ME.
   3364 		 * Should invent a "weak" mode for uvm_fault()
   3365 		 * which would only do the PGO_LOCKED pgo_get().
   3366 		 *
   3367 		 * for now, we handle only the easy but common case.
   3368 		 */
   3369 		if (UVM_ET_ISOBJ(entry) && amap == NULL && uobj != NULL) {
   3370 			off_t offset;
   3371 			off_t size;
   3372 
   3373 			offset = entry->offset;
   3374 			if (start < entry->start) {
   3375 				offset += entry->start - start;
   3376 			}
   3377 			size = entry->offset + (entry->end - entry->start);
   3378 			if (entry->end < end) {
   3379 				size -= end - entry->end;
   3380 			}
   3381 			uvm_readahead(uobj, offset, size);
   3382 		}
   3383 		entry = entry->next;
   3384 	}
   3385 	vm_map_unlock_read(map);
   3386 	UVMHIST_LOG(maphist,"<- done (OK)",0,0,0,0);
   3387 	return 0;
   3388 }
   3389 
   3390 /*
   3391  * uvm_map_pageable: sets the pageability of a range in a map.
   3392  *
   3393  * => wires map entries.  should not be used for transient page locking.
   3394  *	for that, use uvm_fault_wire()/uvm_fault_unwire() (see uvm_vslock()).
   3395  * => regions specified as not pageable require lock-down (wired) memory
   3396  *	and page tables.
   3397  * => map must never be read-locked
   3398  * => if islocked is true, map is already write-locked
   3399  * => we always unlock the map, since we must downgrade to a read-lock
   3400  *	to call uvm_fault_wire()
   3401  * => XXXCDC: check this and try and clean it up.
   3402  */
   3403 
   3404 int
   3405 uvm_map_pageable(struct vm_map *map, vaddr_t start, vaddr_t end,
   3406     bool new_pageable, int lockflags)
   3407 {
   3408 	struct vm_map_entry *entry, *start_entry, *failed_entry;
   3409 	int rv;
   3410 #ifdef DIAGNOSTIC
   3411 	u_int timestamp_save;
   3412 #endif
   3413 	UVMHIST_FUNC("uvm_map_pageable"); UVMHIST_CALLED(maphist);
   3414 	UVMHIST_LOG(maphist,"(map=0x%x,start=0x%x,end=0x%x,new_pageable=0x%x)",
   3415 		    map, start, end, new_pageable);
   3416 	KASSERT(map->flags & VM_MAP_PAGEABLE);
   3417 
   3418 	if ((lockflags & UVM_LK_ENTER) == 0)
   3419 		vm_map_lock(map);
   3420 	VM_MAP_RANGE_CHECK(map, start, end);
   3421 
   3422 	/*
   3423 	 * only one pageability change may take place at one time, since
   3424 	 * uvm_fault_wire assumes it will be called only once for each
   3425 	 * wiring/unwiring.  therefore, we have to make sure we're actually
   3426 	 * changing the pageability for the entire region.  we do so before
   3427 	 * making any changes.
   3428 	 */
   3429 
   3430 	if (uvm_map_lookup_entry(map, start, &start_entry) == false) {
   3431 		if ((lockflags & UVM_LK_EXIT) == 0)
   3432 			vm_map_unlock(map);
   3433 
   3434 		UVMHIST_LOG(maphist,"<- done (fault)",0,0,0,0);
   3435 		return EFAULT;
   3436 	}
   3437 	entry = start_entry;
   3438 
   3439 	/*
   3440 	 * handle wiring and unwiring separately.
   3441 	 */
   3442 
   3443 	if (new_pageable) {		/* unwire */
   3444 		UVM_MAP_CLIP_START(map, entry, start, NULL);
   3445 
   3446 		/*
   3447 		 * unwiring.  first ensure that the range to be unwired is
   3448 		 * really wired down and that there are no holes.
   3449 		 */
   3450 
   3451 		while ((entry != &map->header) && (entry->start < end)) {
   3452 			if (entry->wired_count == 0 ||
   3453 			    (entry->end < end &&
   3454 			     (entry->next == &map->header ||
   3455 			      entry->next->start > entry->end))) {
   3456 				if ((lockflags & UVM_LK_EXIT) == 0)
   3457 					vm_map_unlock(map);
   3458 				UVMHIST_LOG(maphist, "<- done (INVAL)",0,0,0,0);
   3459 				return EINVAL;
   3460 			}
   3461 			entry = entry->next;
   3462 		}
   3463 
   3464 		/*
   3465 		 * POSIX 1003.1b - a single munlock call unlocks a region,
   3466 		 * regardless of the number of mlock calls made on that
   3467 		 * region.
   3468 		 */
   3469 
   3470 		entry = start_entry;
   3471 		while ((entry != &map->header) && (entry->start < end)) {
   3472 			UVM_MAP_CLIP_END(map, entry, end, NULL);
   3473 			if (VM_MAPENT_ISWIRED(entry))
   3474 				uvm_map_entry_unwire(map, entry);
   3475 			entry = entry->next;
   3476 		}
   3477 		if ((lockflags & UVM_LK_EXIT) == 0)
   3478 			vm_map_unlock(map);
   3479 		UVMHIST_LOG(maphist,"<- done (OK UNWIRE)",0,0,0,0);
   3480 		return 0;
   3481 	}
   3482 
   3483 	/*
   3484 	 * wire case: in two passes [XXXCDC: ugly block of code here]
   3485 	 *
   3486 	 * 1: holding the write lock, we create any anonymous maps that need
   3487 	 *    to be created.  then we clip each map entry to the region to
   3488 	 *    be wired and increment its wiring count.
   3489 	 *
   3490 	 * 2: we downgrade to a read lock, and call uvm_fault_wire to fault
   3491 	 *    in the pages for any newly wired area (wired_count == 1).
   3492 	 *
   3493 	 *    downgrading to a read lock for uvm_fault_wire avoids a possible
   3494 	 *    deadlock with another thread that may have faulted on one of
   3495 	 *    the pages to be wired (it would mark the page busy, blocking
   3496 	 *    us, then in turn block on the map lock that we hold).  because
   3497 	 *    of problems in the recursive lock package, we cannot upgrade
   3498 	 *    to a write lock in vm_map_lookup.  thus, any actions that
   3499 	 *    require the write lock must be done beforehand.  because we
   3500 	 *    keep the read lock on the map, the copy-on-write status of the
   3501 	 *    entries we modify here cannot change.
   3502 	 */
   3503 
   3504 	while ((entry != &map->header) && (entry->start < end)) {
   3505 		if (VM_MAPENT_ISWIRED(entry) == 0) { /* not already wired? */
   3506 
   3507 			/*
   3508 			 * perform actions of vm_map_lookup that need the
   3509 			 * write lock on the map: create an anonymous map
   3510 			 * for a copy-on-write region, or an anonymous map
   3511 			 * for a zero-fill region.  (XXXCDC: submap case
   3512 			 * ok?)
   3513 			 */
   3514 
   3515 			if (!UVM_ET_ISSUBMAP(entry)) {  /* not submap */
   3516 				if (UVM_ET_ISNEEDSCOPY(entry) &&
   3517 				    ((entry->max_protection & VM_PROT_WRITE) ||
   3518 				     (entry->object.uvm_obj == NULL))) {
   3519 					amap_copy(map, entry, 0, start, end);
   3520 					/* XXXCDC: wait OK? */
   3521 				}
   3522 			}
   3523 		}
   3524 		UVM_MAP_CLIP_START(map, entry, start, NULL);
   3525 		UVM_MAP_CLIP_END(map, entry, end, NULL);
   3526 		entry->wired_count++;
   3527 
   3528 		/*
   3529 		 * Check for holes
   3530 		 */
   3531 
   3532 		if (entry->protection == VM_PROT_NONE ||
   3533 		    (entry->end < end &&
   3534 		     (entry->next == &map->header ||
   3535 		      entry->next->start > entry->end))) {
   3536 
   3537 			/*
   3538 			 * found one.  amap creation actions do not need to
   3539 			 * be undone, but the wired counts need to be restored.
   3540 			 */
   3541 
   3542 			while (entry != &map->header && entry->end > start) {
   3543 				entry->wired_count--;
   3544 				entry = entry->prev;
   3545 			}
   3546 			if ((lockflags & UVM_LK_EXIT) == 0)
   3547 				vm_map_unlock(map);
   3548 			UVMHIST_LOG(maphist,"<- done (INVALID WIRE)",0,0,0,0);
   3549 			return EINVAL;
   3550 		}
   3551 		entry = entry->next;
   3552 	}
   3553 
   3554 	/*
   3555 	 * Pass 2.
   3556 	 */
   3557 
   3558 #ifdef DIAGNOSTIC
   3559 	timestamp_save = map->timestamp;
   3560 #endif
   3561 	vm_map_busy(map);
   3562 	vm_map_unlock(map);
   3563 
   3564 	rv = 0;
   3565 	entry = start_entry;
   3566 	while (entry != &map->header && entry->start < end) {
   3567 		if (entry->wired_count == 1) {
   3568 			rv = uvm_fault_wire(map, entry->start, entry->end,
   3569 			    entry->max_protection, 1);
   3570 			if (rv) {
   3571 
   3572 				/*
   3573 				 * wiring failed.  break out of the loop.
   3574 				 * we'll clean up the map below, once we
   3575 				 * have a write lock again.
   3576 				 */
   3577 
   3578 				break;
   3579 			}
   3580 		}
   3581 		entry = entry->next;
   3582 	}
   3583 
   3584 	if (rv) {	/* failed? */
   3585 
   3586 		/*
   3587 		 * Get back to an exclusive (write) lock.
   3588 		 */
   3589 
   3590 		vm_map_lock(map);
   3591 		vm_map_unbusy(map);
   3592 
   3593 #ifdef DIAGNOSTIC
   3594 		if (timestamp_save + 1 != map->timestamp)
   3595 			panic("uvm_map_pageable: stale map");
   3596 #endif
   3597 
   3598 		/*
   3599 		 * first drop the wiring count on all the entries
   3600 		 * which haven't actually been wired yet.
   3601 		 */
   3602 
   3603 		failed_entry = entry;
   3604 		while (entry != &map->header && entry->start < end) {
   3605 			entry->wired_count--;
   3606 			entry = entry->next;
   3607 		}
   3608 
   3609 		/*
   3610 		 * now, unwire all the entries that were successfully
   3611 		 * wired above.
   3612 		 */
   3613 
   3614 		entry = start_entry;
   3615 		while (entry != failed_entry) {
   3616 			entry->wired_count--;
   3617 			if (VM_MAPENT_ISWIRED(entry) == 0)
   3618 				uvm_map_entry_unwire(map, entry);
   3619 			entry = entry->next;
   3620 		}
   3621 		if ((lockflags & UVM_LK_EXIT) == 0)
   3622 			vm_map_unlock(map);
   3623 		UVMHIST_LOG(maphist, "<- done (RV=%d)", rv,0,0,0);
   3624 		return (rv);
   3625 	}
   3626 
   3627 	if ((lockflags & UVM_LK_EXIT) == 0) {
   3628 		vm_map_unbusy(map);
   3629 	} else {
   3630 
   3631 		/*
   3632 		 * Get back to an exclusive (write) lock.
   3633 		 */
   3634 
   3635 		vm_map_lock(map);
   3636 		vm_map_unbusy(map);
   3637 	}
   3638 
   3639 	UVMHIST_LOG(maphist,"<- done (OK WIRE)",0,0,0,0);
   3640 	return 0;
   3641 }
   3642 
   3643 /*
   3644  * uvm_map_pageable_all: special case of uvm_map_pageable - affects
   3645  * all mapped regions.
   3646  *
   3647  * => map must not be locked.
   3648  * => if no flags are specified, all regions are unwired.
   3649  * => XXXJRT: has some of the same problems as uvm_map_pageable() above.
   3650  */
   3651 
   3652 int
   3653 uvm_map_pageable_all(struct vm_map *map, int flags, vsize_t limit)
   3654 {
   3655 	struct vm_map_entry *entry, *failed_entry;
   3656 	vsize_t size;
   3657 	int rv;
   3658 #ifdef DIAGNOSTIC
   3659 	u_int timestamp_save;
   3660 #endif
   3661 	UVMHIST_FUNC("uvm_map_pageable_all"); UVMHIST_CALLED(maphist);
   3662 	UVMHIST_LOG(maphist,"(map=0x%x,flags=0x%x)", map, flags, 0, 0);
   3663 
   3664 	KASSERT(map->flags & VM_MAP_PAGEABLE);
   3665 
   3666 	vm_map_lock(map);
   3667 
   3668 	/*
   3669 	 * handle wiring and unwiring separately.
   3670 	 */
   3671 
   3672 	if (flags == 0) {			/* unwire */
   3673 
   3674 		/*
   3675 		 * POSIX 1003.1b -- munlockall unlocks all regions,
   3676 		 * regardless of how many times mlockall has been called.
   3677 		 */
   3678 
   3679 		for (entry = map->header.next; entry != &map->header;
   3680 		     entry = entry->next) {
   3681 			if (VM_MAPENT_ISWIRED(entry))
   3682 				uvm_map_entry_unwire(map, entry);
   3683 		}
   3684 		map->flags &= ~VM_MAP_WIREFUTURE;
   3685 		vm_map_unlock(map);
   3686 		UVMHIST_LOG(maphist,"<- done (OK UNWIRE)",0,0,0,0);
   3687 		return 0;
   3688 	}
   3689 
   3690 	if (flags & MCL_FUTURE) {
   3691 
   3692 		/*
   3693 		 * must wire all future mappings; remember this.
   3694 		 */
   3695 
   3696 		map->flags |= VM_MAP_WIREFUTURE;
   3697 	}
   3698 
   3699 	if ((flags & MCL_CURRENT) == 0) {
   3700 
   3701 		/*
   3702 		 * no more work to do!
   3703 		 */
   3704 
   3705 		UVMHIST_LOG(maphist,"<- done (OK no wire)",0,0,0,0);
   3706 		vm_map_unlock(map);
   3707 		return 0;
   3708 	}
   3709 
   3710 	/*
   3711 	 * wire case: in three passes [XXXCDC: ugly block of code here]
   3712 	 *
   3713 	 * 1: holding the write lock, count all pages mapped by non-wired
   3714 	 *    entries.  if this would cause us to go over our limit, we fail.
   3715 	 *
   3716 	 * 2: still holding the write lock, we create any anonymous maps that
   3717 	 *    need to be created.  then we increment its wiring count.
   3718 	 *
   3719 	 * 3: we downgrade to a read lock, and call uvm_fault_wire to fault
   3720 	 *    in the pages for any newly wired area (wired_count == 1).
   3721 	 *
   3722 	 *    downgrading to a read lock for uvm_fault_wire avoids a possible
   3723 	 *    deadlock with another thread that may have faulted on one of
   3724 	 *    the pages to be wired (it would mark the page busy, blocking
   3725 	 *    us, then in turn block on the map lock that we hold).  because
   3726 	 *    of problems in the recursive lock package, we cannot upgrade
   3727 	 *    to a write lock in vm_map_lookup.  thus, any actions that
   3728 	 *    require the write lock must be done beforehand.  because we
   3729 	 *    keep the read lock on the map, the copy-on-write status of the
   3730 	 *    entries we modify here cannot change.
   3731 	 */
   3732 
   3733 	for (size = 0, entry = map->header.next; entry != &map->header;
   3734 	     entry = entry->next) {
   3735 		if (entry->protection != VM_PROT_NONE &&
   3736 		    VM_MAPENT_ISWIRED(entry) == 0) { /* not already wired? */
   3737 			size += entry->end - entry->start;
   3738 		}
   3739 	}
   3740 
   3741 	if (atop(size) + uvmexp.wired > uvmexp.wiredmax) {
   3742 		vm_map_unlock(map);
   3743 		return ENOMEM;
   3744 	}
   3745 
   3746 	if (limit != 0 &&
   3747 	    (size + ptoa(pmap_wired_count(vm_map_pmap(map))) > limit)) {
   3748 		vm_map_unlock(map);
   3749 		return ENOMEM;
   3750 	}
   3751 
   3752 	/*
   3753 	 * Pass 2.
   3754 	 */
   3755 
   3756 	for (entry = map->header.next; entry != &map->header;
   3757 	     entry = entry->next) {
   3758 		if (entry->protection == VM_PROT_NONE)
   3759 			continue;
   3760 		if (VM_MAPENT_ISWIRED(entry) == 0) { /* not already wired? */
   3761 
   3762 			/*
   3763 			 * perform actions of vm_map_lookup that need the
   3764 			 * write lock on the map: create an anonymous map
   3765 			 * for a copy-on-write region, or an anonymous map
   3766 			 * for a zero-fill region.  (XXXCDC: submap case
   3767 			 * ok?)
   3768 			 */
   3769 
   3770 			if (!UVM_ET_ISSUBMAP(entry)) {	/* not submap */
   3771 				if (UVM_ET_ISNEEDSCOPY(entry) &&
   3772 				    ((entry->max_protection & VM_PROT_WRITE) ||
   3773 				     (entry->object.uvm_obj == NULL))) {
   3774 					amap_copy(map, entry, 0, entry->start,
   3775 					    entry->end);
   3776 					/* XXXCDC: wait OK? */
   3777 				}
   3778 			}
   3779 		}
   3780 		entry->wired_count++;
   3781 	}
   3782 
   3783 	/*
   3784 	 * Pass 3.
   3785 	 */
   3786 
   3787 #ifdef DIAGNOSTIC
   3788 	timestamp_save = map->timestamp;
   3789 #endif
   3790 	vm_map_busy(map);
   3791 	vm_map_unlock(map);
   3792 
   3793 	rv = 0;
   3794 	for (entry = map->header.next; entry != &map->header;
   3795 	     entry = entry->next) {
   3796 		if (entry->wired_count == 1) {
   3797 			rv = uvm_fault_wire(map, entry->start, entry->end,
   3798 			    entry->max_protection, 1);
   3799 			if (rv) {
   3800 
   3801 				/*
   3802 				 * wiring failed.  break out of the loop.
   3803 				 * we'll clean up the map below, once we
   3804 				 * have a write lock again.
   3805 				 */
   3806 
   3807 				break;
   3808 			}
   3809 		}
   3810 	}
   3811 
   3812 	if (rv) {
   3813 
   3814 		/*
   3815 		 * Get back an exclusive (write) lock.
   3816 		 */
   3817 
   3818 		vm_map_lock(map);
   3819 		vm_map_unbusy(map);
   3820 
   3821 #ifdef DIAGNOSTIC
   3822 		if (timestamp_save + 1 != map->timestamp)
   3823 			panic("uvm_map_pageable_all: stale map");
   3824 #endif
   3825 
   3826 		/*
   3827 		 * first drop the wiring count on all the entries
   3828 		 * which haven't actually been wired yet.
   3829 		 *
   3830 		 * Skip VM_PROT_NONE entries like we did above.
   3831 		 */
   3832 
   3833 		failed_entry = entry;
   3834 		for (/* nothing */; entry != &map->header;
   3835 		     entry = entry->next) {
   3836 			if (entry->protection == VM_PROT_NONE)
   3837 				continue;
   3838 			entry->wired_count--;
   3839 		}
   3840 
   3841 		/*
   3842 		 * now, unwire all the entries that were successfully
   3843 		 * wired above.
   3844 		 *
   3845 		 * Skip VM_PROT_NONE entries like we did above.
   3846 		 */
   3847 
   3848 		for (entry = map->header.next; entry != failed_entry;
   3849 		     entry = entry->next) {
   3850 			if (entry->protection == VM_PROT_NONE)
   3851 				continue;
   3852 			entry->wired_count--;
   3853 			if (VM_MAPENT_ISWIRED(entry))
   3854 				uvm_map_entry_unwire(map, entry);
   3855 		}
   3856 		vm_map_unlock(map);
   3857 		UVMHIST_LOG(maphist,"<- done (RV=%d)", rv,0,0,0);
   3858 		return (rv);
   3859 	}
   3860 
   3861 	vm_map_unbusy(map);
   3862 
   3863 	UVMHIST_LOG(maphist,"<- done (OK WIRE)",0,0,0,0);
   3864 	return 0;
   3865 }
   3866 
   3867 /*
   3868  * uvm_map_clean: clean out a map range
   3869  *
   3870  * => valid flags:
   3871  *   if (flags & PGO_CLEANIT): dirty pages are cleaned first
   3872  *   if (flags & PGO_SYNCIO): dirty pages are written synchronously
   3873  *   if (flags & PGO_DEACTIVATE): any cached pages are deactivated after clean
   3874  *   if (flags & PGO_FREE): any cached pages are freed after clean
   3875  * => returns an error if any part of the specified range isn't mapped
   3876  * => never a need to flush amap layer since the anonymous memory has
   3877  *	no permanent home, but may deactivate pages there
   3878  * => called from sys_msync() and sys_madvise()
   3879  * => caller must not write-lock map (read OK).
   3880  * => we may sleep while cleaning if SYNCIO [with map read-locked]
   3881  */
   3882 
   3883 int
   3884 uvm_map_clean(struct vm_map *map, vaddr_t start, vaddr_t end, int flags)
   3885 {
   3886 	struct vm_map_entry *current, *entry;
   3887 	struct uvm_object *uobj;
   3888 	struct vm_amap *amap;
   3889 	struct vm_anon *anon;
   3890 	struct vm_page *pg;
   3891 	vaddr_t offset;
   3892 	vsize_t size;
   3893 	voff_t uoff;
   3894 	int error, refs;
   3895 	UVMHIST_FUNC("uvm_map_clean"); UVMHIST_CALLED(maphist);
   3896 
   3897 	UVMHIST_LOG(maphist,"(map=0x%x,start=0x%x,end=0x%x,flags=0x%x)",
   3898 		    map, start, end, flags);
   3899 	KASSERT((flags & (PGO_FREE|PGO_DEACTIVATE)) !=
   3900 		(PGO_FREE|PGO_DEACTIVATE));
   3901 
   3902 	vm_map_lock_read(map);
   3903 	VM_MAP_RANGE_CHECK(map, start, end);
   3904 	if (uvm_map_lookup_entry(map, start, &entry) == false) {
   3905 		vm_map_unlock_read(map);
   3906 		return EFAULT;
   3907 	}
   3908 
   3909 	/*
   3910 	 * Make a first pass to check for holes and wiring problems.
   3911 	 */
   3912 
   3913 	for (current = entry; current->start < end; current = current->next) {
   3914 		if (UVM_ET_ISSUBMAP(current)) {
   3915 			vm_map_unlock_read(map);
   3916 			return EINVAL;
   3917 		}
   3918 		if ((flags & PGO_FREE) != 0 && VM_MAPENT_ISWIRED(entry)) {
   3919 			vm_map_unlock_read(map);
   3920 			return EBUSY;
   3921 		}
   3922 		if (end <= current->end) {
   3923 			break;
   3924 		}
   3925 		if (current->end != current->next->start) {
   3926 			vm_map_unlock_read(map);
   3927 			return EFAULT;
   3928 		}
   3929 	}
   3930 
   3931 	error = 0;
   3932 	for (current = entry; start < end; current = current->next) {
   3933 		amap = current->aref.ar_amap;	/* top layer */
   3934 		uobj = current->object.uvm_obj;	/* bottom layer */
   3935 		KASSERT(start >= current->start);
   3936 
   3937 		/*
   3938 		 * No amap cleaning necessary if:
   3939 		 *
   3940 		 *	(1) There's no amap.
   3941 		 *
   3942 		 *	(2) We're not deactivating or freeing pages.
   3943 		 */
   3944 
   3945 		if (amap == NULL || (flags & (PGO_DEACTIVATE|PGO_FREE)) == 0)
   3946 			goto flush_object;
   3947 
   3948 		amap_lock(amap);
   3949 		offset = start - current->start;
   3950 		size = MIN(end, current->end) - start;
   3951 		for ( ; size != 0; size -= PAGE_SIZE, offset += PAGE_SIZE) {
   3952 			anon = amap_lookup(&current->aref, offset);
   3953 			if (anon == NULL)
   3954 				continue;
   3955 
   3956 			mutex_enter(&anon->an_lock);
   3957 			pg = anon->an_page;
   3958 			if (pg == NULL) {
   3959 				mutex_exit(&anon->an_lock);
   3960 				continue;
   3961 			}
   3962 
   3963 			switch (flags & (PGO_CLEANIT|PGO_FREE|PGO_DEACTIVATE)) {
   3964 
   3965 			/*
   3966 			 * In these first 3 cases, we just deactivate the page.
   3967 			 */
   3968 
   3969 			case PGO_CLEANIT|PGO_FREE:
   3970 			case PGO_CLEANIT|PGO_DEACTIVATE:
   3971 			case PGO_DEACTIVATE:
   3972  deactivate_it:
   3973 				/*
   3974 				 * skip the page if it's loaned or wired,
   3975 				 * since it shouldn't be on a paging queue
   3976 				 * at all in these cases.
   3977 				 */
   3978 
   3979 				mutex_enter(&uvm_pageqlock);
   3980 				if (pg->loan_count != 0 ||
   3981 				    pg->wire_count != 0) {
   3982 					mutex_exit(&uvm_pageqlock);
   3983 					mutex_exit(&anon->an_lock);
   3984 					continue;
   3985 				}
   3986 				KASSERT(pg->uanon == anon);
   3987 				uvm_pagedeactivate(pg);
   3988 				mutex_exit(&uvm_pageqlock);
   3989 				mutex_exit(&anon->an_lock);
   3990 				continue;
   3991 
   3992 			case PGO_FREE:
   3993 
   3994 				/*
   3995 				 * If there are multiple references to
   3996 				 * the amap, just deactivate the page.
   3997 				 */
   3998 
   3999 				if (amap_refs(amap) > 1)
   4000 					goto deactivate_it;
   4001 
   4002 				/* skip the page if it's wired */
   4003 				if (pg->wire_count != 0) {
   4004 					mutex_exit(&anon->an_lock);
   4005 					continue;
   4006 				}
   4007 				amap_unadd(&current->aref, offset);
   4008 				refs = --anon->an_ref;
   4009 				mutex_exit(&anon->an_lock);
   4010 				if (refs == 0)
   4011 					uvm_anfree(anon);
   4012 				continue;
   4013 			}
   4014 		}
   4015 		amap_unlock(amap);
   4016 
   4017  flush_object:
   4018 		/*
   4019 		 * flush pages if we've got a valid backing object.
   4020 		 * note that we must always clean object pages before
   4021 		 * freeing them since otherwise we could reveal stale
   4022 		 * data from files.
   4023 		 */
   4024 
   4025 		uoff = current->offset + (start - current->start);
   4026 		size = MIN(end, current->end) - start;
   4027 		if (uobj != NULL) {
   4028 			mutex_enter(&uobj->vmobjlock);
   4029 			if (uobj->pgops->pgo_put != NULL)
   4030 				error = (uobj->pgops->pgo_put)(uobj, uoff,
   4031 				    uoff + size, flags | PGO_CLEANIT);
   4032 			else
   4033 				error = 0;
   4034 		}
   4035 		start += size;
   4036 	}
   4037 	vm_map_unlock_read(map);
   4038 	return (error);
   4039 }
   4040 
   4041 
   4042 /*
   4043  * uvm_map_checkprot: check protection in map
   4044  *
   4045  * => must allow specified protection in a fully allocated region.
   4046  * => map must be read or write locked by caller.
   4047  */
   4048 
   4049 bool
   4050 uvm_map_checkprot(struct vm_map *map, vaddr_t start, vaddr_t end,
   4051     vm_prot_t protection)
   4052 {
   4053 	struct vm_map_entry *entry;
   4054 	struct vm_map_entry *tmp_entry;
   4055 
   4056 	if (!uvm_map_lookup_entry(map, start, &tmp_entry)) {
   4057 		return (false);
   4058 	}
   4059 	entry = tmp_entry;
   4060 	while (start < end) {
   4061 		if (entry == &map->header) {
   4062 			return (false);
   4063 		}
   4064 
   4065 		/*
   4066 		 * no holes allowed
   4067 		 */
   4068 
   4069 		if (start < entry->start) {
   4070 			return (false);
   4071 		}
   4072 
   4073 		/*
   4074 		 * check protection associated with entry
   4075 		 */
   4076 
   4077 		if ((entry->protection & protection) != protection) {
   4078 			return (false);
   4079 		}
   4080 		start = entry->end;
   4081 		entry = entry->next;
   4082 	}
   4083 	return (true);
   4084 }
   4085 
   4086 /*
   4087  * uvmspace_alloc: allocate a vmspace structure.
   4088  *
   4089  * - structure includes vm_map and pmap
   4090  * - XXX: no locking on this structure
   4091  * - refcnt set to 1, rest must be init'd by caller
   4092  */
   4093 struct vmspace *
   4094 uvmspace_alloc(vaddr_t vmin, vaddr_t vmax)
   4095 {
   4096 	struct vmspace *vm;
   4097 	UVMHIST_FUNC("uvmspace_alloc"); UVMHIST_CALLED(maphist);
   4098 
   4099 	vm = pool_cache_get(&uvm_vmspace_cache, PR_WAITOK);
   4100 	uvmspace_init(vm, NULL, vmin, vmax);
   4101 	UVMHIST_LOG(maphist,"<- done (vm=0x%x)", vm,0,0,0);
   4102 	return (vm);
   4103 }
   4104 
   4105 /*
   4106  * uvmspace_init: initialize a vmspace structure.
   4107  *
   4108  * - XXX: no locking on this structure
   4109  * - refcnt set to 1, rest must be init'd by caller
   4110  */
   4111 void
   4112 uvmspace_init(struct vmspace *vm, struct pmap *pmap, vaddr_t vmin, vaddr_t vmax)
   4113 {
   4114 	UVMHIST_FUNC("uvmspace_init"); UVMHIST_CALLED(maphist);
   4115 
   4116 	memset(vm, 0, sizeof(*vm));
   4117 	uvm_map_setup(&vm->vm_map, vmin, vmax, VM_MAP_PAGEABLE
   4118 #ifdef __USING_TOPDOWN_VM
   4119 	    | VM_MAP_TOPDOWN
   4120 #endif
   4121 	    );
   4122 	if (pmap)
   4123 		pmap_reference(pmap);
   4124 	else
   4125 		pmap = pmap_create();
   4126 	vm->vm_map.pmap = pmap;
   4127 	vm->vm_refcnt = 1;
   4128 	UVMHIST_LOG(maphist,"<- done",0,0,0,0);
   4129 }
   4130 
   4131 /*
   4132  * uvmspace_share: share a vmspace between two processes
   4133  *
   4134  * - used for vfork, threads(?)
   4135  */
   4136 
   4137 void
   4138 uvmspace_share(struct proc *p1, struct proc *p2)
   4139 {
   4140 
   4141 	uvmspace_addref(p1->p_vmspace);
   4142 	p2->p_vmspace = p1->p_vmspace;
   4143 }
   4144 
   4145 /*
   4146  * uvmspace_unshare: ensure that process "p" has its own, unshared, vmspace
   4147  *
   4148  * - XXX: no locking on vmspace
   4149  */
   4150 
   4151 void
   4152 uvmspace_unshare(struct lwp *l)
   4153 {
   4154 	struct proc *p = l->l_proc;
   4155 	struct vmspace *nvm, *ovm = p->p_vmspace;
   4156 
   4157 	if (ovm->vm_refcnt == 1)
   4158 		/* nothing to do: vmspace isn't shared in the first place */
   4159 		return;
   4160 
   4161 	/* make a new vmspace, still holding old one */
   4162 	nvm = uvmspace_fork(ovm);
   4163 
   4164 	kpreempt_disable();
   4165 	pmap_deactivate(l);		/* unbind old vmspace */
   4166 	p->p_vmspace = nvm;
   4167 	pmap_activate(l);		/* switch to new vmspace */
   4168 	kpreempt_enable();
   4169 
   4170 	uvmspace_free(ovm);		/* drop reference to old vmspace */
   4171 }
   4172 
   4173 /*
   4174  * uvmspace_exec: the process wants to exec a new program
   4175  */
   4176 
   4177 void
   4178 uvmspace_exec(struct lwp *l, vaddr_t start, vaddr_t end)
   4179 {
   4180 	struct proc *p = l->l_proc;
   4181 	struct vmspace *nvm, *ovm = p->p_vmspace;
   4182 	struct vm_map *map = &ovm->vm_map;
   4183 
   4184 #ifdef __sparc__
   4185 	/* XXX cgd 960926: the sparc #ifdef should be a MD hook */
   4186 	kill_user_windows(l);   /* before stack addresses go away */
   4187 #endif
   4188 
   4189 	/*
   4190 	 * see if more than one process is using this vmspace...
   4191 	 */
   4192 
   4193 	if (ovm->vm_refcnt == 1) {
   4194 
   4195 		/*
   4196 		 * if p is the only process using its vmspace then we can safely
   4197 		 * recycle that vmspace for the program that is being exec'd.
   4198 		 */
   4199 
   4200 #ifdef SYSVSHM
   4201 		/*
   4202 		 * SYSV SHM semantics require us to kill all segments on an exec
   4203 		 */
   4204 
   4205 		if (ovm->vm_shm)
   4206 			shmexit(ovm);
   4207 #endif
   4208 
   4209 		/*
   4210 		 * POSIX 1003.1b -- "lock future mappings" is revoked
   4211 		 * when a process execs another program image.
   4212 		 */
   4213 
   4214 		map->flags &= ~VM_MAP_WIREFUTURE;
   4215 
   4216 		/*
   4217 		 * now unmap the old program
   4218 		 */
   4219 
   4220 		pmap_remove_all(map->pmap);
   4221 		uvm_unmap(map, vm_map_min(map), vm_map_max(map));
   4222 		KASSERT(map->header.prev == &map->header);
   4223 		KASSERT(map->nentries == 0);
   4224 
   4225 		/*
   4226 		 * resize the map
   4227 		 */
   4228 
   4229 		vm_map_setmin(map, start);
   4230 		vm_map_setmax(map, end);
   4231 	} else {
   4232 
   4233 		/*
   4234 		 * p's vmspace is being shared, so we can't reuse it for p since
   4235 		 * it is still being used for others.   allocate a new vmspace
   4236 		 * for p
   4237 		 */
   4238 
   4239 		nvm = uvmspace_alloc(start, end);
   4240 
   4241 		/*
   4242 		 * install new vmspace and drop our ref to the old one.
   4243 		 */
   4244 
   4245 		kpreempt_disable();
   4246 		pmap_deactivate(l);
   4247 		p->p_vmspace = nvm;
   4248 		pmap_activate(l);
   4249 		kpreempt_enable();
   4250 
   4251 		uvmspace_free(ovm);
   4252 	}
   4253 }
   4254 
   4255 /*
   4256  * uvmspace_addref: add a referece to a vmspace.
   4257  */
   4258 
   4259 void
   4260 uvmspace_addref(struct vmspace *vm)
   4261 {
   4262 	struct vm_map *map = &vm->vm_map;
   4263 
   4264 	KASSERT((map->flags & VM_MAP_DYING) == 0);
   4265 
   4266 	mutex_enter(&map->misc_lock);
   4267 	KASSERT(vm->vm_refcnt > 0);
   4268 	vm->vm_refcnt++;
   4269 	mutex_exit(&map->misc_lock);
   4270 }
   4271 
   4272 /*
   4273  * uvmspace_free: free a vmspace data structure
   4274  */
   4275 
   4276 void
   4277 uvmspace_free(struct vmspace *vm)
   4278 {
   4279 	struct vm_map_entry *dead_entries;
   4280 	struct vm_map *map = &vm->vm_map;
   4281 	int n;
   4282 
   4283 	UVMHIST_FUNC("uvmspace_free"); UVMHIST_CALLED(maphist);
   4284 
   4285 	UVMHIST_LOG(maphist,"(vm=0x%x) ref=%d", vm, vm->vm_refcnt,0,0);
   4286 	mutex_enter(&map->misc_lock);
   4287 	n = --vm->vm_refcnt;
   4288 	mutex_exit(&map->misc_lock);
   4289 	if (n > 0)
   4290 		return;
   4291 
   4292 	/*
   4293 	 * at this point, there should be no other references to the map.
   4294 	 * delete all of the mappings, then destroy the pmap.
   4295 	 */
   4296 
   4297 	map->flags |= VM_MAP_DYING;
   4298 	pmap_remove_all(map->pmap);
   4299 #ifdef SYSVSHM
   4300 	/* Get rid of any SYSV shared memory segments. */
   4301 	if (vm->vm_shm != NULL)
   4302 		shmexit(vm);
   4303 #endif
   4304 	if (map->nentries) {
   4305 		uvm_unmap_remove(map, vm_map_min(map), vm_map_max(map),
   4306 		    &dead_entries, NULL, 0);
   4307 		if (dead_entries != NULL)
   4308 			uvm_unmap_detach(dead_entries, 0);
   4309 	}
   4310 	KASSERT(map->nentries == 0);
   4311 	KASSERT(map->size == 0);
   4312 	mutex_destroy(&map->misc_lock);
   4313 	mutex_destroy(&map->mutex);
   4314 	rw_destroy(&map->lock);
   4315 	cv_destroy(&map->cv);
   4316 	pmap_destroy(map->pmap);
   4317 	pool_cache_put(&uvm_vmspace_cache, vm);
   4318 }
   4319 
   4320 /*
   4321  *   F O R K   -   m a i n   e n t r y   p o i n t
   4322  */
   4323 /*
   4324  * uvmspace_fork: fork a process' main map
   4325  *
   4326  * => create a new vmspace for child process from parent.
   4327  * => parent's map must not be locked.
   4328  */
   4329 
   4330 struct vmspace *
   4331 uvmspace_fork(struct vmspace *vm1)
   4332 {
   4333 	struct vmspace *vm2;
   4334 	struct vm_map *old_map = &vm1->vm_map;
   4335 	struct vm_map *new_map;
   4336 	struct vm_map_entry *old_entry;
   4337 	struct vm_map_entry *new_entry;
   4338 	UVMHIST_FUNC("uvmspace_fork"); UVMHIST_CALLED(maphist);
   4339 
   4340 	vm_map_lock(old_map);
   4341 
   4342 	vm2 = uvmspace_alloc(vm_map_min(old_map), vm_map_max(old_map));
   4343 	memcpy(&vm2->vm_startcopy, &vm1->vm_startcopy,
   4344 	    (char *) (vm1 + 1) - (char *) &vm1->vm_startcopy);
   4345 	new_map = &vm2->vm_map;		  /* XXX */
   4346 
   4347 	old_entry = old_map->header.next;
   4348 	new_map->size = old_map->size;
   4349 
   4350 	/*
   4351 	 * go entry-by-entry
   4352 	 */
   4353 
   4354 	while (old_entry != &old_map->header) {
   4355 
   4356 		/*
   4357 		 * first, some sanity checks on the old entry
   4358 		 */
   4359 
   4360 		KASSERT(!UVM_ET_ISSUBMAP(old_entry));
   4361 		KASSERT(UVM_ET_ISCOPYONWRITE(old_entry) ||
   4362 			!UVM_ET_ISNEEDSCOPY(old_entry));
   4363 
   4364 		switch (old_entry->inheritance) {
   4365 		case MAP_INHERIT_NONE:
   4366 
   4367 			/*
   4368 			 * drop the mapping, modify size
   4369 			 */
   4370 			new_map->size -= old_entry->end - old_entry->start;
   4371 			break;
   4372 
   4373 		case MAP_INHERIT_SHARE:
   4374 
   4375 			/*
   4376 			 * share the mapping: this means we want the old and
   4377 			 * new entries to share amaps and backing objects.
   4378 			 */
   4379 			/*
   4380 			 * if the old_entry needs a new amap (due to prev fork)
   4381 			 * then we need to allocate it now so that we have
   4382 			 * something we own to share with the new_entry.   [in
   4383 			 * other words, we need to clear needs_copy]
   4384 			 */
   4385 
   4386 			if (UVM_ET_ISNEEDSCOPY(old_entry)) {
   4387 				/* get our own amap, clears needs_copy */
   4388 				amap_copy(old_map, old_entry, AMAP_COPY_NOCHUNK,
   4389 				    0, 0);
   4390 				/* XXXCDC: WAITOK??? */
   4391 			}
   4392 
   4393 			new_entry = uvm_mapent_alloc(new_map, 0);
   4394 			/* old_entry -> new_entry */
   4395 			uvm_mapent_copy(old_entry, new_entry);
   4396 
   4397 			/* new pmap has nothing wired in it */
   4398 			new_entry->wired_count = 0;
   4399 
   4400 			/*
   4401 			 * gain reference to object backing the map (can't
   4402 			 * be a submap, already checked this case).
   4403 			 */
   4404 
   4405 			if (new_entry->aref.ar_amap)
   4406 				uvm_map_reference_amap(new_entry, AMAP_SHARED);
   4407 
   4408 			if (new_entry->object.uvm_obj &&
   4409 			    new_entry->object.uvm_obj->pgops->pgo_reference)
   4410 				new_entry->object.uvm_obj->
   4411 				    pgops->pgo_reference(
   4412 				        new_entry->object.uvm_obj);
   4413 
   4414 			/* insert entry at end of new_map's entry list */
   4415 			uvm_map_entry_link(new_map, new_map->header.prev,
   4416 			    new_entry);
   4417 
   4418 			break;
   4419 
   4420 		case MAP_INHERIT_COPY:
   4421 
   4422 			/*
   4423 			 * copy-on-write the mapping (using mmap's
   4424 			 * MAP_PRIVATE semantics)
   4425 			 *
   4426 			 * allocate new_entry, adjust reference counts.
   4427 			 * (note that new references are read-only).
   4428 			 */
   4429 
   4430 			new_entry = uvm_mapent_alloc(new_map, 0);
   4431 			/* old_entry -> new_entry */
   4432 			uvm_mapent_copy(old_entry, new_entry);
   4433 
   4434 			if (new_entry->aref.ar_amap)
   4435 				uvm_map_reference_amap(new_entry, 0);
   4436 
   4437 			if (new_entry->object.uvm_obj &&
   4438 			    new_entry->object.uvm_obj->pgops->pgo_reference)
   4439 				new_entry->object.uvm_obj->pgops->pgo_reference
   4440 				    (new_entry->object.uvm_obj);
   4441 
   4442 			/* new pmap has nothing wired in it */
   4443 			new_entry->wired_count = 0;
   4444 
   4445 			new_entry->etype |=
   4446 			    (UVM_ET_COPYONWRITE|UVM_ET_NEEDSCOPY);
   4447 			uvm_map_entry_link(new_map, new_map->header.prev,
   4448 			    new_entry);
   4449 
   4450 			/*
   4451 			 * the new entry will need an amap.  it will either
   4452 			 * need to be copied from the old entry or created
   4453 			 * from scratch (if the old entry does not have an
   4454 			 * amap).  can we defer this process until later
   4455 			 * (by setting "needs_copy") or do we need to copy
   4456 			 * the amap now?
   4457 			 *
   4458 			 * we must copy the amap now if any of the following
   4459 			 * conditions hold:
   4460 			 * 1. the old entry has an amap and that amap is
   4461 			 *    being shared.  this means that the old (parent)
   4462 			 *    process is sharing the amap with another
   4463 			 *    process.  if we do not clear needs_copy here
   4464 			 *    we will end up in a situation where both the
   4465 			 *    parent and child process are refering to the
   4466 			 *    same amap with "needs_copy" set.  if the
   4467 			 *    parent write-faults, the fault routine will
   4468 			 *    clear "needs_copy" in the parent by allocating
   4469 			 *    a new amap.   this is wrong because the
   4470 			 *    parent is supposed to be sharing the old amap
   4471 			 *    and the new amap will break that.
   4472 			 *
   4473 			 * 2. if the old entry has an amap and a non-zero
   4474 			 *    wire count then we are going to have to call
   4475 			 *    amap_cow_now to avoid page faults in the
   4476 			 *    parent process.   since amap_cow_now requires
   4477 			 *    "needs_copy" to be clear we might as well
   4478 			 *    clear it here as well.
   4479 			 *
   4480 			 */
   4481 
   4482 			if (old_entry->aref.ar_amap != NULL) {
   4483 				if ((amap_flags(old_entry->aref.ar_amap) &
   4484 				     AMAP_SHARED) != 0 ||
   4485 				    VM_MAPENT_ISWIRED(old_entry)) {
   4486 
   4487 					amap_copy(new_map, new_entry,
   4488 					    AMAP_COPY_NOCHUNK, 0, 0);
   4489 					/* XXXCDC: M_WAITOK ... ok? */
   4490 				}
   4491 			}
   4492 
   4493 			/*
   4494 			 * if the parent's entry is wired down, then the
   4495 			 * parent process does not want page faults on
   4496 			 * access to that memory.  this means that we
   4497 			 * cannot do copy-on-write because we can't write
   4498 			 * protect the old entry.   in this case we
   4499 			 * resolve all copy-on-write faults now, using
   4500 			 * amap_cow_now.   note that we have already
   4501 			 * allocated any needed amap (above).
   4502 			 */
   4503 
   4504 			if (VM_MAPENT_ISWIRED(old_entry)) {
   4505 
   4506 			  /*
   4507 			   * resolve all copy-on-write faults now
   4508 			   * (note that there is nothing to do if
   4509 			   * the old mapping does not have an amap).
   4510 			   */
   4511 			  if (old_entry->aref.ar_amap)
   4512 			    amap_cow_now(new_map, new_entry);
   4513 
   4514 			} else {
   4515 
   4516 			  /*
   4517 			   * setup mappings to trigger copy-on-write faults
   4518 			   * we must write-protect the parent if it has
   4519 			   * an amap and it is not already "needs_copy"...
   4520 			   * if it is already "needs_copy" then the parent
   4521 			   * has already been write-protected by a previous
   4522 			   * fork operation.
   4523 			   */
   4524 
   4525 			  if (old_entry->aref.ar_amap &&
   4526 			      !UVM_ET_ISNEEDSCOPY(old_entry)) {
   4527 			      if (old_entry->max_protection & VM_PROT_WRITE) {
   4528 				pmap_protect(old_map->pmap,
   4529 					     old_entry->start,
   4530 					     old_entry->end,
   4531 					     old_entry->protection &
   4532 					     ~VM_PROT_WRITE);
   4533 			      }
   4534 			      old_entry->etype |= UVM_ET_NEEDSCOPY;
   4535 			  }
   4536 			}
   4537 			break;
   4538 		}  /* end of switch statement */
   4539 		old_entry = old_entry->next;
   4540 	}
   4541 
   4542 	pmap_update(old_map->pmap);
   4543 	vm_map_unlock(old_map);
   4544 
   4545 #ifdef SYSVSHM
   4546 	if (vm1->vm_shm)
   4547 		shmfork(vm1, vm2);
   4548 #endif
   4549 
   4550 #ifdef PMAP_FORK
   4551 	pmap_fork(vm1->vm_map.pmap, vm2->vm_map.pmap);
   4552 #endif
   4553 
   4554 	UVMHIST_LOG(maphist,"<- done",0,0,0,0);
   4555 	return (vm2);
   4556 }
   4557 
   4558 
   4559 /*
   4560  * in-kernel map entry allocation.
   4561  */
   4562 
   4563 struct uvm_kmapent_hdr {
   4564 	LIST_ENTRY(uvm_kmapent_hdr) ukh_listq;
   4565 	int ukh_nused;
   4566 	struct vm_map_entry *ukh_freelist;
   4567 	struct vm_map *ukh_map;
   4568 	struct vm_map_entry ukh_entries[0];
   4569 };
   4570 
   4571 #define	UVM_KMAPENT_CHUNK				\
   4572 	((PAGE_SIZE - sizeof(struct uvm_kmapent_hdr))	\
   4573 	/ sizeof(struct vm_map_entry))
   4574 
   4575 #define	UVM_KHDR_FIND(entry)	\
   4576 	((struct uvm_kmapent_hdr *)(((vaddr_t)entry) & ~PAGE_MASK))
   4577 
   4578 
   4579 #ifdef DIAGNOSTIC
   4580 static struct vm_map *
   4581 uvm_kmapent_map(struct vm_map_entry *entry)
   4582 {
   4583 	const struct uvm_kmapent_hdr *ukh;
   4584 
   4585 	ukh = UVM_KHDR_FIND(entry);
   4586 	return ukh->ukh_map;
   4587 }
   4588 #endif
   4589 
   4590 static inline struct vm_map_entry *
   4591 uvm_kmapent_get(struct uvm_kmapent_hdr *ukh)
   4592 {
   4593 	struct vm_map_entry *entry;
   4594 
   4595 	KASSERT(ukh->ukh_nused <= UVM_KMAPENT_CHUNK);
   4596 	KASSERT(ukh->ukh_nused >= 0);
   4597 
   4598 	entry = ukh->ukh_freelist;
   4599 	if (entry) {
   4600 		KASSERT((entry->flags & (UVM_MAP_KERNEL | UVM_MAP_KMAPENT))
   4601 		    == UVM_MAP_KERNEL);
   4602 		ukh->ukh_freelist = entry->next;
   4603 		ukh->ukh_nused++;
   4604 		KASSERT(ukh->ukh_nused <= UVM_KMAPENT_CHUNK);
   4605 	} else {
   4606 		KASSERT(ukh->ukh_nused == UVM_KMAPENT_CHUNK);
   4607 	}
   4608 
   4609 	return entry;
   4610 }
   4611 
   4612 static inline void
   4613 uvm_kmapent_put(struct uvm_kmapent_hdr *ukh, struct vm_map_entry *entry)
   4614 {
   4615 
   4616 	KASSERT((entry->flags & (UVM_MAP_KERNEL | UVM_MAP_KMAPENT))
   4617 	    == UVM_MAP_KERNEL);
   4618 	KASSERT(ukh->ukh_nused <= UVM_KMAPENT_CHUNK);
   4619 	KASSERT(ukh->ukh_nused > 0);
   4620 	KASSERT(ukh->ukh_freelist != NULL ||
   4621 	    ukh->ukh_nused == UVM_KMAPENT_CHUNK);
   4622 	KASSERT(ukh->ukh_freelist == NULL ||
   4623 	    ukh->ukh_nused < UVM_KMAPENT_CHUNK);
   4624 
   4625 	ukh->ukh_nused--;
   4626 	entry->next = ukh->ukh_freelist;
   4627 	ukh->ukh_freelist = entry;
   4628 }
   4629 
   4630 /*
   4631  * uvm_kmapent_alloc: allocate a map entry for in-kernel map
   4632  */
   4633 
   4634 static struct vm_map_entry *
   4635 uvm_kmapent_alloc(struct vm_map *map, int flags)
   4636 {
   4637 	struct vm_page *pg;
   4638 	struct uvm_map_args args;
   4639 	struct uvm_kmapent_hdr *ukh;
   4640 	struct vm_map_entry *entry;
   4641 	uvm_flag_t mapflags = UVM_MAPFLAG(UVM_PROT_ALL, UVM_PROT_ALL,
   4642 	    UVM_INH_NONE, UVM_ADV_RANDOM, flags | UVM_FLAG_NOMERGE);
   4643 	vaddr_t va;
   4644 	int error;
   4645 	int i;
   4646 
   4647 	KDASSERT(UVM_KMAPENT_CHUNK > 2);
   4648 	KDASSERT(kernel_map != NULL);
   4649 	KASSERT(vm_map_pmap(map) == pmap_kernel());
   4650 
   4651 	UVMMAP_EVCNT_INCR(uke_alloc);
   4652 	entry = NULL;
   4653 again:
   4654 	/*
   4655 	 * try to grab an entry from freelist.
   4656 	 */
   4657 	mutex_spin_enter(&uvm_kentry_lock);
   4658 	ukh = LIST_FIRST(&vm_map_to_kernel(map)->vmk_kentry_free);
   4659 	if (ukh) {
   4660 		entry = uvm_kmapent_get(ukh);
   4661 		if (ukh->ukh_nused == UVM_KMAPENT_CHUNK)
   4662 			LIST_REMOVE(ukh, ukh_listq);
   4663 	}
   4664 	mutex_spin_exit(&uvm_kentry_lock);
   4665 
   4666 	if (entry)
   4667 		return entry;
   4668 
   4669 	/*
   4670 	 * there's no free entry for this vm_map.
   4671 	 * now we need to allocate some vm_map_entry.
   4672 	 * for simplicity, always allocate one page chunk of them at once.
   4673 	 */
   4674 
   4675 	pg = uvm_pagealloc(NULL, 0, NULL,
   4676 	    (flags & UVM_KMF_NOWAIT) != 0 ? UVM_PGA_USERESERVE : 0);
   4677 	if (__predict_false(pg == NULL)) {
   4678 		if (flags & UVM_FLAG_NOWAIT)
   4679 			return NULL;
   4680 		uvm_wait("kme_alloc");
   4681 		goto again;
   4682 	}
   4683 
   4684 	error = uvm_map_prepare(map, 0, PAGE_SIZE, NULL, UVM_UNKNOWN_OFFSET,
   4685 	    0, mapflags, &args);
   4686 	if (error) {
   4687 		uvm_pagefree(pg);
   4688 		return NULL;
   4689 	}
   4690 
   4691 	va = args.uma_start;
   4692 
   4693 	pmap_kenter_pa(va, VM_PAGE_TO_PHYS(pg),
   4694 	    VM_PROT_READ|VM_PROT_WRITE|PMAP_KMPAGE);
   4695 	pmap_update(vm_map_pmap(map));
   4696 
   4697 	ukh = (void *)va;
   4698 
   4699 	/*
   4700 	 * use the first entry for ukh itsself.
   4701 	 */
   4702 
   4703 	entry = &ukh->ukh_entries[0];
   4704 	entry->flags = UVM_MAP_KERNEL | UVM_MAP_KMAPENT;
   4705 	error = uvm_map_enter(map, &args, entry);
   4706 	KASSERT(error == 0);
   4707 
   4708 	ukh->ukh_nused = UVM_KMAPENT_CHUNK;
   4709 	ukh->ukh_map = map;
   4710 	ukh->ukh_freelist = NULL;
   4711 	for (i = UVM_KMAPENT_CHUNK - 1; i >= 2; i--) {
   4712 		struct vm_map_entry *xentry = &ukh->ukh_entries[i];
   4713 
   4714 		xentry->flags = UVM_MAP_KERNEL;
   4715 		uvm_kmapent_put(ukh, xentry);
   4716 	}
   4717 	KASSERT(ukh->ukh_nused == 2);
   4718 
   4719 	mutex_spin_enter(&uvm_kentry_lock);
   4720 	LIST_INSERT_HEAD(&vm_map_to_kernel(map)->vmk_kentry_free,
   4721 	    ukh, ukh_listq);
   4722 	mutex_spin_exit(&uvm_kentry_lock);
   4723 
   4724 	/*
   4725 	 * return second entry.
   4726 	 */
   4727 
   4728 	entry = &ukh->ukh_entries[1];
   4729 	entry->flags = UVM_MAP_KERNEL;
   4730 	UVMMAP_EVCNT_INCR(ukh_alloc);
   4731 	return entry;
   4732 }
   4733 
   4734 /*
   4735  * uvm_mapent_free: free map entry for in-kernel map
   4736  */
   4737 
   4738 static void
   4739 uvm_kmapent_free(struct vm_map_entry *entry)
   4740 {
   4741 	struct uvm_kmapent_hdr *ukh;
   4742 	struct vm_page *pg;
   4743 	struct vm_map *map;
   4744 	struct pmap *pmap;
   4745 	vaddr_t va;
   4746 	paddr_t pa;
   4747 	struct vm_map_entry *deadentry;
   4748 
   4749 	UVMMAP_EVCNT_INCR(uke_free);
   4750 	ukh = UVM_KHDR_FIND(entry);
   4751 	map = ukh->ukh_map;
   4752 
   4753 	mutex_spin_enter(&uvm_kentry_lock);
   4754 	uvm_kmapent_put(ukh, entry);
   4755 	if (ukh->ukh_nused > 1) {
   4756 		if (ukh->ukh_nused == UVM_KMAPENT_CHUNK - 1)
   4757 			LIST_INSERT_HEAD(
   4758 			    &vm_map_to_kernel(map)->vmk_kentry_free,
   4759 			    ukh, ukh_listq);
   4760 		mutex_spin_exit(&uvm_kentry_lock);
   4761 		return;
   4762 	}
   4763 
   4764 	/*
   4765 	 * now we can free this ukh.
   4766 	 *
   4767 	 * however, keep an empty ukh to avoid ping-pong.
   4768 	 */
   4769 
   4770 	if (LIST_FIRST(&vm_map_to_kernel(map)->vmk_kentry_free) == ukh &&
   4771 	    LIST_NEXT(ukh, ukh_listq) == NULL) {
   4772 		mutex_spin_exit(&uvm_kentry_lock);
   4773 		return;
   4774 	}
   4775 	LIST_REMOVE(ukh, ukh_listq);
   4776 	mutex_spin_exit(&uvm_kentry_lock);
   4777 
   4778 	KASSERT(ukh->ukh_nused == 1);
   4779 
   4780 	/*
   4781 	 * remove map entry for ukh itsself.
   4782 	 */
   4783 
   4784 	va = (vaddr_t)ukh;
   4785 	KASSERT((va & PAGE_MASK) == 0);
   4786 	vm_map_lock(map);
   4787 	uvm_unmap_remove(map, va, va + PAGE_SIZE, &deadentry, NULL, 0);
   4788 	KASSERT(deadentry->flags & UVM_MAP_KERNEL);
   4789 	KASSERT(deadentry->flags & UVM_MAP_KMAPENT);
   4790 	KASSERT(deadentry->next == NULL);
   4791 	KASSERT(deadentry == &ukh->ukh_entries[0]);
   4792 
   4793 	/*
   4794 	 * unmap the page from pmap and free it.
   4795 	 */
   4796 
   4797 	pmap = vm_map_pmap(map);
   4798 	KASSERT(pmap == pmap_kernel());
   4799 	if (!pmap_extract(pmap, va, &pa))
   4800 		panic("%s: no mapping", __func__);
   4801 	pmap_kremove(va, PAGE_SIZE);
   4802 	pmap_update(vm_map_pmap(map));
   4803 	vm_map_unlock(map);
   4804 	pg = PHYS_TO_VM_PAGE(pa);
   4805 	uvm_pagefree(pg);
   4806 	UVMMAP_EVCNT_INCR(ukh_free);
   4807 }
   4808 
   4809 static vsize_t
   4810 uvm_kmapent_overhead(vsize_t size)
   4811 {
   4812 
   4813 	/*
   4814 	 * - the max number of unmerged entries is howmany(size, PAGE_SIZE)
   4815 	 *   as the min allocation unit is PAGE_SIZE.
   4816 	 * - UVM_KMAPENT_CHUNK "kmapent"s are allocated from a page.
   4817 	 *   one of them are used to map the page itself.
   4818 	 */
   4819 
   4820 	return howmany(howmany(size, PAGE_SIZE), (UVM_KMAPENT_CHUNK - 1)) *
   4821 	    PAGE_SIZE;
   4822 }
   4823 
   4824 /*
   4825  * map entry reservation
   4826  */
   4827 
   4828 /*
   4829  * uvm_mapent_reserve: reserve map entries for clipping before locking map.
   4830  *
   4831  * => needed when unmapping entries allocated without UVM_FLAG_QUANTUM.
   4832  * => caller shouldn't hold map locked.
   4833  */
   4834 int
   4835 uvm_mapent_reserve(struct vm_map *map, struct uvm_mapent_reservation *umr,
   4836     int nentries, int flags)
   4837 {
   4838 
   4839 	umr->umr_nentries = 0;
   4840 
   4841 	if ((flags & UVM_FLAG_QUANTUM) != 0)
   4842 		return 0;
   4843 
   4844 	if (!VM_MAP_USE_KMAPENT(map))
   4845 		return 0;
   4846 
   4847 	while (nentries--) {
   4848 		struct vm_map_entry *ent;
   4849 		ent = uvm_kmapent_alloc(map, flags);
   4850 		if (!ent) {
   4851 			uvm_mapent_unreserve(map, umr);
   4852 			return ENOMEM;
   4853 		}
   4854 		UMR_PUTENTRY(umr, ent);
   4855 	}
   4856 
   4857 	return 0;
   4858 }
   4859 
   4860 /*
   4861  * uvm_mapent_unreserve:
   4862  *
   4863  * => caller shouldn't hold map locked.
   4864  * => never fail or sleep.
   4865  */
   4866 void
   4867 uvm_mapent_unreserve(struct vm_map *map, struct uvm_mapent_reservation *umr)
   4868 {
   4869 
   4870 	while (!UMR_EMPTY(umr))
   4871 		uvm_kmapent_free(UMR_GETENTRY(umr));
   4872 }
   4873 
   4874 /*
   4875  * uvm_mapent_trymerge: try to merge an entry with its neighbors.
   4876  *
   4877  * => called with map locked.
   4878  * => return non zero if successfully merged.
   4879  */
   4880 
   4881 int
   4882 uvm_mapent_trymerge(struct vm_map *map, struct vm_map_entry *entry, int flags)
   4883 {
   4884 	struct uvm_object *uobj;
   4885 	struct vm_map_entry *next;
   4886 	struct vm_map_entry *prev;
   4887 	vsize_t size;
   4888 	int merged = 0;
   4889 	bool copying;
   4890 	int newetype;
   4891 
   4892 	if (VM_MAP_USE_KMAPENT(map)) {
   4893 		return 0;
   4894 	}
   4895 	if (entry->aref.ar_amap != NULL) {
   4896 		return 0;
   4897 	}
   4898 	if ((entry->flags & UVM_MAP_NOMERGE) != 0) {
   4899 		return 0;
   4900 	}
   4901 
   4902 	uobj = entry->object.uvm_obj;
   4903 	size = entry->end - entry->start;
   4904 	copying = (flags & UVM_MERGE_COPYING) != 0;
   4905 	newetype = copying ? (entry->etype & ~UVM_ET_NEEDSCOPY) : entry->etype;
   4906 
   4907 	next = entry->next;
   4908 	if (next != &map->header &&
   4909 	    next->start == entry->end &&
   4910 	    ((copying && next->aref.ar_amap != NULL &&
   4911 	    amap_refs(next->aref.ar_amap) == 1) ||
   4912 	    (!copying && next->aref.ar_amap == NULL)) &&
   4913 	    UVM_ET_ISCOMPATIBLE(next, newetype,
   4914 	    uobj, entry->flags, entry->protection,
   4915 	    entry->max_protection, entry->inheritance, entry->advice,
   4916 	    entry->wired_count) &&
   4917 	    (uobj == NULL || entry->offset + size == next->offset)) {
   4918 		int error;
   4919 
   4920 		if (copying) {
   4921 			error = amap_extend(next, size,
   4922 			    AMAP_EXTEND_NOWAIT|AMAP_EXTEND_BACKWARDS);
   4923 		} else {
   4924 			error = 0;
   4925 		}
   4926 		if (error == 0) {
   4927 			if (uobj) {
   4928 				if (uobj->pgops->pgo_detach) {
   4929 					uobj->pgops->pgo_detach(uobj);
   4930 				}
   4931 			}
   4932 
   4933 			entry->end = next->end;
   4934 			clear_hints(map, next);
   4935 			uvm_map_entry_unlink(map, next);
   4936 			if (copying) {
   4937 				entry->aref = next->aref;
   4938 				entry->etype &= ~UVM_ET_NEEDSCOPY;
   4939 			}
   4940 			uvm_map_check(map, "trymerge forwardmerge");
   4941 			uvm_mapent_free_merged(map, next);
   4942 			merged++;
   4943 		}
   4944 	}
   4945 
   4946 	prev = entry->prev;
   4947 	if (prev != &map->header &&
   4948 	    prev->end == entry->start &&
   4949 	    ((copying && !merged && prev->aref.ar_amap != NULL &&
   4950 	    amap_refs(prev->aref.ar_amap) == 1) ||
   4951 	    (!copying && prev->aref.ar_amap == NULL)) &&
   4952 	    UVM_ET_ISCOMPATIBLE(prev, newetype,
   4953 	    uobj, entry->flags, entry->protection,
   4954 	    entry->max_protection, entry->inheritance, entry->advice,
   4955 	    entry->wired_count) &&
   4956 	    (uobj == NULL ||
   4957 	    prev->offset + prev->end - prev->start == entry->offset)) {
   4958 		int error;
   4959 
   4960 		if (copying) {
   4961 			error = amap_extend(prev, size,
   4962 			    AMAP_EXTEND_NOWAIT|AMAP_EXTEND_FORWARDS);
   4963 		} else {
   4964 			error = 0;
   4965 		}
   4966 		if (error == 0) {
   4967 			if (uobj) {
   4968 				if (uobj->pgops->pgo_detach) {
   4969 					uobj->pgops->pgo_detach(uobj);
   4970 				}
   4971 				entry->offset = prev->offset;
   4972 			}
   4973 
   4974 			entry->start = prev->start;
   4975 			clear_hints(map, prev);
   4976 			uvm_map_entry_unlink(map, prev);
   4977 			if (copying) {
   4978 				entry->aref = prev->aref;
   4979 				entry->etype &= ~UVM_ET_NEEDSCOPY;
   4980 			}
   4981 			uvm_map_check(map, "trymerge backmerge");
   4982 			uvm_mapent_free_merged(map, prev);
   4983 			merged++;
   4984 		}
   4985 	}
   4986 
   4987 	return merged;
   4988 }
   4989 
   4990 #if defined(DDB) || defined(DEBUGPRINT)
   4991 
   4992 /*
   4993  * DDB hooks
   4994  */
   4995 
   4996 /*
   4997  * uvm_map_printit: actually prints the map
   4998  */
   4999 
   5000 void
   5001 uvm_map_printit(struct vm_map *map, bool full,
   5002     void (*pr)(const char *, ...))
   5003 {
   5004 	struct vm_map_entry *entry;
   5005 
   5006 	(*pr)("MAP %p: [0x%lx->0x%lx]\n", map, vm_map_min(map),
   5007 	    vm_map_max(map));
   5008 	(*pr)("\t#ent=%d, sz=%d, ref=%d, version=%d, flags=0x%x\n",
   5009 	    map->nentries, map->size, map->ref_count, map->timestamp,
   5010 	    map->flags);
   5011 	(*pr)("\tpmap=%p(resident=%ld, wired=%ld)\n", map->pmap,
   5012 	    pmap_resident_count(map->pmap), pmap_wired_count(map->pmap));
   5013 	if (!full)
   5014 		return;
   5015 	for (entry = map->header.next; entry != &map->header;
   5016 	    entry = entry->next) {
   5017 		(*pr)(" - %p: 0x%lx->0x%lx: obj=%p/0x%llx, amap=%p/%d\n",
   5018 		    entry, entry->start, entry->end, entry->object.uvm_obj,
   5019 		    (long long)entry->offset, entry->aref.ar_amap,
   5020 		    entry->aref.ar_pageoff);
   5021 		(*pr)(
   5022 		    "\tsubmap=%c, cow=%c, nc=%c, prot(max)=%d/%d, inh=%d, "
   5023 		    "wc=%d, adv=%d\n",
   5024 		    (entry->etype & UVM_ET_SUBMAP) ? 'T' : 'F',
   5025 		    (entry->etype & UVM_ET_COPYONWRITE) ? 'T' : 'F',
   5026 		    (entry->etype & UVM_ET_NEEDSCOPY) ? 'T' : 'F',
   5027 		    entry->protection, entry->max_protection,
   5028 		    entry->inheritance, entry->wired_count, entry->advice);
   5029 	}
   5030 }
   5031 
   5032 /*
   5033  * uvm_object_printit: actually prints the object
   5034  */
   5035 
   5036 void
   5037 uvm_object_printit(struct uvm_object *uobj, bool full,
   5038     void (*pr)(const char *, ...))
   5039 {
   5040 	struct vm_page *pg;
   5041 	int cnt = 0;
   5042 
   5043 	(*pr)("OBJECT %p: locked=%d, pgops=%p, npages=%d, ",
   5044 	    uobj, mutex_owned(&uobj->vmobjlock), uobj->pgops, uobj->uo_npages);
   5045 	if (UVM_OBJ_IS_KERN_OBJECT(uobj))
   5046 		(*pr)("refs=<SYSTEM>\n");
   5047 	else
   5048 		(*pr)("refs=%d\n", uobj->uo_refs);
   5049 
   5050 	if (!full) {
   5051 		return;
   5052 	}
   5053 	(*pr)("  PAGES <pg,offset>:\n  ");
   5054 	TAILQ_FOREACH(pg, &uobj->memq, listq.queue) {
   5055 		cnt++;
   5056 		(*pr)("<%p,0x%llx> ", pg, (long long)pg->offset);
   5057 		if ((cnt % 3) == 0) {
   5058 			(*pr)("\n  ");
   5059 		}
   5060 	}
   5061 	if ((cnt % 3) != 0) {
   5062 		(*pr)("\n");
   5063 	}
   5064 }
   5065 
   5066 /*
   5067  * uvm_page_printit: actually print the page
   5068  */
   5069 
   5070 static const char page_flagbits[] = UVM_PGFLAGBITS;
   5071 static const char page_pqflagbits[] = UVM_PQFLAGBITS;
   5072 
   5073 void
   5074 uvm_page_printit(struct vm_page *pg, bool full,
   5075     void (*pr)(const char *, ...))
   5076 {
   5077 	struct vm_page *tpg;
   5078 	struct uvm_object *uobj;
   5079 	struct pgflist *pgl;
   5080 	char pgbuf[128];
   5081 	char pqbuf[128];
   5082 
   5083 	(*pr)("PAGE %p:\n", pg);
   5084 	snprintb(pgbuf, sizeof(pgbuf), page_flagbits, pg->flags);
   5085 	snprintb(pqbuf, sizeof(pqbuf), page_pqflagbits, pg->pqflags);
   5086 	(*pr)("  flags=%s, pqflags=%s, wire_count=%d, pa=0x%lx\n",
   5087 	    pgbuf, pqbuf, pg->wire_count, (long)VM_PAGE_TO_PHYS(pg));
   5088 	(*pr)("  uobject=%p, uanon=%p, offset=0x%llx loan_count=%d\n",
   5089 	    pg->uobject, pg->uanon, (long long)pg->offset, pg->loan_count);
   5090 #if defined(UVM_PAGE_TRKOWN)
   5091 	if (pg->flags & PG_BUSY)
   5092 		(*pr)("  owning process = %d, tag=%s\n",
   5093 		    pg->owner, pg->owner_tag);
   5094 	else
   5095 		(*pr)("  page not busy, no owner\n");
   5096 #else
   5097 	(*pr)("  [page ownership tracking disabled]\n");
   5098 #endif
   5099 
   5100 	if (!full)
   5101 		return;
   5102 
   5103 	/* cross-verify object/anon */
   5104 	if ((pg->pqflags & PQ_FREE) == 0) {
   5105 		if (pg->pqflags & PQ_ANON) {
   5106 			if (pg->uanon == NULL || pg->uanon->an_page != pg)
   5107 			    (*pr)("  >>> ANON DOES NOT POINT HERE <<< (%p)\n",
   5108 				(pg->uanon) ? pg->uanon->an_page : NULL);
   5109 			else
   5110 				(*pr)("  anon backpointer is OK\n");
   5111 		} else {
   5112 			uobj = pg->uobject;
   5113 			if (uobj) {
   5114 				(*pr)("  checking object list\n");
   5115 				TAILQ_FOREACH(tpg, &uobj->memq, listq.queue) {
   5116 					if (tpg == pg) {
   5117 						break;
   5118 					}
   5119 				}
   5120 				if (tpg)
   5121 					(*pr)("  page found on object list\n");
   5122 				else
   5123 			(*pr)("  >>> PAGE NOT FOUND ON OBJECT LIST! <<<\n");
   5124 			}
   5125 		}
   5126 	}
   5127 
   5128 	/* cross-verify page queue */
   5129 	if (pg->pqflags & PQ_FREE) {
   5130 		int fl = uvm_page_lookup_freelist(pg);
   5131 		int color = VM_PGCOLOR_BUCKET(pg);
   5132 		pgl = &uvm.page_free[fl].pgfl_buckets[color].pgfl_queues[
   5133 		    ((pg)->flags & PG_ZERO) ? PGFL_ZEROS : PGFL_UNKNOWN];
   5134 	} else {
   5135 		pgl = NULL;
   5136 	}
   5137 
   5138 	if (pgl) {
   5139 		(*pr)("  checking pageq list\n");
   5140 		LIST_FOREACH(tpg, pgl, pageq.list) {
   5141 			if (tpg == pg) {
   5142 				break;
   5143 			}
   5144 		}
   5145 		if (tpg)
   5146 			(*pr)("  page found on pageq list\n");
   5147 		else
   5148 			(*pr)("  >>> PAGE NOT FOUND ON PAGEQ LIST! <<<\n");
   5149 	}
   5150 }
   5151 
   5152 /*
   5153  * uvm_pages_printthem - print a summary of all managed pages
   5154  */
   5155 
   5156 void
   5157 uvm_page_printall(void (*pr)(const char *, ...))
   5158 {
   5159 	unsigned i;
   5160 	struct vm_page *pg;
   5161 
   5162 	(*pr)("%18s %4s %4s %18s %18s"
   5163 #ifdef UVM_PAGE_TRKOWN
   5164 	    " OWNER"
   5165 #endif
   5166 	    "\n", "PAGE", "FLAG", "PQ", "UOBJECT", "UANON");
   5167 	for (i = 0; i < vm_nphysseg; i++) {
   5168 		for (pg = vm_physmem[i].pgs; pg <= vm_physmem[i].lastpg; pg++) {
   5169 			(*pr)("%18p %04x %04x %18p %18p",
   5170 			    pg, pg->flags, pg->pqflags, pg->uobject,
   5171 			    pg->uanon);
   5172 #ifdef UVM_PAGE_TRKOWN
   5173 			if (pg->flags & PG_BUSY)
   5174 				(*pr)(" %d [%s]", pg->owner, pg->owner_tag);
   5175 #endif
   5176 			(*pr)("\n");
   5177 		}
   5178 	}
   5179 }
   5180 
   5181 #endif
   5182 
   5183 /*
   5184  * uvm_map_create: create map
   5185  */
   5186 
   5187 struct vm_map *
   5188 uvm_map_create(pmap_t pmap, vaddr_t vmin, vaddr_t vmax, int flags)
   5189 {
   5190 	struct vm_map *result;
   5191 
   5192 	result = malloc(sizeof(struct vm_map), M_VMMAP, M_WAITOK);
   5193 	uvm_map_setup(result, vmin, vmax, flags);
   5194 	result->pmap = pmap;
   5195 	return(result);
   5196 }
   5197 
   5198 /*
   5199  * uvm_map_setup: init map
   5200  *
   5201  * => map must not be in service yet.
   5202  */
   5203 
   5204 void
   5205 uvm_map_setup(struct vm_map *map, vaddr_t vmin, vaddr_t vmax, int flags)
   5206 {
   5207 	int ipl;
   5208 
   5209 	rb_tree_init(&map->rb_tree, &uvm_map_tree_ops);
   5210 	map->header.next = map->header.prev = &map->header;
   5211 	map->nentries = 0;
   5212 	map->size = 0;
   5213 	map->ref_count = 1;
   5214 	vm_map_setmin(map, vmin);
   5215 	vm_map_setmax(map, vmax);
   5216 	map->flags = flags;
   5217 	map->first_free = &map->header;
   5218 	map->hint = &map->header;
   5219 	map->timestamp = 0;
   5220 	map->busy = NULL;
   5221 
   5222 	if ((flags & VM_MAP_INTRSAFE) != 0) {
   5223 		ipl = IPL_VM;
   5224 	} else {
   5225 		ipl = IPL_NONE;
   5226 	}
   5227 
   5228 	rw_init(&map->lock);
   5229 	cv_init(&map->cv, "vm_map");
   5230 	mutex_init(&map->misc_lock, MUTEX_DRIVER, ipl);
   5231 	mutex_init(&map->mutex, MUTEX_DRIVER, ipl);
   5232 }
   5233 
   5234 
   5235 /*
   5236  *   U N M A P   -   m a i n   e n t r y   p o i n t
   5237  */
   5238 
   5239 /*
   5240  * uvm_unmap1: remove mappings from a vm_map (from "start" up to "stop")
   5241  *
   5242  * => caller must check alignment and size
   5243  * => map must be unlocked (we will lock it)
   5244  * => flags is UVM_FLAG_QUANTUM or 0.
   5245  */
   5246 
   5247 void
   5248 uvm_unmap1(struct vm_map *map, vaddr_t start, vaddr_t end, int flags)
   5249 {
   5250 	struct vm_map_entry *dead_entries;
   5251 	struct uvm_mapent_reservation umr;
   5252 	UVMHIST_FUNC("uvm_unmap"); UVMHIST_CALLED(maphist);
   5253 
   5254 	UVMHIST_LOG(maphist, "  (map=0x%x, start=0x%x, end=0x%x)",
   5255 	    map, start, end, 0);
   5256 	if (map == kernel_map) {
   5257 		LOCKDEBUG_MEM_CHECK((void *)start, end - start);
   5258 	}
   5259 	/*
   5260 	 * work now done by helper functions.   wipe the pmap's and then
   5261 	 * detach from the dead entries...
   5262 	 */
   5263 	uvm_mapent_reserve(map, &umr, 2, flags);
   5264 	vm_map_lock(map);
   5265 	uvm_unmap_remove(map, start, end, &dead_entries, &umr, flags);
   5266 	vm_map_unlock(map);
   5267 	uvm_mapent_unreserve(map, &umr);
   5268 
   5269 	if (dead_entries != NULL)
   5270 		uvm_unmap_detach(dead_entries, 0);
   5271 
   5272 	UVMHIST_LOG(maphist, "<- done", 0,0,0,0);
   5273 }
   5274 
   5275 
   5276 /*
   5277  * uvm_map_reference: add reference to a map
   5278  *
   5279  * => map need not be locked (we use misc_lock).
   5280  */
   5281 
   5282 void
   5283 uvm_map_reference(struct vm_map *map)
   5284 {
   5285 	mutex_enter(&map->misc_lock);
   5286 	map->ref_count++;
   5287 	mutex_exit(&map->misc_lock);
   5288 }
   5289 
   5290 struct vm_map_kernel *
   5291 vm_map_to_kernel(struct vm_map *map)
   5292 {
   5293 
   5294 	KASSERT(VM_MAP_IS_KERNEL(map));
   5295 
   5296 	return (struct vm_map_kernel *)map;
   5297 }
   5298 
   5299 bool
   5300 vm_map_starved_p(struct vm_map *map)
   5301 {
   5302 
   5303 	if ((map->flags & VM_MAP_WANTVA) != 0) {
   5304 		return true;
   5305 	}
   5306 	/* XXX */
   5307 	if ((vm_map_max(map) - vm_map_min(map)) / 16 * 15 < map->size) {
   5308 		return true;
   5309 	}
   5310 	return false;
   5311 }
   5312 
   5313 #if defined(DDB) || defined(DEBUGPRINT)
   5314 void
   5315 uvm_whatis(uintptr_t addr, void (*pr)(const char *, ...))
   5316 {
   5317 	struct vm_map *map;
   5318 
   5319 	for (map = kernel_map;;) {
   5320 		struct vm_map_entry *entry;
   5321 
   5322 		if (!uvm_map_lookup_entry_bytree(map, (vaddr_t)addr, &entry)) {
   5323 			break;
   5324 		}
   5325 		(*pr)("%p is %p+%zu from VMMAP %p\n",
   5326 		    (void *)addr, (void *)entry->start,
   5327 		    (size_t)(addr - (uintptr_t)entry->start), map);
   5328 		if (!UVM_ET_ISSUBMAP(entry)) {
   5329 			break;
   5330 		}
   5331 		map = entry->object.sub_map;
   5332 	}
   5333 }
   5334 #endif /* defined(DDB) || defined(DEBUGPRINT) */
   5335