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