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