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