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