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