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