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