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