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