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