Home | History | Annotate | Line # | Download | only in uvm
uvm_map.c revision 1.147
      1 /*	$NetBSD: uvm_map.c,v 1.147 2003/11/02 07:58:52 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.147 2003/11/02 07:58:52 yamt Exp $");
     75 
     76 #include "opt_ddb.h"
     77 #include "opt_uvmhist.h"
     78 #include "opt_sysv.h"
     79 
     80 #include <sys/param.h>
     81 #include <sys/systm.h>
     82 #include <sys/mman.h>
     83 #include <sys/proc.h>
     84 #include <sys/malloc.h>
     85 #include <sys/pool.h>
     86 #include <sys/kernel.h>
     87 #include <sys/mount.h>
     88 /* XXX uvm_map.h is included by vnode.h */
     89 #define	RB_AUGMENT(x)	uvm_rb_augment(x)
     90 #include <sys/vnode.h>
     91 
     92 #ifdef SYSVSHM
     93 #include <sys/shm.h>
     94 #endif
     95 
     96 #define UVM_MAP
     97 #include <uvm/uvm.h>
     98 
     99 #ifdef DDB
    100 #include <uvm/uvm_ddb.h>
    101 #endif
    102 
    103 extern struct vm_map *pager_map;
    104 
    105 struct uvm_cnt map_ubackmerge, map_uforwmerge;
    106 struct uvm_cnt map_ubimerge, map_unomerge;
    107 struct uvm_cnt map_kbackmerge, map_kforwmerge;
    108 struct uvm_cnt map_kbimerge, map_knomerge;
    109 struct uvm_cnt uvm_map_call, uvm_mlk_call, uvm_mlk_hint;
    110 const char vmmapbsy[] = "vmmapbsy";
    111 
    112 /*
    113  * pool for vmspace structures.
    114  */
    115 
    116 struct pool uvm_vmspace_pool;
    117 
    118 /*
    119  * pool for dynamically-allocated map entries.
    120  */
    121 
    122 struct pool uvm_map_entry_pool;
    123 struct pool uvm_map_entry_kmem_pool;
    124 
    125 MALLOC_DEFINE(M_VMMAP, "VM map", "VM map structures");
    126 MALLOC_DEFINE(M_VMPMAP, "VM pmap", "VM pmap");
    127 
    128 #ifdef PMAP_GROWKERNEL
    129 /*
    130  * This global represents the end of the kernel virtual address
    131  * space.  If we want to exceed this, we must grow the kernel
    132  * virtual address space dynamically.
    133  *
    134  * Note, this variable is locked by kernel_map's lock.
    135  */
    136 vaddr_t uvm_maxkaddr;
    137 #endif
    138 
    139 /*
    140  * macros
    141  */
    142 
    143 /*
    144  * uvm_map_entry_link: insert entry into a map
    145  *
    146  * => map must be locked
    147  */
    148 #define uvm_map_entry_link(map, after_where, entry) do { \
    149 	KASSERT(entry->start < entry->end); \
    150 	(map)->nentries++; \
    151 	(entry)->prev = (after_where); \
    152 	(entry)->next = (after_where)->next; \
    153 	(entry)->prev->next = (entry); \
    154 	(entry)->next->prev = (entry); \
    155 	uvm_rb_insert((map), (entry)); \
    156 } while (/*CONSTCOND*/ 0)
    157 
    158 /*
    159  * uvm_map_entry_unlink: remove entry from a map
    160  *
    161  * => map must be locked
    162  */
    163 #define uvm_map_entry_unlink(map, entry) do { \
    164 	(map)->nentries--; \
    165 	(entry)->next->prev = (entry)->prev; \
    166 	(entry)->prev->next = (entry)->next; \
    167 	uvm_rb_remove((map), (entry)); \
    168 } while (/*CONSTCOND*/ 0)
    169 
    170 /*
    171  * SAVE_HINT: saves the specified entry as the hint for future lookups.
    172  *
    173  * => map need not be locked (protected by hint_lock).
    174  */
    175 #define SAVE_HINT(map,check,value) do { \
    176 	simple_lock(&(map)->hint_lock); \
    177 	if ((map)->hint == (check)) \
    178 		(map)->hint = (value); \
    179 	simple_unlock(&(map)->hint_lock); \
    180 } while (/*CONSTCOND*/ 0)
    181 
    182 /*
    183  * VM_MAP_RANGE_CHECK: check and correct range
    184  *
    185  * => map must at least be read locked
    186  */
    187 
    188 #define VM_MAP_RANGE_CHECK(map, start, end) do { \
    189 	if (start < vm_map_min(map))		\
    190 		start = vm_map_min(map);	\
    191 	if (end > vm_map_max(map))		\
    192 		end = vm_map_max(map);		\
    193 	if (start > end)			\
    194 		start = end;			\
    195 } while (/*CONSTCOND*/ 0)
    196 
    197 /*
    198  * local prototypes
    199  */
    200 
    201 static struct vm_map_entry *
    202 		uvm_mapent_alloc(struct vm_map *, int);
    203 static void	uvm_mapent_copy(struct vm_map_entry *, struct vm_map_entry *);
    204 static void	uvm_mapent_free(struct vm_map_entry *);
    205 static void	uvm_map_entry_unwire(struct vm_map *, struct vm_map_entry *);
    206 static void	uvm_map_reference_amap(struct vm_map_entry *, int);
    207 static int	uvm_map_space_avail(vaddr_t *, vsize_t, voff_t, vsize_t, int,
    208 		    struct vm_map_entry *);
    209 static void	uvm_map_unreference_amap(struct vm_map_entry *, int);
    210 
    211 int _uvm_tree_sanity(struct vm_map *, const char *);
    212 static vsize_t uvm_rb_subtree_space(const struct vm_map_entry *);
    213 
    214 static __inline int
    215 uvm_compare(const struct vm_map_entry *a, const struct vm_map_entry *b)
    216 {
    217 
    218 	if (a->start < b->start)
    219 		return (-1);
    220 	else if (a->start > b->start)
    221 		return (1);
    222 
    223 	return (0);
    224 }
    225 
    226 static __inline void
    227 uvm_rb_augment(struct vm_map_entry *entry)
    228 {
    229 
    230 	entry->space = uvm_rb_subtree_space(entry);
    231 }
    232 
    233 RB_PROTOTYPE(uvm_tree, vm_map_entry, rb_entry, uvm_compare);
    234 
    235 RB_GENERATE(uvm_tree, vm_map_entry, rb_entry, uvm_compare);
    236 
    237 static __inline vsize_t
    238 uvm_rb_space(const struct vm_map *map, const struct vm_map_entry *entry)
    239 {
    240 	/* XXX map is not used */
    241 
    242 	KASSERT(entry->next != NULL);
    243 	return entry->next->start - entry->end;
    244 }
    245 
    246 static vsize_t
    247 uvm_rb_subtree_space(const struct vm_map_entry *entry)
    248 {
    249 	vaddr_t space, tmp;
    250 
    251 	space = entry->ownspace;
    252 	if (RB_LEFT(entry, rb_entry)) {
    253 		tmp = RB_LEFT(entry, rb_entry)->space;
    254 		if (tmp > space)
    255 			space = tmp;
    256 	}
    257 
    258 	if (RB_RIGHT(entry, rb_entry)) {
    259 		tmp = RB_RIGHT(entry, rb_entry)->space;
    260 		if (tmp > space)
    261 			space = tmp;
    262 	}
    263 
    264 	return (space);
    265 }
    266 
    267 static __inline void
    268 uvm_rb_fixup(struct vm_map *map, struct vm_map_entry *entry)
    269 {
    270 	/* We need to traverse to the very top */
    271 	do {
    272 		entry->ownspace = uvm_rb_space(map, entry);
    273 		entry->space = uvm_rb_subtree_space(entry);
    274 	} while ((entry = RB_PARENT(entry, rb_entry)) != NULL);
    275 }
    276 
    277 static __inline void
    278 uvm_rb_insert(struct vm_map *map, struct vm_map_entry *entry)
    279 {
    280 	vaddr_t space = uvm_rb_space(map, entry);
    281 	struct vm_map_entry *tmp;
    282 
    283 	entry->ownspace = entry->space = space;
    284 	tmp = RB_INSERT(uvm_tree, &(map)->rbhead, entry);
    285 #ifdef DIAGNOSTIC
    286 	if (tmp != NULL)
    287 		panic("uvm_rb_insert: duplicate entry?");
    288 #endif
    289 	uvm_rb_fixup(map, entry);
    290 	if (entry->prev != &map->header)
    291 		uvm_rb_fixup(map, entry->prev);
    292 }
    293 
    294 static __inline void
    295 uvm_rb_remove(struct vm_map *map, struct vm_map_entry *entry)
    296 {
    297 	struct vm_map_entry *parent;
    298 
    299 	parent = RB_PARENT(entry, rb_entry);
    300 	RB_REMOVE(uvm_tree, &(map)->rbhead, entry);
    301 	if (entry->prev != &map->header)
    302 		uvm_rb_fixup(map, entry->prev);
    303 	if (parent)
    304 		uvm_rb_fixup(map, parent);
    305 }
    306 
    307 #ifdef DEBUG
    308 #define uvm_tree_sanity(x,y) _uvm_tree_sanity(x,y)
    309 #else
    310 #define uvm_tree_sanity(x,y)
    311 #endif
    312 
    313 int
    314 _uvm_tree_sanity(struct vm_map *map, const char *name)
    315 {
    316 	struct vm_map_entry *tmp, *trtmp;
    317 	int n = 0, i = 1;
    318 
    319 	RB_FOREACH(tmp, uvm_tree, &map->rbhead) {
    320 		if (tmp->ownspace != uvm_rb_space(map, tmp)) {
    321 			printf("%s: %d/%d ownspace %lx != %lx %s\n",
    322 			    name, n + 1, map->nentries,
    323 			    (ulong)tmp->ownspace, (ulong)uvm_rb_space(map, tmp),
    324 			    tmp->next == &map->header ? "(last)" : "");
    325 			goto error;
    326 		}
    327 	}
    328 	trtmp = NULL;
    329 	RB_FOREACH(tmp, uvm_tree, &map->rbhead) {
    330 		if (tmp->space != uvm_rb_subtree_space(tmp)) {
    331 			printf("%s: space %lx != %lx\n",
    332 			    name, (ulong)tmp->space,
    333 			    (ulong)uvm_rb_subtree_space(tmp));
    334 			goto error;
    335 		}
    336 		if (trtmp != NULL && trtmp->start >= tmp->start) {
    337 			printf("%s: corrupt: 0x%lx >= 0x%lx\n",
    338 			    name, trtmp->start, tmp->start);
    339 			goto error;
    340 		}
    341 		n++;
    342 
    343 		trtmp = tmp;
    344 	}
    345 
    346 	if (n != map->nentries) {
    347 		printf("%s: nentries: %d vs %d\n",
    348 		    name, n, map->nentries);
    349 		goto error;
    350 	}
    351 
    352 	for (tmp = map->header.next; tmp && tmp != &map->header;
    353 	    tmp = tmp->next, i++) {
    354 		trtmp = RB_FIND(uvm_tree, &map->rbhead, tmp);
    355 		if (trtmp != tmp) {
    356 			printf("%s: lookup: %d: %p - %p: %p\n",
    357 			    name, i, tmp, trtmp,
    358 			    RB_PARENT(tmp, rb_entry));
    359 			goto error;
    360 		}
    361 	}
    362 
    363 	return (0);
    364  error:
    365 #ifdef	DDB
    366 	/* handy breakpoint location for error case */
    367 	__asm(".globl treesanity_label\ntreesanity_label:");
    368 #endif
    369 	return (-1);
    370 }
    371 
    372 /*
    373  * local inlines
    374  */
    375 
    376 /*
    377  * uvm_mapent_alloc: allocate a map entry
    378  */
    379 
    380 static __inline struct vm_map_entry *
    381 uvm_mapent_alloc(struct vm_map *map, int flags)
    382 {
    383 	struct vm_map_entry *me;
    384 	int s;
    385 	int pflags = (flags & UVM_FLAG_NOWAIT) ? PR_NOWAIT : PR_WAITOK;
    386 	UVMHIST_FUNC("uvm_mapent_alloc"); UVMHIST_CALLED(maphist);
    387 
    388 	if (map->flags & VM_MAP_INTRSAFE || cold) {
    389 		s = splvm();
    390 		simple_lock(&uvm.kentry_lock);
    391 		me = uvm.kentry_free;
    392 		if (me)
    393 			uvm.kentry_free = me->next;
    394 		simple_unlock(&uvm.kentry_lock);
    395 		splx(s);
    396 		if (__predict_false(me == NULL)) {
    397 			panic("uvm_mapent_alloc: out of static map entries, "
    398 			    "check MAX_KMAPENT (currently %d)",
    399 			    MAX_KMAPENT);
    400 		}
    401 		me->flags = UVM_MAP_STATIC;
    402 	} else if (map == kernel_map) {
    403 		me = pool_get(&uvm_map_entry_kmem_pool, pflags);
    404 		if (__predict_false(me == NULL))
    405 			return NULL;
    406 		me->flags = UVM_MAP_KMEM;
    407 	} else {
    408 		me = pool_get(&uvm_map_entry_pool, pflags);
    409 		if (__predict_false(me == NULL))
    410 			return NULL;
    411 		me->flags = 0;
    412 	}
    413 
    414 	UVMHIST_LOG(maphist, "<- new entry=0x%x [kentry=%d]", me,
    415 	    ((map->flags & VM_MAP_INTRSAFE) != 0 || map == kernel_map), 0, 0);
    416 	return (me);
    417 }
    418 
    419 /*
    420  * uvm_mapent_free: free map entry
    421  */
    422 
    423 static __inline void
    424 uvm_mapent_free(struct vm_map_entry *me)
    425 {
    426 	int s;
    427 	UVMHIST_FUNC("uvm_mapent_free"); UVMHIST_CALLED(maphist);
    428 
    429 	UVMHIST_LOG(maphist,"<- freeing map entry=0x%x [flags=%d]",
    430 		me, me->flags, 0, 0);
    431 	if (me->flags & UVM_MAP_STATIC) {
    432 		s = splvm();
    433 		simple_lock(&uvm.kentry_lock);
    434 		me->next = uvm.kentry_free;
    435 		uvm.kentry_free = me;
    436 		simple_unlock(&uvm.kentry_lock);
    437 		splx(s);
    438 	} else if (me->flags & UVM_MAP_KMEM) {
    439 		pool_put(&uvm_map_entry_kmem_pool, me);
    440 	} else {
    441 		pool_put(&uvm_map_entry_pool, me);
    442 	}
    443 }
    444 
    445 /*
    446  * uvm_mapent_copy: copy a map entry, preserving flags
    447  */
    448 
    449 static __inline void
    450 uvm_mapent_copy(struct vm_map_entry *src, struct vm_map_entry *dst)
    451 {
    452 
    453 	memcpy(dst, src, ((char *)&src->uvm_map_entry_stop_copy) -
    454 	    ((char *)src));
    455 }
    456 
    457 /*
    458  * uvm_map_entry_unwire: unwire a map entry
    459  *
    460  * => map should be locked by caller
    461  */
    462 
    463 static __inline void
    464 uvm_map_entry_unwire(struct vm_map *map, struct vm_map_entry *entry)
    465 {
    466 
    467 	entry->wired_count = 0;
    468 	uvm_fault_unwire_locked(map, entry->start, entry->end);
    469 }
    470 
    471 
    472 /*
    473  * wrapper for calling amap_ref()
    474  */
    475 static __inline void
    476 uvm_map_reference_amap(struct vm_map_entry *entry, int flags)
    477 {
    478 
    479 	amap_ref(entry->aref.ar_amap, entry->aref.ar_pageoff,
    480 	    (entry->end - entry->start) >> PAGE_SHIFT, flags);
    481 }
    482 
    483 
    484 /*
    485  * wrapper for calling amap_unref()
    486  */
    487 static __inline void
    488 uvm_map_unreference_amap(struct vm_map_entry *entry, int flags)
    489 {
    490 
    491 	amap_unref(entry->aref.ar_amap, entry->aref.ar_pageoff,
    492 	    (entry->end - entry->start) >> PAGE_SHIFT, flags);
    493 }
    494 
    495 
    496 /*
    497  * uvm_map_init: init mapping system at boot time.   note that we allocate
    498  * and init the static pool of struct vm_map_entry *'s for the kernel here.
    499  */
    500 
    501 void
    502 uvm_map_init(void)
    503 {
    504 	static struct vm_map_entry kernel_map_entry[MAX_KMAPENT];
    505 #if defined(UVMHIST)
    506 	static struct uvm_history_ent maphistbuf[100];
    507 	static struct uvm_history_ent pdhistbuf[100];
    508 #endif
    509 	int lcv;
    510 
    511 	/*
    512 	 * first, init logging system.
    513 	 */
    514 
    515 	UVMHIST_FUNC("uvm_map_init");
    516 	UVMHIST_INIT_STATIC(maphist, maphistbuf);
    517 	UVMHIST_INIT_STATIC(pdhist, pdhistbuf);
    518 	UVMHIST_CALLED(maphist);
    519 	UVMHIST_LOG(maphist,"<starting uvm map system>", 0, 0, 0, 0);
    520 	UVMCNT_INIT(uvm_map_call, UVMCNT_CNT, 0,
    521 	    "# uvm_map() successful calls", 0);
    522 
    523 	UVMCNT_INIT(map_ubackmerge, UVMCNT_CNT, 0,
    524 	    "# uvm_map() back umerges", 0);
    525 	UVMCNT_INIT(map_uforwmerge, UVMCNT_CNT, 0,
    526 	    "# uvm_map() forward umerges", 0);
    527 	UVMCNT_INIT(map_ubimerge, UVMCNT_CNT, 0,
    528 	    "# uvm_map() dual umerge", 0);
    529 	UVMCNT_INIT(map_unomerge, UVMCNT_CNT, 0,
    530 	    "# uvm_map() no umerge", 0);
    531 
    532 	UVMCNT_INIT(map_kbackmerge, UVMCNT_CNT, 0,
    533 	    "# uvm_map() back kmerges", 0);
    534 	UVMCNT_INIT(map_kforwmerge, UVMCNT_CNT, 0,
    535 	    "# uvm_map() forward kmerges", 0);
    536 	UVMCNT_INIT(map_kbimerge, UVMCNT_CNT, 0,
    537 	    "# uvm_map() dual kmerge", 0);
    538 	UVMCNT_INIT(map_knomerge, UVMCNT_CNT, 0,
    539 	    "# uvm_map() no kmerge", 0);
    540 
    541 	UVMCNT_INIT(uvm_mlk_call, UVMCNT_CNT, 0, "# map lookup calls", 0);
    542 	UVMCNT_INIT(uvm_mlk_hint, UVMCNT_CNT, 0, "# map lookup hint hits", 0);
    543 
    544 	/*
    545 	 * now set up static pool of kernel map entrys ...
    546 	 */
    547 
    548 	simple_lock_init(&uvm.kentry_lock);
    549 	uvm.kentry_free = NULL;
    550 	for (lcv = 0 ; lcv < MAX_KMAPENT ; lcv++) {
    551 		kernel_map_entry[lcv].next = uvm.kentry_free;
    552 		uvm.kentry_free = &kernel_map_entry[lcv];
    553 	}
    554 
    555 	/*
    556 	 * initialize the map-related pools.
    557 	 */
    558 	pool_init(&uvm_vmspace_pool, sizeof(struct vmspace),
    559 	    0, 0, 0, "vmsppl", &pool_allocator_nointr);
    560 	pool_init(&uvm_map_entry_pool, sizeof(struct vm_map_entry),
    561 	    0, 0, 0, "vmmpepl", &pool_allocator_nointr);
    562 	pool_init(&uvm_map_entry_kmem_pool, sizeof(struct vm_map_entry),
    563 	    0, 0, 0, "vmmpekpl", NULL);
    564 }
    565 
    566 /*
    567  * clippers
    568  */
    569 
    570 /*
    571  * uvm_map_clip_start: ensure that the entry begins at or after
    572  *	the starting address, if it doesn't we split the entry.
    573  *
    574  * => caller should use UVM_MAP_CLIP_START macro rather than calling
    575  *    this directly
    576  * => map must be locked by caller
    577  */
    578 
    579 void
    580 uvm_map_clip_start(struct vm_map *map, struct vm_map_entry *entry,
    581     vaddr_t start)
    582 {
    583 	struct vm_map_entry *new_entry;
    584 	vaddr_t new_adj;
    585 
    586 	/* uvm_map_simplify_entry(map, entry); */ /* XXX */
    587 
    588 	uvm_tree_sanity(map, "clip_start entry");
    589 
    590 	/*
    591 	 * Split off the front portion.  note that we must insert the new
    592 	 * entry BEFORE this one, so that this entry has the specified
    593 	 * starting address.
    594 	 */
    595 
    596 	new_entry = uvm_mapent_alloc(map, 0);
    597 	uvm_mapent_copy(entry, new_entry); /* entry -> new_entry */
    598 
    599 	new_entry->end = start;
    600 	new_adj = start - new_entry->start;
    601 	if (entry->object.uvm_obj)
    602 		entry->offset += new_adj;	/* shift start over */
    603 
    604 	/* Does not change order for the RB tree */
    605 	entry->start = start;
    606 
    607 	if (new_entry->aref.ar_amap) {
    608 		amap_splitref(&new_entry->aref, &entry->aref, new_adj);
    609 	}
    610 
    611 	uvm_map_entry_link(map, entry->prev, new_entry);
    612 
    613 	if (UVM_ET_ISSUBMAP(entry)) {
    614 		/* ... unlikely to happen, but play it safe */
    615 		 uvm_map_reference(new_entry->object.sub_map);
    616 	} else {
    617 		if (UVM_ET_ISOBJ(entry) &&
    618 		    entry->object.uvm_obj->pgops &&
    619 		    entry->object.uvm_obj->pgops->pgo_reference)
    620 			entry->object.uvm_obj->pgops->pgo_reference(
    621 			    entry->object.uvm_obj);
    622 	}
    623 
    624 	uvm_tree_sanity(map, "clip_start leave");
    625 }
    626 
    627 /*
    628  * uvm_map_clip_end: ensure that the entry ends at or before
    629  *	the ending address, if it does't we split the reference
    630  *
    631  * => caller should use UVM_MAP_CLIP_END macro rather than calling
    632  *    this directly
    633  * => map must be locked by caller
    634  */
    635 
    636 void
    637 uvm_map_clip_end(struct vm_map *map, struct vm_map_entry *entry, vaddr_t end)
    638 {
    639 	struct vm_map_entry *	new_entry;
    640 	vaddr_t new_adj; /* #bytes we move start forward */
    641 
    642 	uvm_tree_sanity(map, "clip_end entry");
    643 	/*
    644 	 *	Create a new entry and insert it
    645 	 *	AFTER the specified entry
    646 	 */
    647 
    648 	new_entry = uvm_mapent_alloc(map, 0);
    649 	uvm_mapent_copy(entry, new_entry); /* entry -> new_entry */
    650 
    651 	new_entry->start = entry->end = end;
    652 	new_adj = end - entry->start;
    653 	if (new_entry->object.uvm_obj)
    654 		new_entry->offset += new_adj;
    655 
    656 	if (entry->aref.ar_amap)
    657 		amap_splitref(&entry->aref, &new_entry->aref, new_adj);
    658 
    659 	uvm_rb_fixup(map, entry);
    660 
    661 	uvm_map_entry_link(map, entry, new_entry);
    662 
    663 	if (UVM_ET_ISSUBMAP(entry)) {
    664 		/* ... unlikely to happen, but play it safe */
    665 		uvm_map_reference(new_entry->object.sub_map);
    666 	} else {
    667 		if (UVM_ET_ISOBJ(entry) &&
    668 		    entry->object.uvm_obj->pgops &&
    669 		    entry->object.uvm_obj->pgops->pgo_reference)
    670 			entry->object.uvm_obj->pgops->pgo_reference(
    671 			    entry->object.uvm_obj);
    672 	}
    673 
    674 	uvm_tree_sanity(map, "clip_end leave");
    675 }
    676 
    677 
    678 /*
    679  *   M A P   -   m a i n   e n t r y   p o i n t
    680  */
    681 /*
    682  * uvm_map: establish a valid mapping in a map
    683  *
    684  * => assume startp is page aligned.
    685  * => assume size is a multiple of PAGE_SIZE.
    686  * => assume sys_mmap provides enough of a "hint" to have us skip
    687  *	over text/data/bss area.
    688  * => map must be unlocked (we will lock it)
    689  * => <uobj,uoffset> value meanings (4 cases):
    690  *	 [1] <NULL,uoffset>		== uoffset is a hint for PMAP_PREFER
    691  *	 [2] <NULL,UVM_UNKNOWN_OFFSET>	== don't PMAP_PREFER
    692  *	 [3] <uobj,uoffset>		== normal mapping
    693  *	 [4] <uobj,UVM_UNKNOWN_OFFSET>	== uvm_map finds offset based on VA
    694  *
    695  *    case [4] is for kernel mappings where we don't know the offset until
    696  *    we've found a virtual address.   note that kernel object offsets are
    697  *    always relative to vm_map_min(kernel_map).
    698  *
    699  * => if `align' is non-zero, we try to align the virtual address to
    700  *	the specified alignment.  this is only a hint; if we can't
    701  *	do it, the address will be unaligned.  this is provided as
    702  *	a mechanism for large pages.
    703  *
    704  * => XXXCDC: need way to map in external amap?
    705  */
    706 
    707 int
    708 uvm_map(struct vm_map *map, vaddr_t *startp /* IN/OUT */, vsize_t size,
    709     struct uvm_object *uobj, voff_t uoffset, vsize_t align, uvm_flag_t flags)
    710 {
    711 	struct vm_map_entry *prev_entry, *new_entry;
    712 	const int amapwaitflag = (flags & UVM_FLAG_NOWAIT) ?
    713 	    AMAP_EXTEND_NOWAIT : 0;
    714 	vm_prot_t prot = UVM_PROTECTION(flags), maxprot =
    715 	    UVM_MAXPROTECTION(flags);
    716 	vm_inherit_t inherit = UVM_INHERIT(flags);
    717 	int advice = UVM_ADVICE(flags);
    718 	int error, merged = 0, kmap = (vm_map_pmap(map) == pmap_kernel());
    719 	UVMHIST_FUNC("uvm_map");
    720 	UVMHIST_CALLED(maphist);
    721 
    722 	UVMHIST_LOG(maphist, "(map=0x%x, *startp=0x%x, size=%d, flags=0x%x)",
    723 	    map, *startp, size, flags);
    724 	UVMHIST_LOG(maphist, "  uobj/offset 0x%x/%d", uobj, uoffset,0,0);
    725 
    726 	/*
    727 	 * detect a popular device driver bug.
    728 	 */
    729 
    730 	KASSERT(doing_shutdown || curlwp != NULL ||
    731 	    (map->flags & VM_MAP_INTRSAFE));
    732 
    733 	/*
    734 	 * zero-sized mapping doesn't make any sense.
    735 	 */
    736 	KASSERT(size > 0);
    737 
    738 	uvm_tree_sanity(map, "map entry");
    739 
    740 	/*
    741 	 * check sanity of protection code
    742 	 */
    743 
    744 	if ((prot & maxprot) != prot) {
    745 		UVMHIST_LOG(maphist, "<- prot. failure:  prot=0x%x, max=0x%x",
    746 		prot, maxprot,0,0);
    747 		return EACCES;
    748 	}
    749 
    750 	/*
    751 	 * for pager_map, allocate the new entry first to avoid sleeping
    752 	 * for memory while we have the map locked.
    753 	 */
    754 
    755 	new_entry = NULL;
    756 	if (map == pager_map) {
    757 		new_entry = uvm_mapent_alloc(map, (flags & UVM_FLAG_NOWAIT));
    758 		if (__predict_false(new_entry == NULL))
    759 			return ENOMEM;
    760 	}
    761 
    762 	/*
    763 	 * figure out where to put new VM range
    764 	 */
    765 
    766 	if (vm_map_lock_try(map) == FALSE) {
    767 		if (flags & UVM_FLAG_TRYLOCK) {
    768 			if (new_entry) {
    769 				uvm_mapent_free(new_entry);
    770 			}
    771 			return EAGAIN;
    772 		}
    773 		vm_map_lock(map); /* could sleep here */
    774 	}
    775 	if ((prev_entry = uvm_map_findspace(map, *startp, size, startp,
    776 	    uobj, uoffset, align, flags)) == NULL) {
    777 		UVMHIST_LOG(maphist,"<- uvm_map_findspace failed!",0,0,0,0);
    778 		vm_map_unlock(map);
    779 		if (new_entry) {
    780 			uvm_mapent_free(new_entry);
    781 		}
    782 		return ENOMEM;
    783 	}
    784 
    785 #ifdef PMAP_GROWKERNEL
    786 	{
    787 		/*
    788 		 * If the kernel pmap can't map the requested space,
    789 		 * then allocate more resources for it.
    790 		 */
    791 		if (map == kernel_map && uvm_maxkaddr < (*startp + size))
    792 			uvm_maxkaddr = pmap_growkernel(*startp + size);
    793 	}
    794 #endif
    795 
    796 	UVMCNT_INCR(uvm_map_call);
    797 
    798 	/*
    799 	 * if uobj is null, then uoffset is either a VAC hint for PMAP_PREFER
    800 	 * [typically from uvm_map_reserve] or it is UVM_UNKNOWN_OFFSET.   in
    801 	 * either case we want to zero it  before storing it in the map entry
    802 	 * (because it looks strange and confusing when debugging...)
    803 	 *
    804 	 * if uobj is not null
    805 	 *   if uoffset is not UVM_UNKNOWN_OFFSET then we have a normal mapping
    806 	 *      and we do not need to change uoffset.
    807 	 *   if uoffset is UVM_UNKNOWN_OFFSET then we need to find the offset
    808 	 *      now (based on the starting address of the map).   this case is
    809 	 *      for kernel object mappings where we don't know the offset until
    810 	 *      the virtual address is found (with uvm_map_findspace).   the
    811 	 *      offset is the distance we are from the start of the map.
    812 	 */
    813 
    814 	if (uobj == NULL) {
    815 		uoffset = 0;
    816 	} else {
    817 		if (uoffset == UVM_UNKNOWN_OFFSET) {
    818 			KASSERT(UVM_OBJ_IS_KERN_OBJECT(uobj));
    819 			uoffset = *startp - vm_map_min(kernel_map);
    820 		}
    821 	}
    822 
    823 	/*
    824 	 * try and insert in map by extending previous entry, if possible.
    825 	 * XXX: we don't try and pull back the next entry.   might be useful
    826 	 * for a stack, but we are currently allocating our stack in advance.
    827 	 */
    828 
    829 	if (flags & UVM_FLAG_NOMERGE)
    830 		goto nomerge;
    831 
    832 	if (prev_entry->end == *startp &&
    833 	    prev_entry != &map->header &&
    834 	    prev_entry->object.uvm_obj == uobj) {
    835 
    836 		if (uobj && prev_entry->offset +
    837 		    (prev_entry->end - prev_entry->start) != uoffset)
    838 			goto forwardmerge;
    839 
    840 		if (UVM_ET_ISSUBMAP(prev_entry))
    841 			goto forwardmerge;
    842 
    843 		if (prev_entry->protection != prot ||
    844 		    prev_entry->max_protection != maxprot)
    845 			goto forwardmerge;
    846 
    847 		if (prev_entry->inheritance != inherit ||
    848 		    prev_entry->advice != advice)
    849 			goto forwardmerge;
    850 
    851 		/* wiring status must match (new area is unwired) */
    852 		if (VM_MAPENT_ISWIRED(prev_entry))
    853 			goto forwardmerge;
    854 
    855 		/*
    856 		 * can't extend a shared amap.  note: no need to lock amap to
    857 		 * look at refs since we don't care about its exact value.
    858 		 * if it is one (i.e. we have only reference) it will stay there
    859 		 */
    860 
    861 		if (prev_entry->aref.ar_amap &&
    862 		    amap_refs(prev_entry->aref.ar_amap) != 1) {
    863 			goto forwardmerge;
    864 		}
    865 
    866 		if (prev_entry->aref.ar_amap) {
    867 			error = amap_extend(prev_entry, size,
    868 			    amapwaitflag | AMAP_EXTEND_FORWARDS);
    869 			if (error) {
    870 				vm_map_unlock(map);
    871 				if (new_entry) {
    872 					uvm_mapent_free(new_entry);
    873 				}
    874 				return error;
    875 			}
    876 		}
    877 
    878 		if (kmap)
    879 			UVMCNT_INCR(map_kbackmerge);
    880 		else
    881 			UVMCNT_INCR(map_ubackmerge);
    882 		UVMHIST_LOG(maphist,"  starting back merge", 0, 0, 0, 0);
    883 
    884 		/*
    885 		 * drop our reference to uobj since we are extending a reference
    886 		 * that we already have (the ref count can not drop to zero).
    887 		 */
    888 
    889 		if (uobj && uobj->pgops->pgo_detach)
    890 			uobj->pgops->pgo_detach(uobj);
    891 
    892 		prev_entry->end += size;
    893 		uvm_rb_fixup(map, prev_entry);
    894 
    895 		uvm_tree_sanity(map, "map backmerged");
    896 
    897 		UVMHIST_LOG(maphist,"<- done (via backmerge)!", 0, 0, 0, 0);
    898 		if (new_entry) {
    899 			uvm_mapent_free(new_entry);
    900 			new_entry = NULL;
    901 		}
    902 		merged++;
    903 	}
    904 
    905 forwardmerge:
    906 	if (prev_entry->next->start == (*startp + size) &&
    907 	    prev_entry->next != &map->header &&
    908 	    prev_entry->next->object.uvm_obj == uobj) {
    909 
    910 		if (uobj && prev_entry->next->offset != uoffset + size)
    911 			goto nomerge;
    912 
    913 		if (UVM_ET_ISSUBMAP(prev_entry->next))
    914 			goto nomerge;
    915 
    916 		if (prev_entry->next->protection != prot ||
    917 		    prev_entry->next->max_protection != maxprot)
    918 			goto nomerge;
    919 
    920 		if (prev_entry->next->inheritance != inherit ||
    921 		    prev_entry->next->advice != advice)
    922 			goto nomerge;
    923 
    924 		/* wiring status must match (new area is unwired) */
    925 		if (VM_MAPENT_ISWIRED(prev_entry->next))
    926 			goto nomerge;
    927 
    928 		/*
    929 		 * can't extend a shared amap.  note: no need to lock amap to
    930 		 * look at refs since we don't care about its exact value.
    931 		 * if it is one (i.e. we have only reference) it will stay there.
    932 		 *
    933 		 * note that we also can't merge two amaps, so if we
    934 		 * merged with the previous entry which has an amap,
    935 		 * and the next entry also has an amap, we give up.
    936 		 *
    937 		 * Interesting cases:
    938 		 * amap, new, amap -> give up second merge (single fwd extend)
    939 		 * amap, new, none -> double forward extend (extend again here)
    940 		 * none, new, amap -> double backward extend (done here)
    941 		 * uobj, new, amap -> single backward extend (done here)
    942 		 *
    943 		 * XXX should we attempt to deal with someone refilling
    944 		 * the deallocated region between two entries that are
    945 		 * backed by the same amap (ie, arefs is 2, "prev" and
    946 		 * "next" refer to it, and adding this allocation will
    947 		 * close the hole, thus restoring arefs to 1 and
    948 		 * deallocating the "next" vm_map_entry)?  -- @@@
    949 		 */
    950 
    951 		if (prev_entry->next->aref.ar_amap &&
    952 		    (amap_refs(prev_entry->next->aref.ar_amap) != 1 ||
    953 		     (merged && prev_entry->aref.ar_amap))) {
    954 			goto nomerge;
    955 		}
    956 
    957 		if (merged) {
    958 			/*
    959 			 * Try to extend the amap of the previous entry to
    960 			 * cover the next entry as well.  If it doesn't work
    961 			 * just skip on, don't actually give up, since we've
    962 			 * already completed the back merge.
    963 			 */
    964 			if (prev_entry->aref.ar_amap) {
    965 				if (amap_extend(prev_entry,
    966 				    prev_entry->next->end -
    967 				    prev_entry->next->start,
    968 				    amapwaitflag | AMAP_EXTEND_FORWARDS))
    969 					goto nomerge;
    970 			}
    971 
    972 			/*
    973 			 * Try to extend the amap of the *next* entry
    974 			 * back to cover the new allocation *and* the
    975 			 * previous entry as well (the previous merge
    976 			 * didn't have an amap already otherwise we
    977 			 * wouldn't be checking here for an amap).  If
    978 			 * it doesn't work just skip on, again, don't
    979 			 * actually give up, since we've already
    980 			 * completed the back merge.
    981 			 */
    982 			else if (prev_entry->next->aref.ar_amap) {
    983 				if (amap_extend(prev_entry->next,
    984 				    prev_entry->end -
    985 				    prev_entry->start,
    986 				    amapwaitflag | AMAP_EXTEND_BACKWARDS))
    987 					goto nomerge;
    988 			}
    989 		} else {
    990 			/*
    991 			 * Pull the next entry's amap backwards to cover this
    992 			 * new allocation.
    993 			 */
    994 			if (prev_entry->next->aref.ar_amap) {
    995 				error = amap_extend(prev_entry->next, size,
    996 				    amapwaitflag | AMAP_EXTEND_BACKWARDS);
    997 				if (error) {
    998 					vm_map_unlock(map);
    999 					if (new_entry) {
   1000 						uvm_mapent_free(new_entry);
   1001 					}
   1002 					return error;
   1003 				}
   1004 			}
   1005 		}
   1006 
   1007 		if (merged) {
   1008 			if (kmap) {
   1009 				UVMCNT_DECR(map_kbackmerge);
   1010 				UVMCNT_INCR(map_kbimerge);
   1011 			} else {
   1012 				UVMCNT_DECR(map_ubackmerge);
   1013 				UVMCNT_INCR(map_ubimerge);
   1014 			}
   1015 		} else {
   1016 			if (kmap)
   1017 				UVMCNT_INCR(map_kforwmerge);
   1018 			else
   1019 				UVMCNT_INCR(map_uforwmerge);
   1020 		}
   1021 		UVMHIST_LOG(maphist,"  starting forward merge", 0, 0, 0, 0);
   1022 
   1023 		/*
   1024 		 * drop our reference to uobj since we are extending a reference
   1025 		 * that we already have (the ref count can not drop to zero).
   1026 		 * (if merged, we've already detached)
   1027 		 */
   1028 		if (uobj && uobj->pgops->pgo_detach && !merged)
   1029 			uobj->pgops->pgo_detach(uobj);
   1030 
   1031 		if (merged) {
   1032 			struct vm_map_entry *dead = prev_entry->next;
   1033 			prev_entry->end = dead->end;
   1034 			uvm_map_entry_unlink(map, dead);
   1035 			if (dead->aref.ar_amap != NULL) {
   1036 				prev_entry->aref = dead->aref;
   1037 				dead->aref.ar_amap = NULL;
   1038 			}
   1039 			uvm_mapent_free(dead);
   1040 		} else {
   1041 			prev_entry->next->start -= size;
   1042 			if (prev_entry != &map->header)
   1043 				uvm_rb_fixup(map, prev_entry);
   1044 			if (uobj)
   1045 				prev_entry->next->offset = uoffset;
   1046 		}
   1047 
   1048 		uvm_tree_sanity(map, "map forwardmerged");
   1049 
   1050 		UVMHIST_LOG(maphist,"<- done forwardmerge", 0, 0, 0, 0);
   1051 		if (new_entry) {
   1052 			uvm_mapent_free(new_entry);
   1053 			new_entry = NULL;
   1054 		}
   1055 		merged++;
   1056 	}
   1057 
   1058 nomerge:
   1059 	if (!merged) {
   1060 		UVMHIST_LOG(maphist,"  allocating new map entry", 0, 0, 0, 0);
   1061 		if (kmap)
   1062 			UVMCNT_INCR(map_knomerge);
   1063 		else
   1064 			UVMCNT_INCR(map_unomerge);
   1065 
   1066 		/*
   1067 		 * allocate new entry and link it in.
   1068 		 */
   1069 
   1070 		if (new_entry == NULL) {
   1071 			new_entry = uvm_mapent_alloc(map,
   1072 				(flags & UVM_FLAG_NOWAIT));
   1073 			if (__predict_false(new_entry == NULL)) {
   1074 				vm_map_unlock(map);
   1075 				return ENOMEM;
   1076 			}
   1077 		}
   1078 		new_entry->start = *startp;
   1079 		new_entry->end = new_entry->start + size;
   1080 		new_entry->object.uvm_obj = uobj;
   1081 		new_entry->offset = uoffset;
   1082 
   1083 		if (uobj)
   1084 			new_entry->etype = UVM_ET_OBJ;
   1085 		else
   1086 			new_entry->etype = 0;
   1087 
   1088 		if (flags & UVM_FLAG_COPYONW) {
   1089 			new_entry->etype |= UVM_ET_COPYONWRITE;
   1090 			if ((flags & UVM_FLAG_OVERLAY) == 0)
   1091 				new_entry->etype |= UVM_ET_NEEDSCOPY;
   1092 		}
   1093 
   1094 		new_entry->protection = prot;
   1095 		new_entry->max_protection = maxprot;
   1096 		new_entry->inheritance = inherit;
   1097 		new_entry->wired_count = 0;
   1098 		new_entry->advice = advice;
   1099 		if (flags & UVM_FLAG_OVERLAY) {
   1100 
   1101 			/*
   1102 			 * to_add: for BSS we overallocate a little since we
   1103 			 * are likely to extend
   1104 			 */
   1105 
   1106 			vaddr_t to_add = (flags & UVM_FLAG_AMAPPAD) ?
   1107 				UVM_AMAP_CHUNK << PAGE_SHIFT : 0;
   1108 			struct vm_amap *amap = amap_alloc(size, to_add,
   1109 			    (flags & UVM_FLAG_NOWAIT) ? M_NOWAIT : M_WAITOK);
   1110 			if (__predict_false(amap == NULL)) {
   1111 				vm_map_unlock(map);
   1112 				uvm_mapent_free(new_entry);
   1113 				return ENOMEM;
   1114 			}
   1115 			new_entry->aref.ar_pageoff = 0;
   1116 			new_entry->aref.ar_amap = amap;
   1117 		} else {
   1118 			new_entry->aref.ar_pageoff = 0;
   1119 			new_entry->aref.ar_amap = NULL;
   1120 		}
   1121 		uvm_map_entry_link(map, prev_entry, new_entry);
   1122 
   1123 		/*
   1124 		 * Update the free space hint
   1125 		 */
   1126 
   1127 		if ((map->first_free == prev_entry) &&
   1128 		    (prev_entry->end >= new_entry->start))
   1129 			map->first_free = new_entry;
   1130 	}
   1131 
   1132 	map->size += size;
   1133 
   1134 	UVMHIST_LOG(maphist,"<- done!", 0, 0, 0, 0);
   1135 	vm_map_unlock(map);
   1136 	return 0;
   1137 }
   1138 
   1139 /*
   1140  * uvm_map_lookup_entry: find map entry at or before an address
   1141  *
   1142  * => map must at least be read-locked by caller
   1143  * => entry is returned in "entry"
   1144  * => return value is true if address is in the returned entry
   1145  */
   1146 
   1147 boolean_t
   1148 uvm_map_lookup_entry(struct vm_map *map, vaddr_t address,
   1149     struct vm_map_entry **entry	/* OUT */)
   1150 {
   1151 	struct vm_map_entry *cur;
   1152 	boolean_t use_tree = FALSE;
   1153 	UVMHIST_FUNC("uvm_map_lookup_entry");
   1154 	UVMHIST_CALLED(maphist);
   1155 
   1156 	UVMHIST_LOG(maphist,"(map=0x%x,addr=0x%x,ent=0x%x)",
   1157 	    map, address, entry, 0);
   1158 
   1159 	/*
   1160 	 * start looking either from the head of the
   1161 	 * list, or from the hint.
   1162 	 */
   1163 
   1164 	simple_lock(&map->hint_lock);
   1165 	cur = map->hint;
   1166 	simple_unlock(&map->hint_lock);
   1167 
   1168 	if (cur == &map->header)
   1169 		cur = cur->next;
   1170 
   1171 	UVMCNT_INCR(uvm_mlk_call);
   1172 	if (address >= cur->start) {
   1173 
   1174 		/*
   1175 		 * go from hint to end of list.
   1176 		 *
   1177 		 * but first, make a quick check to see if
   1178 		 * we are already looking at the entry we
   1179 		 * want (which is usually the case).
   1180 		 * note also that we don't need to save the hint
   1181 		 * here... it is the same hint (unless we are
   1182 		 * at the header, in which case the hint didn't
   1183 		 * buy us anything anyway).
   1184 		 */
   1185 
   1186 		if (cur != &map->header && cur->end > address) {
   1187 			UVMCNT_INCR(uvm_mlk_hint);
   1188 			*entry = cur;
   1189 			UVMHIST_LOG(maphist,"<- got it via hint (0x%x)",
   1190 			    cur, 0, 0, 0);
   1191 			return (TRUE);
   1192 		}
   1193 
   1194 		if (map->nentries > 30)
   1195 			use_tree = TRUE;
   1196 	} else {
   1197 
   1198 		/*
   1199 		 * invalid hint.  use tree.
   1200 		 */
   1201 		use_tree = TRUE;
   1202 	}
   1203 
   1204 	uvm_tree_sanity(map, __func__);
   1205 
   1206 	if (use_tree) {
   1207 		struct vm_map_entry *prev = &map->header;
   1208 		cur = RB_ROOT(&map->rbhead);
   1209 
   1210 		/*
   1211 		 * Simple lookup in the tree.  Happens when the hint is
   1212 		 * invalid, or nentries reach a threshold.
   1213 		 */
   1214 		while (cur) {
   1215 			if (address >= cur->start) {
   1216 				if (address < cur->end) {
   1217 					*entry = cur;
   1218 					goto got;
   1219 				}
   1220 				prev = cur;
   1221 				cur = RB_RIGHT(cur, rb_entry);
   1222 			} else
   1223 				cur = RB_LEFT(cur, rb_entry);
   1224 		}
   1225 		*entry = prev;
   1226 		goto failed;
   1227 	}
   1228 
   1229 	/*
   1230 	 * search linearly
   1231 	 */
   1232 
   1233 	while (cur != &map->header) {
   1234 		if (cur->end > address) {
   1235 			if (address >= cur->start) {
   1236 				/*
   1237 				 * save this lookup for future
   1238 				 * hints, and return
   1239 				 */
   1240 
   1241 				*entry = cur;
   1242 got:
   1243 				SAVE_HINT(map, map->hint, *entry);
   1244 				UVMHIST_LOG(maphist,"<- search got it (0x%x)",
   1245 					cur, 0, 0, 0);
   1246 				KDASSERT((*entry)->start <= address);
   1247 				KDASSERT(address < (*entry)->end);
   1248 				return (TRUE);
   1249 			}
   1250 			break;
   1251 		}
   1252 		cur = cur->next;
   1253 	}
   1254 	*entry = cur->prev;
   1255 failed:
   1256 	SAVE_HINT(map, map->hint, *entry);
   1257 	UVMHIST_LOG(maphist,"<- failed!",0,0,0,0);
   1258 	KDASSERT((*entry) == &map->header || (*entry)->end <= address);
   1259 	KDASSERT((*entry)->next == &map->header ||
   1260 	    address < (*entry)->next->start);
   1261 	return (FALSE);
   1262 }
   1263 
   1264 /*
   1265  * See if the range between start and start + length fits in the gap
   1266  * entry->next->start and entry->end.  Returns 1 if fits, 0 if doesn't
   1267  * fit, and -1 address wraps around.
   1268  */
   1269 static __inline int
   1270 uvm_map_space_avail(vaddr_t *start, vsize_t length, voff_t uoffset,
   1271     vsize_t align, int topdown, struct vm_map_entry *entry)
   1272 {
   1273 	vaddr_t end;
   1274 
   1275 #ifdef PMAP_PREFER
   1276 	/*
   1277 	 * push start address forward as needed to avoid VAC alias problems.
   1278 	 * we only do this if a valid offset is specified.
   1279 	 */
   1280 
   1281 	if (uoffset != UVM_UNKNOWN_OFFSET)
   1282 		PMAP_PREFER(uoffset, start);
   1283 #endif
   1284 	if (align != 0) {
   1285 		if ((*start & (align - 1)) != 0) {
   1286 			if (topdown)
   1287 				*start &= ~(align - 1);
   1288 			else
   1289 				*start = roundup(*start, align);
   1290 		}
   1291 		/*
   1292 		 * XXX Should we PMAP_PREFER() here again?
   1293 		 */
   1294 	}
   1295 
   1296 	/*
   1297 	 * Find the end of the proposed new region.  Be sure we didn't
   1298 	 * wrap around the address; if so, we lose.  Otherwise, if the
   1299 	 * proposed new region fits before the next entry, we win.
   1300 	 */
   1301 
   1302 	end = *start + length;
   1303 	if (end < *start)
   1304 		return (-1);
   1305 
   1306 	if (entry->next->start >= end && *start >= entry->end)
   1307 		return (1);
   1308 
   1309 	return (0);
   1310 }
   1311 
   1312 /*
   1313  * uvm_map_findspace: find "length" sized space in "map".
   1314  *
   1315  * => "hint" is a hint about where we want it, unless FINDSPACE_FIXED is
   1316  *	set (in which case we insist on using "hint").
   1317  * => "result" is VA returned
   1318  * => uobj/uoffset are to be used to handle VAC alignment, if required
   1319  * => if `align' is non-zero, we attempt to align to that value.
   1320  * => caller must at least have read-locked map
   1321  * => returns NULL on failure, or pointer to prev. map entry if success
   1322  * => note this is a cross between the old vm_map_findspace and vm_map_find
   1323  */
   1324 
   1325 struct vm_map_entry *
   1326 uvm_map_findspace(struct vm_map *map, vaddr_t hint, vsize_t length,
   1327     vaddr_t *result /* OUT */, struct uvm_object *uobj, voff_t uoffset,
   1328     vsize_t align, int flags)
   1329 {
   1330 	struct vm_map_entry *entry;
   1331 	struct vm_map_entry *child, *prev, *tmp;
   1332 	vaddr_t orig_hint;
   1333 	const int topdown = map->flags & VM_MAP_TOPDOWN;
   1334 	UVMHIST_FUNC("uvm_map_findspace");
   1335 	UVMHIST_CALLED(maphist);
   1336 
   1337 	UVMHIST_LOG(maphist, "(map=0x%x, hint=0x%x, len=%d, flags=0x%x)",
   1338 	    map, hint, length, flags);
   1339 	KASSERT((align & (align - 1)) == 0);
   1340 	KASSERT((flags & UVM_FLAG_FIXED) == 0 || align == 0);
   1341 
   1342 	uvm_tree_sanity(map, "map_findspace entry");
   1343 
   1344 	/*
   1345 	 * remember the original hint.  if we are aligning, then we
   1346 	 * may have to try again with no alignment constraint if
   1347 	 * we fail the first time.
   1348 	 */
   1349 
   1350 	orig_hint = hint;
   1351 	if (hint < map->min_offset) {	/* check ranges ... */
   1352 		if (flags & UVM_FLAG_FIXED) {
   1353 			UVMHIST_LOG(maphist,"<- VA below map range",0,0,0,0);
   1354 			return (NULL);
   1355 		}
   1356 		hint = map->min_offset;
   1357 	}
   1358 	if (hint > map->max_offset) {
   1359 		UVMHIST_LOG(maphist,"<- VA 0x%x > range [0x%x->0x%x]",
   1360 		    hint, map->min_offset, map->max_offset, 0);
   1361 		return (NULL);
   1362 	}
   1363 
   1364 	/*
   1365 	 * Look for the first possible address; if there's already
   1366 	 * something at this address, we have to start after it.
   1367 	 */
   1368 
   1369 	/*
   1370 	 * @@@: there are four, no, eight cases to consider.
   1371 	 *
   1372 	 * 0: found,     fixed,     bottom up -> fail
   1373 	 * 1: found,     fixed,     top down  -> fail
   1374 	 * 2: found,     not fixed, bottom up -> start after entry->end,
   1375 	 *                                       loop up
   1376 	 * 3: found,     not fixed, top down  -> start before entry->start,
   1377 	 *                                       loop down
   1378 	 * 4: not found, fixed,     bottom up -> check entry->next->start, fail
   1379 	 * 5: not found, fixed,     top down  -> check entry->next->start, fail
   1380 	 * 6: not found, not fixed, bottom up -> check entry->next->start,
   1381 	 *                                       loop up
   1382 	 * 7: not found, not fixed, top down  -> check entry->next->start,
   1383 	 *                                       loop down
   1384 	 *
   1385 	 * as you can see, it reduces to roughly five cases, and that
   1386 	 * adding top down mapping only adds one unique case (without
   1387 	 * it, there would be four cases).
   1388 	 */
   1389 
   1390 	if ((flags & UVM_FLAG_FIXED) == 0 && hint == map->min_offset) {
   1391 		entry = map->first_free;
   1392 	} else {
   1393 		if (uvm_map_lookup_entry(map, hint, &entry)) {
   1394 			/* "hint" address already in use ... */
   1395 			if (flags & UVM_FLAG_FIXED) {
   1396 				UVMHIST_LOG(maphist, "<- fixed & VA in use",
   1397 				    0, 0, 0, 0);
   1398 				return (NULL);
   1399 			}
   1400 			if (topdown)
   1401 				/* Start from lower gap. */
   1402 				entry = entry->prev;
   1403 		} else if (flags & UVM_FLAG_FIXED) {
   1404 			if (entry->next->start >= hint + length &&
   1405 			    hint + length > hint)
   1406 				goto found;
   1407 
   1408 			/* "hint" address is gap but too small */
   1409 			UVMHIST_LOG(maphist, "<- fixed mapping failed",
   1410 			    0, 0, 0, 0);
   1411 			return (NULL); /* only one shot at it ... */
   1412 		} else {
   1413 			/*
   1414 			 * See if given hint fits in this gap.
   1415 			 */
   1416 			switch (uvm_map_space_avail(&hint, length,
   1417 			    uoffset, align, topdown, entry)) {
   1418 			case 1:
   1419 				goto found;
   1420 			case -1:
   1421 				goto wraparound;
   1422 			}
   1423 
   1424 			if (topdown)
   1425 				/*
   1426 				 * Still there is a chance to fit
   1427 				 * if hint > entry->end.
   1428 				 */
   1429 				;
   1430 			else
   1431 				goto nextgap;
   1432 		}
   1433 	}
   1434 
   1435 	/*
   1436 	 * Note that all UVM_FLAGS_FIXED case is already handled.
   1437 	 */
   1438 	KDASSERT((flags & UVM_FLAG_FIXED) == 0);
   1439 
   1440 	/* Try to find the space in the red-black tree */
   1441 
   1442 	/* Check slot before any entry */
   1443 	hint = topdown ? entry->next->start - length : entry->end;
   1444 	switch (uvm_map_space_avail(&hint, length, uoffset, align,
   1445 	    topdown, entry)) {
   1446 	case 1:
   1447 		goto found;
   1448 	case -1:
   1449 		goto wraparound;
   1450 	}
   1451 
   1452 nextgap:
   1453 	/* If there is not enough space in the whole tree, we fail */
   1454 	tmp = RB_ROOT(&map->rbhead);
   1455 	if (tmp == NULL || tmp->space < length)
   1456 		goto notfound;
   1457 
   1458 	prev = NULL; /* previous candidate */
   1459 
   1460 	/* Find an entry close to hint that has enough space */
   1461 	for (; tmp;) {
   1462 		KASSERT(tmp->next->start == tmp->end + tmp->ownspace);
   1463 		if (topdown) {
   1464 			if (tmp->next->start < hint + length &&
   1465 			    (prev == NULL || tmp->end > prev->end)) {
   1466 				if (tmp->ownspace >= length)
   1467 					prev = tmp;
   1468 				else if ((child = RB_LEFT(tmp, rb_entry))
   1469 				    != NULL && child->space >= length)
   1470 					prev = tmp;
   1471 			}
   1472 		} else {
   1473 			if (tmp->end >= hint &&
   1474 			    (prev == NULL || tmp->end < prev->end)) {
   1475 				if (tmp->ownspace >= length)
   1476 					prev = tmp;
   1477 				else if ((child = RB_RIGHT(tmp, rb_entry))
   1478 				    != NULL && child->space >= length)
   1479 					prev = tmp;
   1480 			}
   1481 		}
   1482 		if (tmp->next->start < hint + length)
   1483 			child = RB_RIGHT(tmp, rb_entry);
   1484 		else if (tmp->end > hint)
   1485 			child = RB_LEFT(tmp, rb_entry);
   1486 		else {
   1487 			if (tmp->ownspace >= length)
   1488 				break;
   1489 			if (topdown)
   1490 				child = RB_LEFT(tmp, rb_entry);
   1491 			else
   1492 				child = RB_RIGHT(tmp, rb_entry);
   1493 		}
   1494 		if (child == NULL || child->space < length)
   1495 			break;
   1496 		tmp = child;
   1497 	}
   1498 
   1499 	if (tmp != NULL && hint < tmp->end + tmp->ownspace) {
   1500 		/*
   1501 		 * Check if the entry that we found satifies the
   1502 		 * space requirement
   1503 		 */
   1504 		if (hint < tmp->end || hint < tmp->end + tmp->ownspace - length)
   1505 			hint = topdown ? tmp->next->start - length : tmp->end;
   1506 		if (uvm_map_space_avail(&hint, length, uoffset, align,
   1507 		    topdown, tmp) == 1) {
   1508 			entry = tmp;
   1509 			goto found;
   1510 		}
   1511 		if (tmp->ownspace >= length)
   1512 			goto listsearch;
   1513 	}
   1514 	if (prev == NULL)
   1515 		goto notfound;
   1516 
   1517 	hint = topdown ? prev->next->start - length : prev->end;
   1518 	if (uvm_map_space_avail(&hint, length, uoffset, align, topdown, prev)
   1519 	    == 1) {
   1520 		entry = prev;
   1521 		goto found;
   1522 	}
   1523 	if (prev->ownspace >= length)
   1524 		goto listsearch;
   1525 
   1526 	if (topdown)
   1527 		tmp = RB_LEFT(prev, rb_entry);
   1528 	else
   1529 		tmp = RB_RIGHT(prev, rb_entry);
   1530 	for (;;) {
   1531 		KASSERT(tmp && tmp->space >= length);
   1532 		if (topdown)
   1533 			child = RB_RIGHT(tmp, rb_entry);
   1534 		else
   1535 			child = RB_LEFT(tmp, rb_entry);
   1536 		if (child && child->space >= length) {
   1537 			tmp = child;
   1538 			continue;
   1539 		}
   1540 		if (tmp->ownspace >= length)
   1541 			break;
   1542 		if (topdown)
   1543 			tmp = RB_LEFT(tmp, rb_entry);
   1544 		else
   1545 			tmp = RB_RIGHT(tmp, rb_entry);
   1546 	}
   1547 
   1548 	hint = topdown ? tmp->next->start - length : tmp->end;
   1549 	switch (uvm_map_space_avail(&hint, length, uoffset, align,
   1550 	    topdown, tmp)) {
   1551 	case 1:
   1552 		entry = tmp;
   1553 		goto found;
   1554 	}
   1555 
   1556 	/*
   1557 	 * The tree fails to find an entry because of offset or alignment
   1558 	 * restrictions.  Search the list instead.
   1559 	 */
   1560  listsearch:
   1561 	/*
   1562 	 * Look through the rest of the map, trying to fit a new region in
   1563 	 * the gap between existing regions, or after the very last region.
   1564 	 * note: entry->end = base VA of current gap,
   1565 	 *	 entry->next->start = VA of end of current gap
   1566 	 */
   1567 
   1568 	for (;;) {
   1569 		/* Update hint for current gap. */
   1570 		hint = topdown ? entry->next->start - length : entry->end;
   1571 
   1572 		/* See if it fits. */
   1573 		switch (uvm_map_space_avail(&hint, length, uoffset, align,
   1574 		    topdown, entry)) {
   1575 		case 1:
   1576 			goto found;
   1577 		case -1:
   1578 			goto wraparound;
   1579 		}
   1580 
   1581 		/* Advance to next/previous gap */
   1582 		if (topdown) {
   1583 			if (entry == &map->header) {
   1584 				UVMHIST_LOG(maphist, "<- failed (off start)",
   1585 				    0,0,0,0);
   1586 				goto notfound;
   1587 			}
   1588 			entry = entry->prev;
   1589 		} else {
   1590 			entry = entry->next;
   1591 			if (entry == &map->header) {
   1592 				UVMHIST_LOG(maphist, "<- failed (off end)",
   1593 				    0,0,0,0);
   1594 				goto notfound;
   1595 			}
   1596 		}
   1597 	}
   1598 
   1599  found:
   1600 	SAVE_HINT(map, map->hint, entry);
   1601 	*result = hint;
   1602 	UVMHIST_LOG(maphist,"<- got it!  (result=0x%x)", hint, 0,0,0);
   1603 	KASSERT(entry->end <= hint);
   1604 	KASSERT(hint + length <= entry->next->start);
   1605 	return (entry);
   1606 
   1607  wraparound:
   1608 	UVMHIST_LOG(maphist, "<- failed (wrap around)", 0,0,0,0);
   1609 
   1610  notfound:
   1611 	if (align != 0) {
   1612 		UVMHIST_LOG(maphist, "calling recursively, no align",
   1613 		    0,0,0,0);
   1614 		return (uvm_map_findspace(map, orig_hint,
   1615 		    length, result, uobj, uoffset, 0, flags));
   1616 	}
   1617 	return (NULL);
   1618 }
   1619 
   1620 /*
   1621  *   U N M A P   -   m a i n   h e l p e r   f u n c t i o n s
   1622  */
   1623 
   1624 /*
   1625  * uvm_unmap_remove: remove mappings from a vm_map (from "start" up to "stop")
   1626  *
   1627  * => caller must check alignment and size
   1628  * => map must be locked by caller
   1629  * => we return a list of map entries that we've remove from the map
   1630  *    in "entry_list"
   1631  */
   1632 
   1633 void
   1634 uvm_unmap_remove(struct vm_map *map, vaddr_t start, vaddr_t end,
   1635     struct vm_map_entry **entry_list /* OUT */)
   1636 {
   1637 	struct vm_map_entry *entry, *first_entry, *next;
   1638 	vaddr_t len;
   1639 	UVMHIST_FUNC("uvm_unmap_remove"); UVMHIST_CALLED(maphist);
   1640 
   1641 	UVMHIST_LOG(maphist,"(map=0x%x, start=0x%x, end=0x%x)",
   1642 	    map, start, end, 0);
   1643 	VM_MAP_RANGE_CHECK(map, start, end);
   1644 
   1645 	uvm_tree_sanity(map, "unmap_remove entry");
   1646 
   1647 	/*
   1648 	 * find first entry
   1649 	 */
   1650 
   1651 	if (uvm_map_lookup_entry(map, start, &first_entry) == TRUE) {
   1652 		/* clip and go... */
   1653 		entry = first_entry;
   1654 		UVM_MAP_CLIP_START(map, entry, start);
   1655 		/* critical!  prevents stale hint */
   1656 		SAVE_HINT(map, entry, entry->prev);
   1657 	} else {
   1658 		entry = first_entry->next;
   1659 	}
   1660 
   1661 	/*
   1662 	 * Save the free space hint
   1663 	 */
   1664 
   1665 	if (map->first_free->start >= start)
   1666 		map->first_free = entry->prev;
   1667 
   1668 	/*
   1669 	 * note: we now re-use first_entry for a different task.  we remove
   1670 	 * a number of map entries from the map and save them in a linked
   1671 	 * list headed by "first_entry".  once we remove them from the map
   1672 	 * the caller should unlock the map and drop the references to the
   1673 	 * backing objects [c.f. uvm_unmap_detach].  the object is to
   1674 	 * separate unmapping from reference dropping.  why?
   1675 	 *   [1] the map has to be locked for unmapping
   1676 	 *   [2] the map need not be locked for reference dropping
   1677 	 *   [3] dropping references may trigger pager I/O, and if we hit
   1678 	 *       a pager that does synchronous I/O we may have to wait for it.
   1679 	 *   [4] we would like all waiting for I/O to occur with maps unlocked
   1680 	 *       so that we don't block other threads.
   1681 	 */
   1682 
   1683 	first_entry = NULL;
   1684 	*entry_list = NULL;
   1685 
   1686 	/*
   1687 	 * break up the area into map entry sized regions and unmap.  note
   1688 	 * that all mappings have to be removed before we can even consider
   1689 	 * dropping references to amaps or VM objects (otherwise we could end
   1690 	 * up with a mapping to a page on the free list which would be very bad)
   1691 	 */
   1692 
   1693 	while ((entry != &map->header) && (entry->start < end)) {
   1694 		UVM_MAP_CLIP_END(map, entry, end);
   1695 		next = entry->next;
   1696 		len = entry->end - entry->start;
   1697 
   1698 		/*
   1699 		 * unwire before removing addresses from the pmap; otherwise
   1700 		 * unwiring will put the entries back into the pmap (XXX).
   1701 		 */
   1702 
   1703 		if (VM_MAPENT_ISWIRED(entry)) {
   1704 			uvm_map_entry_unwire(map, entry);
   1705 		}
   1706 		if ((map->flags & VM_MAP_PAGEABLE) == 0) {
   1707 
   1708 			/*
   1709 			 * if the map is non-pageable, any pages mapped there
   1710 			 * must be wired and entered with pmap_kenter_pa(),
   1711 			 * and we should free any such pages immediately.
   1712 			 * this is mostly used for kmem_map and mb_map.
   1713 			 */
   1714 
   1715 			uvm_km_pgremove_intrsafe(entry->start, entry->end);
   1716 			pmap_kremove(entry->start, len);
   1717 		} else if (UVM_ET_ISOBJ(entry) &&
   1718 			   UVM_OBJ_IS_KERN_OBJECT(entry->object.uvm_obj)) {
   1719 			KASSERT(vm_map_pmap(map) == pmap_kernel());
   1720 
   1721 			/*
   1722 			 * note: kernel object mappings are currently used in
   1723 			 * two ways:
   1724 			 *  [1] "normal" mappings of pages in the kernel object
   1725 			 *  [2] uvm_km_valloc'd allocations in which we
   1726 			 *      pmap_enter in some non-kernel-object page
   1727 			 *      (e.g. vmapbuf).
   1728 			 *
   1729 			 * for case [1], we need to remove the mapping from
   1730 			 * the pmap and then remove the page from the kernel
   1731 			 * object (because, once pages in a kernel object are
   1732 			 * unmapped they are no longer needed, unlike, say,
   1733 			 * a vnode where you might want the data to persist
   1734 			 * until flushed out of a queue).
   1735 			 *
   1736 			 * for case [2], we need to remove the mapping from
   1737 			 * the pmap.  there shouldn't be any pages at the
   1738 			 * specified offset in the kernel object [but it
   1739 			 * doesn't hurt to call uvm_km_pgremove just to be
   1740 			 * safe?]
   1741 			 *
   1742 			 * uvm_km_pgremove currently does the following:
   1743 			 *   for pages in the kernel object in range:
   1744 			 *     - drops the swap slot
   1745 			 *     - uvm_pagefree the page
   1746 			 */
   1747 
   1748 			/*
   1749 			 * remove mappings from pmap and drop the pages
   1750 			 * from the object.  offsets are always relative
   1751 			 * to vm_map_min(kernel_map).
   1752 			 */
   1753 
   1754 			pmap_remove(pmap_kernel(), entry->start,
   1755 			    entry->start + len);
   1756 			uvm_km_pgremove(entry->object.uvm_obj,
   1757 			    entry->start - vm_map_min(kernel_map),
   1758 			    entry->end - vm_map_min(kernel_map));
   1759 
   1760 			/*
   1761 			 * null out kernel_object reference, we've just
   1762 			 * dropped it
   1763 			 */
   1764 
   1765 			entry->etype &= ~UVM_ET_OBJ;
   1766 			entry->object.uvm_obj = NULL;
   1767 		} else if (UVM_ET_ISOBJ(entry) || entry->aref.ar_amap) {
   1768 
   1769 			/*
   1770 			 * remove mappings the standard way.
   1771 			 */
   1772 
   1773 			pmap_remove(map->pmap, entry->start, entry->end);
   1774 		}
   1775 
   1776 		/*
   1777 		 * remove entry from map and put it on our list of entries
   1778 		 * that we've nuked.  then go to next entry.
   1779 		 */
   1780 
   1781 		UVMHIST_LOG(maphist, "  removed map entry 0x%x", entry, 0, 0,0);
   1782 
   1783 		/* critical!  prevents stale hint */
   1784 		SAVE_HINT(map, entry, entry->prev);
   1785 
   1786 		uvm_map_entry_unlink(map, entry);
   1787 		KASSERT(map->size >= len);
   1788 		map->size -= len;
   1789 		entry->prev = NULL;
   1790 		entry->next = first_entry;
   1791 		first_entry = entry;
   1792 		entry = next;
   1793 	}
   1794 	if ((map->flags & VM_MAP_DYING) == 0) {
   1795 		pmap_update(vm_map_pmap(map));
   1796 	}
   1797 
   1798 	uvm_tree_sanity(map, "unmap_remove leave");
   1799 
   1800 	/*
   1801 	 * now we've cleaned up the map and are ready for the caller to drop
   1802 	 * references to the mapped objects.
   1803 	 */
   1804 
   1805 	*entry_list = first_entry;
   1806 	UVMHIST_LOG(maphist,"<- done!", 0, 0, 0, 0);
   1807 }
   1808 
   1809 /*
   1810  * uvm_unmap_detach: drop references in a chain of map entries
   1811  *
   1812  * => we will free the map entries as we traverse the list.
   1813  */
   1814 
   1815 void
   1816 uvm_unmap_detach(struct vm_map_entry *first_entry, int flags)
   1817 {
   1818 	struct vm_map_entry *next_entry;
   1819 	UVMHIST_FUNC("uvm_unmap_detach"); UVMHIST_CALLED(maphist);
   1820 
   1821 	while (first_entry) {
   1822 		KASSERT(!VM_MAPENT_ISWIRED(first_entry));
   1823 		UVMHIST_LOG(maphist,
   1824 		    "  detach 0x%x: amap=0x%x, obj=0x%x, submap?=%d",
   1825 		    first_entry, first_entry->aref.ar_amap,
   1826 		    first_entry->object.uvm_obj,
   1827 		    UVM_ET_ISSUBMAP(first_entry));
   1828 
   1829 		/*
   1830 		 * drop reference to amap, if we've got one
   1831 		 */
   1832 
   1833 		if (first_entry->aref.ar_amap)
   1834 			uvm_map_unreference_amap(first_entry, flags);
   1835 
   1836 		/*
   1837 		 * drop reference to our backing object, if we've got one
   1838 		 */
   1839 
   1840 		KASSERT(!UVM_ET_ISSUBMAP(first_entry));
   1841 		if (UVM_ET_ISOBJ(first_entry) &&
   1842 		    first_entry->object.uvm_obj->pgops->pgo_detach) {
   1843 			(*first_entry->object.uvm_obj->pgops->pgo_detach)
   1844 				(first_entry->object.uvm_obj);
   1845 		}
   1846 		next_entry = first_entry->next;
   1847 		uvm_mapent_free(first_entry);
   1848 		first_entry = next_entry;
   1849 	}
   1850 	UVMHIST_LOG(maphist, "<- done", 0,0,0,0);
   1851 }
   1852 
   1853 /*
   1854  *   E X T R A C T I O N   F U N C T I O N S
   1855  */
   1856 
   1857 /*
   1858  * uvm_map_reserve: reserve space in a vm_map for future use.
   1859  *
   1860  * => we reserve space in a map by putting a dummy map entry in the
   1861  *    map (dummy means obj=NULL, amap=NULL, prot=VM_PROT_NONE)
   1862  * => map should be unlocked (we will write lock it)
   1863  * => we return true if we were able to reserve space
   1864  * => XXXCDC: should be inline?
   1865  */
   1866 
   1867 int
   1868 uvm_map_reserve(struct vm_map *map, vsize_t size,
   1869     vaddr_t offset	/* hint for pmap_prefer */,
   1870     vsize_t align	/* alignment hint */,
   1871     vaddr_t *raddr	/* IN:hint, OUT: reserved VA */)
   1872 {
   1873 	UVMHIST_FUNC("uvm_map_reserve"); UVMHIST_CALLED(maphist);
   1874 
   1875 	UVMHIST_LOG(maphist, "(map=0x%x, size=0x%x, offset=0x%x,addr=0x%x)",
   1876 	    map,size,offset,raddr);
   1877 
   1878 	size = round_page(size);
   1879 	if (*raddr < vm_map_min(map))
   1880 		*raddr = vm_map_min(map);		/* hint */
   1881 
   1882 	/*
   1883 	 * reserve some virtual space.
   1884 	 */
   1885 
   1886 	if (uvm_map(map, raddr, size, NULL, offset, 0,
   1887 	    UVM_MAPFLAG(UVM_PROT_NONE, UVM_PROT_NONE, UVM_INH_NONE,
   1888 	    UVM_ADV_RANDOM, UVM_FLAG_NOMERGE)) != 0) {
   1889 	    UVMHIST_LOG(maphist, "<- done (no VM)", 0,0,0,0);
   1890 		return (FALSE);
   1891 	}
   1892 
   1893 	UVMHIST_LOG(maphist, "<- done (*raddr=0x%x)", *raddr,0,0,0);
   1894 	return (TRUE);
   1895 }
   1896 
   1897 /*
   1898  * uvm_map_replace: replace a reserved (blank) area of memory with
   1899  * real mappings.
   1900  *
   1901  * => caller must WRITE-LOCK the map
   1902  * => we return TRUE if replacement was a success
   1903  * => we expect the newents chain to have nnewents entrys on it and
   1904  *    we expect newents->prev to point to the last entry on the list
   1905  * => note newents is allowed to be NULL
   1906  */
   1907 
   1908 int
   1909 uvm_map_replace(struct vm_map *map, vaddr_t start, vaddr_t end,
   1910     struct vm_map_entry *newents, int nnewents)
   1911 {
   1912 	struct vm_map_entry *oldent, *last;
   1913 
   1914 	uvm_tree_sanity(map, "map_replace entry");
   1915 
   1916 	/*
   1917 	 * first find the blank map entry at the specified address
   1918 	 */
   1919 
   1920 	if (!uvm_map_lookup_entry(map, start, &oldent)) {
   1921 		return (FALSE);
   1922 	}
   1923 
   1924 	/*
   1925 	 * check to make sure we have a proper blank entry
   1926 	 */
   1927 
   1928 	if (oldent->start != start || oldent->end != end ||
   1929 	    oldent->object.uvm_obj != NULL || oldent->aref.ar_amap != NULL) {
   1930 		return (FALSE);
   1931 	}
   1932 
   1933 #ifdef DIAGNOSTIC
   1934 
   1935 	/*
   1936 	 * sanity check the newents chain
   1937 	 */
   1938 
   1939 	{
   1940 		struct vm_map_entry *tmpent = newents;
   1941 		int nent = 0;
   1942 		vaddr_t cur = start;
   1943 
   1944 		while (tmpent) {
   1945 			nent++;
   1946 			if (tmpent->start < cur)
   1947 				panic("uvm_map_replace1");
   1948 			if (tmpent->start > tmpent->end || tmpent->end > end) {
   1949 		printf("tmpent->start=0x%lx, tmpent->end=0x%lx, end=0x%lx\n",
   1950 			    tmpent->start, tmpent->end, end);
   1951 				panic("uvm_map_replace2");
   1952 			}
   1953 			cur = tmpent->end;
   1954 			if (tmpent->next) {
   1955 				if (tmpent->next->prev != tmpent)
   1956 					panic("uvm_map_replace3");
   1957 			} else {
   1958 				if (newents->prev != tmpent)
   1959 					panic("uvm_map_replace4");
   1960 			}
   1961 			tmpent = tmpent->next;
   1962 		}
   1963 		if (nent != nnewents)
   1964 			panic("uvm_map_replace5");
   1965 	}
   1966 #endif
   1967 
   1968 	/*
   1969 	 * map entry is a valid blank!   replace it.   (this does all the
   1970 	 * work of map entry link/unlink...).
   1971 	 */
   1972 
   1973 	if (newents) {
   1974 		last = newents->prev;
   1975 
   1976 		/* critical: flush stale hints out of map */
   1977 		SAVE_HINT(map, map->hint, newents);
   1978 		if (map->first_free == oldent)
   1979 			map->first_free = last;
   1980 
   1981 		last->next = oldent->next;
   1982 		last->next->prev = last;
   1983 
   1984 		/* Fix RB tree */
   1985 		uvm_rb_remove(map, oldent);
   1986 
   1987 		newents->prev = oldent->prev;
   1988 		newents->prev->next = newents;
   1989 		map->nentries = map->nentries + (nnewents - 1);
   1990 
   1991 		/* Fixup the RB tree */
   1992 		{
   1993 			int i;
   1994 			struct vm_map_entry *tmp;
   1995 
   1996 			tmp = newents;
   1997 			for (i = 0; i < nnewents && tmp; i++) {
   1998 				uvm_rb_insert(map, tmp);
   1999 				tmp = tmp->next;
   2000 			}
   2001 		}
   2002 	} else {
   2003 
   2004 		/* critical: flush stale hints out of map */
   2005 		SAVE_HINT(map, map->hint, oldent->prev);
   2006 		if (map->first_free == oldent)
   2007 			map->first_free = oldent->prev;
   2008 
   2009 		/* NULL list of new entries: just remove the old one */
   2010 		uvm_map_entry_unlink(map, oldent);
   2011 	}
   2012 
   2013 	uvm_tree_sanity(map, "map_replace leave");
   2014 
   2015 	/*
   2016 	 * now we can free the old blank entry, unlock the map and return.
   2017 	 */
   2018 
   2019 	uvm_mapent_free(oldent);
   2020 	return (TRUE);
   2021 }
   2022 
   2023 /*
   2024  * uvm_map_extract: extract a mapping from a map and put it somewhere
   2025  *	(maybe removing the old mapping)
   2026  *
   2027  * => maps should be unlocked (we will write lock them)
   2028  * => returns 0 on success, error code otherwise
   2029  * => start must be page aligned
   2030  * => len must be page sized
   2031  * => flags:
   2032  *      UVM_EXTRACT_REMOVE: remove mappings from srcmap
   2033  *      UVM_EXTRACT_CONTIG: abort if unmapped area (advisory only)
   2034  *      UVM_EXTRACT_QREF: for a temporary extraction do quick obj refs
   2035  *      UVM_EXTRACT_FIXPROT: set prot to maxprot as we go
   2036  *    >>>NOTE: if you set REMOVE, you are not allowed to use CONTIG or QREF!<<<
   2037  *    >>>NOTE: QREF's must be unmapped via the QREF path, thus should only
   2038  *             be used from within the kernel in a kernel level map <<<
   2039  */
   2040 
   2041 int
   2042 uvm_map_extract(struct vm_map *srcmap, vaddr_t start, vsize_t len,
   2043     struct vm_map *dstmap, vaddr_t *dstaddrp, int flags)
   2044 {
   2045 	vaddr_t dstaddr, end, newend, oldoffset, fudge, orig_fudge,
   2046 	    oldstart;
   2047 	struct vm_map_entry *chain, *endchain, *entry, *orig_entry, *newentry,
   2048 	    *deadentry, *oldentry;
   2049 	vsize_t elen;
   2050 	int nchain, error, copy_ok;
   2051 	UVMHIST_FUNC("uvm_map_extract"); UVMHIST_CALLED(maphist);
   2052 
   2053 	UVMHIST_LOG(maphist,"(srcmap=0x%x,start=0x%x, len=0x%x", srcmap, start,
   2054 	    len,0);
   2055 	UVMHIST_LOG(maphist," ...,dstmap=0x%x, flags=0x%x)", dstmap,flags,0,0);
   2056 
   2057 	uvm_tree_sanity(srcmap, "map_extract src enter");
   2058 	uvm_tree_sanity(dstmap, "map_extract dst enter");
   2059 
   2060 	/*
   2061 	 * step 0: sanity check: start must be on a page boundary, length
   2062 	 * must be page sized.  can't ask for CONTIG/QREF if you asked for
   2063 	 * REMOVE.
   2064 	 */
   2065 
   2066 	KASSERT((start & PAGE_MASK) == 0 && (len & PAGE_MASK) == 0);
   2067 	KASSERT((flags & UVM_EXTRACT_REMOVE) == 0 ||
   2068 		(flags & (UVM_EXTRACT_CONTIG|UVM_EXTRACT_QREF)) == 0);
   2069 
   2070 	/*
   2071 	 * step 1: reserve space in the target map for the extracted area
   2072 	 */
   2073 
   2074 	dstaddr = vm_map_min(dstmap);
   2075 	if (uvm_map_reserve(dstmap, len, start, 0, &dstaddr) == FALSE)
   2076 		return (ENOMEM);
   2077 	*dstaddrp = dstaddr;	/* pass address back to caller */
   2078 	UVMHIST_LOG(maphist, "  dstaddr=0x%x", dstaddr,0,0,0);
   2079 
   2080 	/*
   2081 	 * step 2: setup for the extraction process loop by init'ing the
   2082 	 * map entry chain, locking src map, and looking up the first useful
   2083 	 * entry in the map.
   2084 	 */
   2085 
   2086 	end = start + len;
   2087 	newend = dstaddr + len;
   2088 	chain = endchain = NULL;
   2089 	nchain = 0;
   2090 	vm_map_lock(srcmap);
   2091 
   2092 	if (uvm_map_lookup_entry(srcmap, start, &entry)) {
   2093 
   2094 		/* "start" is within an entry */
   2095 		if (flags & UVM_EXTRACT_QREF) {
   2096 
   2097 			/*
   2098 			 * for quick references we don't clip the entry, so
   2099 			 * the entry may map space "before" the starting
   2100 			 * virtual address... this is the "fudge" factor
   2101 			 * (which can be non-zero only the first time
   2102 			 * through the "while" loop in step 3).
   2103 			 */
   2104 
   2105 			fudge = start - entry->start;
   2106 		} else {
   2107 
   2108 			/*
   2109 			 * normal reference: we clip the map to fit (thus
   2110 			 * fudge is zero)
   2111 			 */
   2112 
   2113 			UVM_MAP_CLIP_START(srcmap, entry, start);
   2114 			SAVE_HINT(srcmap, srcmap->hint, entry->prev);
   2115 			fudge = 0;
   2116 		}
   2117 	} else {
   2118 
   2119 		/* "start" is not within an entry ... skip to next entry */
   2120 		if (flags & UVM_EXTRACT_CONTIG) {
   2121 			error = EINVAL;
   2122 			goto bad;    /* definite hole here ... */
   2123 		}
   2124 
   2125 		entry = entry->next;
   2126 		fudge = 0;
   2127 	}
   2128 
   2129 	/* save values from srcmap for step 6 */
   2130 	orig_entry = entry;
   2131 	orig_fudge = fudge;
   2132 
   2133 	/*
   2134 	 * step 3: now start looping through the map entries, extracting
   2135 	 * as we go.
   2136 	 */
   2137 
   2138 	while (entry->start < end && entry != &srcmap->header) {
   2139 
   2140 		/* if we are not doing a quick reference, clip it */
   2141 		if ((flags & UVM_EXTRACT_QREF) == 0)
   2142 			UVM_MAP_CLIP_END(srcmap, entry, end);
   2143 
   2144 		/* clear needs_copy (allow chunking) */
   2145 		if (UVM_ET_ISNEEDSCOPY(entry)) {
   2146 			if (fudge)
   2147 				oldstart = entry->start;
   2148 			else
   2149 				oldstart = 0;	/* XXX: gcc */
   2150 			amap_copy(srcmap, entry, M_NOWAIT, TRUE, start, end);
   2151 			if (UVM_ET_ISNEEDSCOPY(entry)) {  /* failed? */
   2152 				error = ENOMEM;
   2153 				goto bad;
   2154 			}
   2155 
   2156 			/* amap_copy could clip (during chunk)!  update fudge */
   2157 			if (fudge) {
   2158 				fudge = fudge - (entry->start - oldstart);
   2159 				orig_fudge = fudge;
   2160 			}
   2161 		}
   2162 
   2163 		/* calculate the offset of this from "start" */
   2164 		oldoffset = (entry->start + fudge) - start;
   2165 
   2166 		/* allocate a new map entry */
   2167 		newentry = uvm_mapent_alloc(dstmap, 0);
   2168 		if (newentry == NULL) {
   2169 			error = ENOMEM;
   2170 			goto bad;
   2171 		}
   2172 
   2173 		/* set up new map entry */
   2174 		newentry->next = NULL;
   2175 		newentry->prev = endchain;
   2176 		newentry->start = dstaddr + oldoffset;
   2177 		newentry->end =
   2178 		    newentry->start + (entry->end - (entry->start + fudge));
   2179 		if (newentry->end > newend || newentry->end < newentry->start)
   2180 			newentry->end = newend;
   2181 		newentry->object.uvm_obj = entry->object.uvm_obj;
   2182 		if (newentry->object.uvm_obj) {
   2183 			if (newentry->object.uvm_obj->pgops->pgo_reference)
   2184 				newentry->object.uvm_obj->pgops->
   2185 				    pgo_reference(newentry->object.uvm_obj);
   2186 				newentry->offset = entry->offset + fudge;
   2187 		} else {
   2188 			newentry->offset = 0;
   2189 		}
   2190 		newentry->etype = entry->etype;
   2191 		newentry->protection = (flags & UVM_EXTRACT_FIXPROT) ?
   2192 			entry->max_protection : entry->protection;
   2193 		newentry->max_protection = entry->max_protection;
   2194 		newentry->inheritance = entry->inheritance;
   2195 		newentry->wired_count = 0;
   2196 		newentry->aref.ar_amap = entry->aref.ar_amap;
   2197 		if (newentry->aref.ar_amap) {
   2198 			newentry->aref.ar_pageoff =
   2199 			    entry->aref.ar_pageoff + (fudge >> PAGE_SHIFT);
   2200 			uvm_map_reference_amap(newentry, AMAP_SHARED |
   2201 			    ((flags & UVM_EXTRACT_QREF) ? AMAP_REFALL : 0));
   2202 		} else {
   2203 			newentry->aref.ar_pageoff = 0;
   2204 		}
   2205 		newentry->advice = entry->advice;
   2206 
   2207 		/* now link it on the chain */
   2208 		nchain++;
   2209 		if (endchain == NULL) {
   2210 			chain = endchain = newentry;
   2211 		} else {
   2212 			endchain->next = newentry;
   2213 			endchain = newentry;
   2214 		}
   2215 
   2216 		/* end of 'while' loop! */
   2217 		if ((flags & UVM_EXTRACT_CONTIG) && entry->end < end &&
   2218 		    (entry->next == &srcmap->header ||
   2219 		    entry->next->start != entry->end)) {
   2220 			error = EINVAL;
   2221 			goto bad;
   2222 		}
   2223 		entry = entry->next;
   2224 		fudge = 0;
   2225 	}
   2226 
   2227 	/*
   2228 	 * step 4: close off chain (in format expected by uvm_map_replace)
   2229 	 */
   2230 
   2231 	if (chain)
   2232 		chain->prev = endchain;
   2233 
   2234 	/*
   2235 	 * step 5: attempt to lock the dest map so we can pmap_copy.
   2236 	 * note usage of copy_ok:
   2237 	 *   1 => dstmap locked, pmap_copy ok, and we "replace" here (step 5)
   2238 	 *   0 => dstmap unlocked, NO pmap_copy, and we will "replace" in step 7
   2239 	 */
   2240 
   2241 	if (srcmap == dstmap || vm_map_lock_try(dstmap) == TRUE) {
   2242 		copy_ok = 1;
   2243 		if (!uvm_map_replace(dstmap, dstaddr, dstaddr+len, chain,
   2244 		    nchain)) {
   2245 			if (srcmap != dstmap)
   2246 				vm_map_unlock(dstmap);
   2247 			error = EIO;
   2248 			goto bad;
   2249 		}
   2250 	} else {
   2251 		copy_ok = 0;
   2252 		/* replace defered until step 7 */
   2253 	}
   2254 
   2255 	/*
   2256 	 * step 6: traverse the srcmap a second time to do the following:
   2257 	 *  - if we got a lock on the dstmap do pmap_copy
   2258 	 *  - if UVM_EXTRACT_REMOVE remove the entries
   2259 	 * we make use of orig_entry and orig_fudge (saved in step 2)
   2260 	 */
   2261 
   2262 	if (copy_ok || (flags & UVM_EXTRACT_REMOVE)) {
   2263 
   2264 		/* purge possible stale hints from srcmap */
   2265 		if (flags & UVM_EXTRACT_REMOVE) {
   2266 			SAVE_HINT(srcmap, srcmap->hint, orig_entry->prev);
   2267 			if (srcmap->first_free->start >= start)
   2268 				srcmap->first_free = orig_entry->prev;
   2269 		}
   2270 
   2271 		entry = orig_entry;
   2272 		fudge = orig_fudge;
   2273 		deadentry = NULL;	/* for UVM_EXTRACT_REMOVE */
   2274 
   2275 		while (entry->start < end && entry != &srcmap->header) {
   2276 			if (copy_ok) {
   2277 				oldoffset = (entry->start + fudge) - start;
   2278 				elen = MIN(end, entry->end) -
   2279 				    (entry->start + fudge);
   2280 				pmap_copy(dstmap->pmap, srcmap->pmap,
   2281 				    dstaddr + oldoffset, elen,
   2282 				    entry->start + fudge);
   2283 			}
   2284 
   2285 			/* we advance "entry" in the following if statement */
   2286 			if (flags & UVM_EXTRACT_REMOVE) {
   2287 				pmap_remove(srcmap->pmap, entry->start,
   2288 						entry->end);
   2289 				oldentry = entry;	/* save entry */
   2290 				entry = entry->next;	/* advance */
   2291 				uvm_map_entry_unlink(srcmap, oldentry);
   2292 							/* add to dead list */
   2293 				oldentry->next = deadentry;
   2294 				deadentry = oldentry;
   2295 			} else {
   2296 				entry = entry->next;		/* advance */
   2297 			}
   2298 
   2299 			/* end of 'while' loop */
   2300 			fudge = 0;
   2301 		}
   2302 		pmap_update(srcmap->pmap);
   2303 
   2304 		/*
   2305 		 * unlock dstmap.  we will dispose of deadentry in
   2306 		 * step 7 if needed
   2307 		 */
   2308 
   2309 		if (copy_ok && srcmap != dstmap)
   2310 			vm_map_unlock(dstmap);
   2311 
   2312 	} else {
   2313 		deadentry = NULL;
   2314 	}
   2315 
   2316 	/*
   2317 	 * step 7: we are done with the source map, unlock.   if copy_ok
   2318 	 * is 0 then we have not replaced the dummy mapping in dstmap yet
   2319 	 * and we need to do so now.
   2320 	 */
   2321 
   2322 	vm_map_unlock(srcmap);
   2323 	if ((flags & UVM_EXTRACT_REMOVE) && deadentry)
   2324 		uvm_unmap_detach(deadentry, 0);   /* dispose of old entries */
   2325 
   2326 	/* now do the replacement if we didn't do it in step 5 */
   2327 	if (copy_ok == 0) {
   2328 		vm_map_lock(dstmap);
   2329 		error = uvm_map_replace(dstmap, dstaddr, dstaddr+len, chain,
   2330 		    nchain);
   2331 		vm_map_unlock(dstmap);
   2332 
   2333 		if (error == FALSE) {
   2334 			error = EIO;
   2335 			goto bad2;
   2336 		}
   2337 	}
   2338 
   2339 	uvm_tree_sanity(srcmap, "map_extract src leave");
   2340 	uvm_tree_sanity(dstmap, "map_extract dst leave");
   2341 
   2342 	return (0);
   2343 
   2344 	/*
   2345 	 * bad: failure recovery
   2346 	 */
   2347 bad:
   2348 	vm_map_unlock(srcmap);
   2349 bad2:			/* src already unlocked */
   2350 	if (chain)
   2351 		uvm_unmap_detach(chain,
   2352 		    (flags & UVM_EXTRACT_QREF) ? AMAP_REFALL : 0);
   2353 
   2354 	uvm_tree_sanity(srcmap, "map_extract src err leave");
   2355 	uvm_tree_sanity(dstmap, "map_extract dst err leave");
   2356 
   2357 	uvm_unmap(dstmap, dstaddr, dstaddr+len);   /* ??? */
   2358 	return (error);
   2359 }
   2360 
   2361 /* end of extraction functions */
   2362 
   2363 /*
   2364  * uvm_map_submap: punch down part of a map into a submap
   2365  *
   2366  * => only the kernel_map is allowed to be submapped
   2367  * => the purpose of submapping is to break up the locking granularity
   2368  *	of a larger map
   2369  * => the range specified must have been mapped previously with a uvm_map()
   2370  *	call [with uobj==NULL] to create a blank map entry in the main map.
   2371  *	[And it had better still be blank!]
   2372  * => maps which contain submaps should never be copied or forked.
   2373  * => to remove a submap, use uvm_unmap() on the main map
   2374  *	and then uvm_map_deallocate() the submap.
   2375  * => main map must be unlocked.
   2376  * => submap must have been init'd and have a zero reference count.
   2377  *	[need not be locked as we don't actually reference it]
   2378  */
   2379 
   2380 int
   2381 uvm_map_submap(struct vm_map *map, vaddr_t start, vaddr_t end,
   2382     struct vm_map *submap)
   2383 {
   2384 	struct vm_map_entry *entry;
   2385 	int error;
   2386 
   2387 	vm_map_lock(map);
   2388 	VM_MAP_RANGE_CHECK(map, start, end);
   2389 
   2390 	if (uvm_map_lookup_entry(map, start, &entry)) {
   2391 		UVM_MAP_CLIP_START(map, entry, start);
   2392 		UVM_MAP_CLIP_END(map, entry, end);		/* to be safe */
   2393 	} else {
   2394 		entry = NULL;
   2395 	}
   2396 
   2397 	if (entry != NULL &&
   2398 	    entry->start == start && entry->end == end &&
   2399 	    entry->object.uvm_obj == NULL && entry->aref.ar_amap == NULL &&
   2400 	    !UVM_ET_ISCOPYONWRITE(entry) && !UVM_ET_ISNEEDSCOPY(entry)) {
   2401 		entry->etype |= UVM_ET_SUBMAP;
   2402 		entry->object.sub_map = submap;
   2403 		entry->offset = 0;
   2404 		uvm_map_reference(submap);
   2405 		error = 0;
   2406 	} else {
   2407 		error = EINVAL;
   2408 	}
   2409 	vm_map_unlock(map);
   2410 	return error;
   2411 }
   2412 
   2413 
   2414 /*
   2415  * uvm_map_protect: change map protection
   2416  *
   2417  * => set_max means set max_protection.
   2418  * => map must be unlocked.
   2419  */
   2420 
   2421 #define MASK(entry)	(UVM_ET_ISCOPYONWRITE(entry) ? \
   2422 			 ~VM_PROT_WRITE : VM_PROT_ALL)
   2423 
   2424 int
   2425 uvm_map_protect(struct vm_map *map, vaddr_t start, vaddr_t end,
   2426     vm_prot_t new_prot, boolean_t set_max)
   2427 {
   2428 	struct vm_map_entry *current, *entry;
   2429 	int error = 0;
   2430 	UVMHIST_FUNC("uvm_map_protect"); UVMHIST_CALLED(maphist);
   2431 	UVMHIST_LOG(maphist,"(map=0x%x,start=0x%x,end=0x%x,new_prot=0x%x)",
   2432 		    map, start, end, new_prot);
   2433 
   2434 	vm_map_lock(map);
   2435 	VM_MAP_RANGE_CHECK(map, start, end);
   2436 	if (uvm_map_lookup_entry(map, start, &entry)) {
   2437 		UVM_MAP_CLIP_START(map, entry, start);
   2438 	} else {
   2439 		entry = entry->next;
   2440 	}
   2441 
   2442 	/*
   2443 	 * make a first pass to check for protection violations.
   2444 	 */
   2445 
   2446 	current = entry;
   2447 	while ((current != &map->header) && (current->start < end)) {
   2448 		if (UVM_ET_ISSUBMAP(current)) {
   2449 			error = EINVAL;
   2450 			goto out;
   2451 		}
   2452 		if ((new_prot & current->max_protection) != new_prot) {
   2453 			error = EACCES;
   2454 			goto out;
   2455 		}
   2456 		/*
   2457 		 * Don't allow VM_PROT_EXECUTE to be set on entries that
   2458 		 * point to vnodes that are associated with a NOEXEC file
   2459 		 * system.
   2460 		 */
   2461 		if (UVM_ET_ISOBJ(current) &&
   2462 		    UVM_OBJ_IS_VNODE(current->object.uvm_obj)) {
   2463 			struct vnode *vp =
   2464 			    (struct vnode *) current->object.uvm_obj;
   2465 
   2466 			if ((new_prot & VM_PROT_EXECUTE) != 0 &&
   2467 			    (vp->v_mount->mnt_flag & MNT_NOEXEC) != 0) {
   2468 				error = EACCES;
   2469 				goto out;
   2470 			}
   2471 		}
   2472 		current = current->next;
   2473 	}
   2474 
   2475 	/* go back and fix up protections (no need to clip this time). */
   2476 
   2477 	current = entry;
   2478 	while ((current != &map->header) && (current->start < end)) {
   2479 		vm_prot_t old_prot;
   2480 
   2481 		UVM_MAP_CLIP_END(map, current, end);
   2482 		old_prot = current->protection;
   2483 		if (set_max)
   2484 			current->protection =
   2485 			    (current->max_protection = new_prot) & old_prot;
   2486 		else
   2487 			current->protection = new_prot;
   2488 
   2489 		/*
   2490 		 * update physical map if necessary.  worry about copy-on-write
   2491 		 * here -- CHECK THIS XXX
   2492 		 */
   2493 
   2494 		if (current->protection != old_prot) {
   2495 			/* update pmap! */
   2496 			pmap_protect(map->pmap, current->start, current->end,
   2497 			    current->protection & MASK(entry));
   2498 
   2499 			/*
   2500 			 * If this entry points at a vnode, and the
   2501 			 * protection includes VM_PROT_EXECUTE, mark
   2502 			 * the vnode as VEXECMAP.
   2503 			 */
   2504 			if (UVM_ET_ISOBJ(current)) {
   2505 				struct uvm_object *uobj =
   2506 				    current->object.uvm_obj;
   2507 
   2508 				if (UVM_OBJ_IS_VNODE(uobj) &&
   2509 				    (current->protection & VM_PROT_EXECUTE))
   2510 					vn_markexec((struct vnode *) uobj);
   2511 			}
   2512 		}
   2513 
   2514 		/*
   2515 		 * If the map is configured to lock any future mappings,
   2516 		 * wire this entry now if the old protection was VM_PROT_NONE
   2517 		 * and the new protection is not VM_PROT_NONE.
   2518 		 */
   2519 
   2520 		if ((map->flags & VM_MAP_WIREFUTURE) != 0 &&
   2521 		    VM_MAPENT_ISWIRED(entry) == 0 &&
   2522 		    old_prot == VM_PROT_NONE &&
   2523 		    new_prot != VM_PROT_NONE) {
   2524 			if (uvm_map_pageable(map, entry->start,
   2525 			    entry->end, FALSE,
   2526 			    UVM_LK_ENTER|UVM_LK_EXIT) != 0) {
   2527 
   2528 				/*
   2529 				 * If locking the entry fails, remember the
   2530 				 * error if it's the first one.  Note we
   2531 				 * still continue setting the protection in
   2532 				 * the map, but will return the error
   2533 				 * condition regardless.
   2534 				 *
   2535 				 * XXX Ignore what the actual error is,
   2536 				 * XXX just call it a resource shortage
   2537 				 * XXX so that it doesn't get confused
   2538 				 * XXX what uvm_map_protect() itself would
   2539 				 * XXX normally return.
   2540 				 */
   2541 
   2542 				error = ENOMEM;
   2543 			}
   2544 		}
   2545 		current = current->next;
   2546 	}
   2547 	pmap_update(map->pmap);
   2548 
   2549  out:
   2550 	vm_map_unlock(map);
   2551 	UVMHIST_LOG(maphist, "<- done, error=%d",error,0,0,0);
   2552 	return error;
   2553 }
   2554 
   2555 #undef  MASK
   2556 
   2557 /*
   2558  * uvm_map_inherit: set inheritance code for range of addrs in map.
   2559  *
   2560  * => map must be unlocked
   2561  * => note that the inherit code is used during a "fork".  see fork
   2562  *	code for details.
   2563  */
   2564 
   2565 int
   2566 uvm_map_inherit(struct vm_map *map, vaddr_t start, vaddr_t end,
   2567     vm_inherit_t new_inheritance)
   2568 {
   2569 	struct vm_map_entry *entry, *temp_entry;
   2570 	UVMHIST_FUNC("uvm_map_inherit"); UVMHIST_CALLED(maphist);
   2571 	UVMHIST_LOG(maphist,"(map=0x%x,start=0x%x,end=0x%x,new_inh=0x%x)",
   2572 	    map, start, end, new_inheritance);
   2573 
   2574 	switch (new_inheritance) {
   2575 	case MAP_INHERIT_NONE:
   2576 	case MAP_INHERIT_COPY:
   2577 	case MAP_INHERIT_SHARE:
   2578 		break;
   2579 	default:
   2580 		UVMHIST_LOG(maphist,"<- done (INVALID ARG)",0,0,0,0);
   2581 		return EINVAL;
   2582 	}
   2583 
   2584 	vm_map_lock(map);
   2585 	VM_MAP_RANGE_CHECK(map, start, end);
   2586 	if (uvm_map_lookup_entry(map, start, &temp_entry)) {
   2587 		entry = temp_entry;
   2588 		UVM_MAP_CLIP_START(map, entry, start);
   2589 	}  else {
   2590 		entry = temp_entry->next;
   2591 	}
   2592 	while ((entry != &map->header) && (entry->start < end)) {
   2593 		UVM_MAP_CLIP_END(map, entry, end);
   2594 		entry->inheritance = new_inheritance;
   2595 		entry = entry->next;
   2596 	}
   2597 	vm_map_unlock(map);
   2598 	UVMHIST_LOG(maphist,"<- done (OK)",0,0,0,0);
   2599 	return 0;
   2600 }
   2601 
   2602 /*
   2603  * uvm_map_advice: set advice code for range of addrs in map.
   2604  *
   2605  * => map must be unlocked
   2606  */
   2607 
   2608 int
   2609 uvm_map_advice(struct vm_map *map, vaddr_t start, vaddr_t end, int new_advice)
   2610 {
   2611 	struct vm_map_entry *entry, *temp_entry;
   2612 	UVMHIST_FUNC("uvm_map_advice"); UVMHIST_CALLED(maphist);
   2613 	UVMHIST_LOG(maphist,"(map=0x%x,start=0x%x,end=0x%x,new_adv=0x%x)",
   2614 	    map, start, end, new_advice);
   2615 
   2616 	vm_map_lock(map);
   2617 	VM_MAP_RANGE_CHECK(map, start, end);
   2618 	if (uvm_map_lookup_entry(map, start, &temp_entry)) {
   2619 		entry = temp_entry;
   2620 		UVM_MAP_CLIP_START(map, entry, start);
   2621 	} else {
   2622 		entry = temp_entry->next;
   2623 	}
   2624 
   2625 	/*
   2626 	 * XXXJRT: disallow holes?
   2627 	 */
   2628 
   2629 	while ((entry != &map->header) && (entry->start < end)) {
   2630 		UVM_MAP_CLIP_END(map, entry, end);
   2631 
   2632 		switch (new_advice) {
   2633 		case MADV_NORMAL:
   2634 		case MADV_RANDOM:
   2635 		case MADV_SEQUENTIAL:
   2636 			/* nothing special here */
   2637 			break;
   2638 
   2639 		default:
   2640 			vm_map_unlock(map);
   2641 			UVMHIST_LOG(maphist,"<- done (INVALID ARG)",0,0,0,0);
   2642 			return EINVAL;
   2643 		}
   2644 		entry->advice = new_advice;
   2645 		entry = entry->next;
   2646 	}
   2647 
   2648 	vm_map_unlock(map);
   2649 	UVMHIST_LOG(maphist,"<- done (OK)",0,0,0,0);
   2650 	return 0;
   2651 }
   2652 
   2653 /*
   2654  * uvm_map_pageable: sets the pageability of a range in a map.
   2655  *
   2656  * => wires map entries.  should not be used for transient page locking.
   2657  *	for that, use uvm_fault_wire()/uvm_fault_unwire() (see uvm_vslock()).
   2658  * => regions sepcified as not pageable require lock-down (wired) memory
   2659  *	and page tables.
   2660  * => map must never be read-locked
   2661  * => if islocked is TRUE, map is already write-locked
   2662  * => we always unlock the map, since we must downgrade to a read-lock
   2663  *	to call uvm_fault_wire()
   2664  * => XXXCDC: check this and try and clean it up.
   2665  */
   2666 
   2667 int
   2668 uvm_map_pageable(struct vm_map *map, vaddr_t start, vaddr_t end,
   2669     boolean_t new_pageable, int lockflags)
   2670 {
   2671 	struct vm_map_entry *entry, *start_entry, *failed_entry;
   2672 	int rv;
   2673 #ifdef DIAGNOSTIC
   2674 	u_int timestamp_save;
   2675 #endif
   2676 	UVMHIST_FUNC("uvm_map_pageable"); UVMHIST_CALLED(maphist);
   2677 	UVMHIST_LOG(maphist,"(map=0x%x,start=0x%x,end=0x%x,new_pageable=0x%x)",
   2678 		    map, start, end, new_pageable);
   2679 	KASSERT(map->flags & VM_MAP_PAGEABLE);
   2680 
   2681 	if ((lockflags & UVM_LK_ENTER) == 0)
   2682 		vm_map_lock(map);
   2683 	VM_MAP_RANGE_CHECK(map, start, end);
   2684 
   2685 	/*
   2686 	 * only one pageability change may take place at one time, since
   2687 	 * uvm_fault_wire assumes it will be called only once for each
   2688 	 * wiring/unwiring.  therefore, we have to make sure we're actually
   2689 	 * changing the pageability for the entire region.  we do so before
   2690 	 * making any changes.
   2691 	 */
   2692 
   2693 	if (uvm_map_lookup_entry(map, start, &start_entry) == FALSE) {
   2694 		if ((lockflags & UVM_LK_EXIT) == 0)
   2695 			vm_map_unlock(map);
   2696 
   2697 		UVMHIST_LOG(maphist,"<- done (fault)",0,0,0,0);
   2698 		return EFAULT;
   2699 	}
   2700 	entry = start_entry;
   2701 
   2702 	/*
   2703 	 * handle wiring and unwiring separately.
   2704 	 */
   2705 
   2706 	if (new_pageable) {		/* unwire */
   2707 		UVM_MAP_CLIP_START(map, entry, start);
   2708 
   2709 		/*
   2710 		 * unwiring.  first ensure that the range to be unwired is
   2711 		 * really wired down and that there are no holes.
   2712 		 */
   2713 
   2714 		while ((entry != &map->header) && (entry->start < end)) {
   2715 			if (entry->wired_count == 0 ||
   2716 			    (entry->end < end &&
   2717 			     (entry->next == &map->header ||
   2718 			      entry->next->start > entry->end))) {
   2719 				if ((lockflags & UVM_LK_EXIT) == 0)
   2720 					vm_map_unlock(map);
   2721 				UVMHIST_LOG(maphist, "<- done (INVAL)",0,0,0,0);
   2722 				return EINVAL;
   2723 			}
   2724 			entry = entry->next;
   2725 		}
   2726 
   2727 		/*
   2728 		 * POSIX 1003.1b - a single munlock call unlocks a region,
   2729 		 * regardless of the number of mlock calls made on that
   2730 		 * region.
   2731 		 */
   2732 
   2733 		entry = start_entry;
   2734 		while ((entry != &map->header) && (entry->start < end)) {
   2735 			UVM_MAP_CLIP_END(map, entry, end);
   2736 			if (VM_MAPENT_ISWIRED(entry))
   2737 				uvm_map_entry_unwire(map, entry);
   2738 			entry = entry->next;
   2739 		}
   2740 		if ((lockflags & UVM_LK_EXIT) == 0)
   2741 			vm_map_unlock(map);
   2742 		UVMHIST_LOG(maphist,"<- done (OK UNWIRE)",0,0,0,0);
   2743 		return 0;
   2744 	}
   2745 
   2746 	/*
   2747 	 * wire case: in two passes [XXXCDC: ugly block of code here]
   2748 	 *
   2749 	 * 1: holding the write lock, we create any anonymous maps that need
   2750 	 *    to be created.  then we clip each map entry to the region to
   2751 	 *    be wired and increment its wiring count.
   2752 	 *
   2753 	 * 2: we downgrade to a read lock, and call uvm_fault_wire to fault
   2754 	 *    in the pages for any newly wired area (wired_count == 1).
   2755 	 *
   2756 	 *    downgrading to a read lock for uvm_fault_wire avoids a possible
   2757 	 *    deadlock with another thread that may have faulted on one of
   2758 	 *    the pages to be wired (it would mark the page busy, blocking
   2759 	 *    us, then in turn block on the map lock that we hold).  because
   2760 	 *    of problems in the recursive lock package, we cannot upgrade
   2761 	 *    to a write lock in vm_map_lookup.  thus, any actions that
   2762 	 *    require the write lock must be done beforehand.  because we
   2763 	 *    keep the read lock on the map, the copy-on-write status of the
   2764 	 *    entries we modify here cannot change.
   2765 	 */
   2766 
   2767 	while ((entry != &map->header) && (entry->start < end)) {
   2768 		if (VM_MAPENT_ISWIRED(entry) == 0) { /* not already wired? */
   2769 
   2770 			/*
   2771 			 * perform actions of vm_map_lookup that need the
   2772 			 * write lock on the map: create an anonymous map
   2773 			 * for a copy-on-write region, or an anonymous map
   2774 			 * for a zero-fill region.  (XXXCDC: submap case
   2775 			 * ok?)
   2776 			 */
   2777 
   2778 			if (!UVM_ET_ISSUBMAP(entry)) {  /* not submap */
   2779 				if (UVM_ET_ISNEEDSCOPY(entry) &&
   2780 				    ((entry->max_protection & VM_PROT_WRITE) ||
   2781 				     (entry->object.uvm_obj == NULL))) {
   2782 					amap_copy(map, entry, M_WAITOK, TRUE,
   2783 					    start, end);
   2784 					/* XXXCDC: wait OK? */
   2785 				}
   2786 			}
   2787 		}
   2788 		UVM_MAP_CLIP_START(map, entry, start);
   2789 		UVM_MAP_CLIP_END(map, entry, end);
   2790 		entry->wired_count++;
   2791 
   2792 		/*
   2793 		 * Check for holes
   2794 		 */
   2795 
   2796 		if (entry->protection == VM_PROT_NONE ||
   2797 		    (entry->end < end &&
   2798 		     (entry->next == &map->header ||
   2799 		      entry->next->start > entry->end))) {
   2800 
   2801 			/*
   2802 			 * found one.  amap creation actions do not need to
   2803 			 * be undone, but the wired counts need to be restored.
   2804 			 */
   2805 
   2806 			while (entry != &map->header && entry->end > start) {
   2807 				entry->wired_count--;
   2808 				entry = entry->prev;
   2809 			}
   2810 			if ((lockflags & UVM_LK_EXIT) == 0)
   2811 				vm_map_unlock(map);
   2812 			UVMHIST_LOG(maphist,"<- done (INVALID WIRE)",0,0,0,0);
   2813 			return EINVAL;
   2814 		}
   2815 		entry = entry->next;
   2816 	}
   2817 
   2818 	/*
   2819 	 * Pass 2.
   2820 	 */
   2821 
   2822 #ifdef DIAGNOSTIC
   2823 	timestamp_save = map->timestamp;
   2824 #endif
   2825 	vm_map_busy(map);
   2826 	vm_map_downgrade(map);
   2827 
   2828 	rv = 0;
   2829 	entry = start_entry;
   2830 	while (entry != &map->header && entry->start < end) {
   2831 		if (entry->wired_count == 1) {
   2832 			rv = uvm_fault_wire(map, entry->start, entry->end,
   2833 			    VM_FAULT_WIREMAX, entry->max_protection);
   2834 			if (rv) {
   2835 
   2836 				/*
   2837 				 * wiring failed.  break out of the loop.
   2838 				 * we'll clean up the map below, once we
   2839 				 * have a write lock again.
   2840 				 */
   2841 
   2842 				break;
   2843 			}
   2844 		}
   2845 		entry = entry->next;
   2846 	}
   2847 
   2848 	if (rv) {	/* failed? */
   2849 
   2850 		/*
   2851 		 * Get back to an exclusive (write) lock.
   2852 		 */
   2853 
   2854 		vm_map_upgrade(map);
   2855 		vm_map_unbusy(map);
   2856 
   2857 #ifdef DIAGNOSTIC
   2858 		if (timestamp_save != map->timestamp)
   2859 			panic("uvm_map_pageable: stale map");
   2860 #endif
   2861 
   2862 		/*
   2863 		 * first drop the wiring count on all the entries
   2864 		 * which haven't actually been wired yet.
   2865 		 */
   2866 
   2867 		failed_entry = entry;
   2868 		while (entry != &map->header && entry->start < end) {
   2869 			entry->wired_count--;
   2870 			entry = entry->next;
   2871 		}
   2872 
   2873 		/*
   2874 		 * now, unwire all the entries that were successfully
   2875 		 * wired above.
   2876 		 */
   2877 
   2878 		entry = start_entry;
   2879 		while (entry != failed_entry) {
   2880 			entry->wired_count--;
   2881 			if (VM_MAPENT_ISWIRED(entry) == 0)
   2882 				uvm_map_entry_unwire(map, entry);
   2883 			entry = entry->next;
   2884 		}
   2885 		if ((lockflags & UVM_LK_EXIT) == 0)
   2886 			vm_map_unlock(map);
   2887 		UVMHIST_LOG(maphist, "<- done (RV=%d)", rv,0,0,0);
   2888 		return (rv);
   2889 	}
   2890 
   2891 	/* We are holding a read lock here. */
   2892 	if ((lockflags & UVM_LK_EXIT) == 0) {
   2893 		vm_map_unbusy(map);
   2894 		vm_map_unlock_read(map);
   2895 	} else {
   2896 
   2897 		/*
   2898 		 * Get back to an exclusive (write) lock.
   2899 		 */
   2900 
   2901 		vm_map_upgrade(map);
   2902 		vm_map_unbusy(map);
   2903 	}
   2904 
   2905 	UVMHIST_LOG(maphist,"<- done (OK WIRE)",0,0,0,0);
   2906 	return 0;
   2907 }
   2908 
   2909 /*
   2910  * uvm_map_pageable_all: special case of uvm_map_pageable - affects
   2911  * all mapped regions.
   2912  *
   2913  * => map must not be locked.
   2914  * => if no flags are specified, all regions are unwired.
   2915  * => XXXJRT: has some of the same problems as uvm_map_pageable() above.
   2916  */
   2917 
   2918 int
   2919 uvm_map_pageable_all(struct vm_map *map, int flags, vsize_t limit)
   2920 {
   2921 	struct vm_map_entry *entry, *failed_entry;
   2922 	vsize_t size;
   2923 	int rv;
   2924 #ifdef DIAGNOSTIC
   2925 	u_int timestamp_save;
   2926 #endif
   2927 	UVMHIST_FUNC("uvm_map_pageable_all"); UVMHIST_CALLED(maphist);
   2928 	UVMHIST_LOG(maphist,"(map=0x%x,flags=0x%x)", map, flags, 0, 0);
   2929 
   2930 	KASSERT(map->flags & VM_MAP_PAGEABLE);
   2931 
   2932 	vm_map_lock(map);
   2933 
   2934 	/*
   2935 	 * handle wiring and unwiring separately.
   2936 	 */
   2937 
   2938 	if (flags == 0) {			/* unwire */
   2939 
   2940 		/*
   2941 		 * POSIX 1003.1b -- munlockall unlocks all regions,
   2942 		 * regardless of how many times mlockall has been called.
   2943 		 */
   2944 
   2945 		for (entry = map->header.next; entry != &map->header;
   2946 		     entry = entry->next) {
   2947 			if (VM_MAPENT_ISWIRED(entry))
   2948 				uvm_map_entry_unwire(map, entry);
   2949 		}
   2950 		vm_map_modflags(map, 0, VM_MAP_WIREFUTURE);
   2951 		vm_map_unlock(map);
   2952 		UVMHIST_LOG(maphist,"<- done (OK UNWIRE)",0,0,0,0);
   2953 		return 0;
   2954 	}
   2955 
   2956 	if (flags & MCL_FUTURE) {
   2957 
   2958 		/*
   2959 		 * must wire all future mappings; remember this.
   2960 		 */
   2961 
   2962 		vm_map_modflags(map, VM_MAP_WIREFUTURE, 0);
   2963 	}
   2964 
   2965 	if ((flags & MCL_CURRENT) == 0) {
   2966 
   2967 		/*
   2968 		 * no more work to do!
   2969 		 */
   2970 
   2971 		UVMHIST_LOG(maphist,"<- done (OK no wire)",0,0,0,0);
   2972 		vm_map_unlock(map);
   2973 		return 0;
   2974 	}
   2975 
   2976 	/*
   2977 	 * wire case: in three passes [XXXCDC: ugly block of code here]
   2978 	 *
   2979 	 * 1: holding the write lock, count all pages mapped by non-wired
   2980 	 *    entries.  if this would cause us to go over our limit, we fail.
   2981 	 *
   2982 	 * 2: still holding the write lock, we create any anonymous maps that
   2983 	 *    need to be created.  then we increment its wiring count.
   2984 	 *
   2985 	 * 3: we downgrade to a read lock, and call uvm_fault_wire to fault
   2986 	 *    in the pages for any newly wired area (wired_count == 1).
   2987 	 *
   2988 	 *    downgrading to a read lock for uvm_fault_wire avoids a possible
   2989 	 *    deadlock with another thread that may have faulted on one of
   2990 	 *    the pages to be wired (it would mark the page busy, blocking
   2991 	 *    us, then in turn block on the map lock that we hold).  because
   2992 	 *    of problems in the recursive lock package, we cannot upgrade
   2993 	 *    to a write lock in vm_map_lookup.  thus, any actions that
   2994 	 *    require the write lock must be done beforehand.  because we
   2995 	 *    keep the read lock on the map, the copy-on-write status of the
   2996 	 *    entries we modify here cannot change.
   2997 	 */
   2998 
   2999 	for (size = 0, entry = map->header.next; entry != &map->header;
   3000 	     entry = entry->next) {
   3001 		if (entry->protection != VM_PROT_NONE &&
   3002 		    VM_MAPENT_ISWIRED(entry) == 0) { /* not already wired? */
   3003 			size += entry->end - entry->start;
   3004 		}
   3005 	}
   3006 
   3007 	if (atop(size) + uvmexp.wired > uvmexp.wiredmax) {
   3008 		vm_map_unlock(map);
   3009 		return ENOMEM;
   3010 	}
   3011 
   3012 	/* XXX non-pmap_wired_count case must be handled by caller */
   3013 #ifdef pmap_wired_count
   3014 	if (limit != 0 &&
   3015 	    (size + ptoa(pmap_wired_count(vm_map_pmap(map))) > limit)) {
   3016 		vm_map_unlock(map);
   3017 		return ENOMEM;
   3018 	}
   3019 #endif
   3020 
   3021 	/*
   3022 	 * Pass 2.
   3023 	 */
   3024 
   3025 	for (entry = map->header.next; entry != &map->header;
   3026 	     entry = entry->next) {
   3027 		if (entry->protection == VM_PROT_NONE)
   3028 			continue;
   3029 		if (VM_MAPENT_ISWIRED(entry) == 0) { /* not already wired? */
   3030 
   3031 			/*
   3032 			 * perform actions of vm_map_lookup that need the
   3033 			 * write lock on the map: create an anonymous map
   3034 			 * for a copy-on-write region, or an anonymous map
   3035 			 * for a zero-fill region.  (XXXCDC: submap case
   3036 			 * ok?)
   3037 			 */
   3038 
   3039 			if (!UVM_ET_ISSUBMAP(entry)) {	/* not submap */
   3040 				if (UVM_ET_ISNEEDSCOPY(entry) &&
   3041 				    ((entry->max_protection & VM_PROT_WRITE) ||
   3042 				     (entry->object.uvm_obj == NULL))) {
   3043 					amap_copy(map, entry, M_WAITOK, TRUE,
   3044 					    entry->start, entry->end);
   3045 					/* XXXCDC: wait OK? */
   3046 				}
   3047 			}
   3048 		}
   3049 		entry->wired_count++;
   3050 	}
   3051 
   3052 	/*
   3053 	 * Pass 3.
   3054 	 */
   3055 
   3056 #ifdef DIAGNOSTIC
   3057 	timestamp_save = map->timestamp;
   3058 #endif
   3059 	vm_map_busy(map);
   3060 	vm_map_downgrade(map);
   3061 
   3062 	rv = 0;
   3063 	for (entry = map->header.next; entry != &map->header;
   3064 	     entry = entry->next) {
   3065 		if (entry->wired_count == 1) {
   3066 			rv = uvm_fault_wire(map, entry->start, entry->end,
   3067 			    VM_FAULT_WIREMAX, entry->max_protection);
   3068 			if (rv) {
   3069 
   3070 				/*
   3071 				 * wiring failed.  break out of the loop.
   3072 				 * we'll clean up the map below, once we
   3073 				 * have a write lock again.
   3074 				 */
   3075 
   3076 				break;
   3077 			}
   3078 		}
   3079 	}
   3080 
   3081 	if (rv) {
   3082 
   3083 		/*
   3084 		 * Get back an exclusive (write) lock.
   3085 		 */
   3086 
   3087 		vm_map_upgrade(map);
   3088 		vm_map_unbusy(map);
   3089 
   3090 #ifdef DIAGNOSTIC
   3091 		if (timestamp_save != map->timestamp)
   3092 			panic("uvm_map_pageable_all: stale map");
   3093 #endif
   3094 
   3095 		/*
   3096 		 * first drop the wiring count on all the entries
   3097 		 * which haven't actually been wired yet.
   3098 		 *
   3099 		 * Skip VM_PROT_NONE entries like we did above.
   3100 		 */
   3101 
   3102 		failed_entry = entry;
   3103 		for (/* nothing */; entry != &map->header;
   3104 		     entry = entry->next) {
   3105 			if (entry->protection == VM_PROT_NONE)
   3106 				continue;
   3107 			entry->wired_count--;
   3108 		}
   3109 
   3110 		/*
   3111 		 * now, unwire all the entries that were successfully
   3112 		 * wired above.
   3113 		 *
   3114 		 * Skip VM_PROT_NONE entries like we did above.
   3115 		 */
   3116 
   3117 		for (entry = map->header.next; entry != failed_entry;
   3118 		     entry = entry->next) {
   3119 			if (entry->protection == VM_PROT_NONE)
   3120 				continue;
   3121 			entry->wired_count--;
   3122 			if (VM_MAPENT_ISWIRED(entry))
   3123 				uvm_map_entry_unwire(map, entry);
   3124 		}
   3125 		vm_map_unlock(map);
   3126 		UVMHIST_LOG(maphist,"<- done (RV=%d)", rv,0,0,0);
   3127 		return (rv);
   3128 	}
   3129 
   3130 	/* We are holding a read lock here. */
   3131 	vm_map_unbusy(map);
   3132 	vm_map_unlock_read(map);
   3133 
   3134 	UVMHIST_LOG(maphist,"<- done (OK WIRE)",0,0,0,0);
   3135 	return 0;
   3136 }
   3137 
   3138 /*
   3139  * uvm_map_clean: clean out a map range
   3140  *
   3141  * => valid flags:
   3142  *   if (flags & PGO_CLEANIT): dirty pages are cleaned first
   3143  *   if (flags & PGO_SYNCIO): dirty pages are written synchronously
   3144  *   if (flags & PGO_DEACTIVATE): any cached pages are deactivated after clean
   3145  *   if (flags & PGO_FREE): any cached pages are freed after clean
   3146  * => returns an error if any part of the specified range isn't mapped
   3147  * => never a need to flush amap layer since the anonymous memory has
   3148  *	no permanent home, but may deactivate pages there
   3149  * => called from sys_msync() and sys_madvise()
   3150  * => caller must not write-lock map (read OK).
   3151  * => we may sleep while cleaning if SYNCIO [with map read-locked]
   3152  */
   3153 
   3154 int
   3155 uvm_map_clean(struct vm_map *map, vaddr_t start, vaddr_t end, int flags)
   3156 {
   3157 	struct vm_map_entry *current, *entry;
   3158 	struct uvm_object *uobj;
   3159 	struct vm_amap *amap;
   3160 	struct vm_anon *anon;
   3161 	struct vm_page *pg;
   3162 	vaddr_t offset;
   3163 	vsize_t size;
   3164 	int error, refs;
   3165 	UVMHIST_FUNC("uvm_map_clean"); UVMHIST_CALLED(maphist);
   3166 
   3167 	UVMHIST_LOG(maphist,"(map=0x%x,start=0x%x,end=0x%x,flags=0x%x)",
   3168 		    map, start, end, flags);
   3169 	KASSERT((flags & (PGO_FREE|PGO_DEACTIVATE)) !=
   3170 		(PGO_FREE|PGO_DEACTIVATE));
   3171 
   3172 	vm_map_lock_read(map);
   3173 	VM_MAP_RANGE_CHECK(map, start, end);
   3174 	if (uvm_map_lookup_entry(map, start, &entry) == FALSE) {
   3175 		vm_map_unlock_read(map);
   3176 		return EFAULT;
   3177 	}
   3178 
   3179 	/*
   3180 	 * Make a first pass to check for holes.
   3181 	 */
   3182 
   3183 	for (current = entry; current->start < end; current = current->next) {
   3184 		if (UVM_ET_ISSUBMAP(current)) {
   3185 			vm_map_unlock_read(map);
   3186 			return EINVAL;
   3187 		}
   3188 		if (end <= current->end) {
   3189 			break;
   3190 		}
   3191 		if (current->end != current->next->start) {
   3192 			vm_map_unlock_read(map);
   3193 			return EFAULT;
   3194 		}
   3195 	}
   3196 
   3197 	error = 0;
   3198 	for (current = entry; start < end; current = current->next) {
   3199 		amap = current->aref.ar_amap;	/* top layer */
   3200 		uobj = current->object.uvm_obj;	/* bottom layer */
   3201 		KASSERT(start >= current->start);
   3202 
   3203 		/*
   3204 		 * No amap cleaning necessary if:
   3205 		 *
   3206 		 *	(1) There's no amap.
   3207 		 *
   3208 		 *	(2) We're not deactivating or freeing pages.
   3209 		 */
   3210 
   3211 		if (amap == NULL || (flags & (PGO_DEACTIVATE|PGO_FREE)) == 0)
   3212 			goto flush_object;
   3213 
   3214 		amap_lock(amap);
   3215 		offset = start - current->start;
   3216 		size = MIN(end, current->end) - start;
   3217 		for ( ; size != 0; size -= PAGE_SIZE, offset += PAGE_SIZE) {
   3218 			anon = amap_lookup(&current->aref, offset);
   3219 			if (anon == NULL)
   3220 				continue;
   3221 
   3222 			simple_lock(&anon->an_lock);
   3223 			pg = anon->u.an_page;
   3224 			if (pg == NULL) {
   3225 				simple_unlock(&anon->an_lock);
   3226 				continue;
   3227 			}
   3228 
   3229 			switch (flags & (PGO_CLEANIT|PGO_FREE|PGO_DEACTIVATE)) {
   3230 
   3231 			/*
   3232 			 * In these first 3 cases, we just deactivate the page.
   3233 			 */
   3234 
   3235 			case PGO_CLEANIT|PGO_FREE:
   3236 			case PGO_CLEANIT|PGO_DEACTIVATE:
   3237 			case PGO_DEACTIVATE:
   3238  deactivate_it:
   3239 				/*
   3240 				 * skip the page if it's loaned or wired,
   3241 				 * since it shouldn't be on a paging queue
   3242 				 * at all in these cases.
   3243 				 */
   3244 
   3245 				uvm_lock_pageq();
   3246 				if (pg->loan_count != 0 ||
   3247 				    pg->wire_count != 0) {
   3248 					uvm_unlock_pageq();
   3249 					simple_unlock(&anon->an_lock);
   3250 					continue;
   3251 				}
   3252 				KASSERT(pg->uanon == anon);
   3253 				pmap_clear_reference(pg);
   3254 				uvm_pagedeactivate(pg);
   3255 				uvm_unlock_pageq();
   3256 				simple_unlock(&anon->an_lock);
   3257 				continue;
   3258 
   3259 			case PGO_FREE:
   3260 
   3261 				/*
   3262 				 * If there are multiple references to
   3263 				 * the amap, just deactivate the page.
   3264 				 */
   3265 
   3266 				if (amap_refs(amap) > 1)
   3267 					goto deactivate_it;
   3268 
   3269 				/* skip the page if it's wired */
   3270 				if (pg->wire_count != 0) {
   3271 					simple_unlock(&anon->an_lock);
   3272 					continue;
   3273 				}
   3274 				amap_unadd(&current->aref, offset);
   3275 				refs = --anon->an_ref;
   3276 				simple_unlock(&anon->an_lock);
   3277 				if (refs == 0)
   3278 					uvm_anfree(anon);
   3279 				continue;
   3280 			}
   3281 		}
   3282 		amap_unlock(amap);
   3283 
   3284  flush_object:
   3285 		/*
   3286 		 * flush pages if we've got a valid backing object.
   3287 		 * note that we must always clean object pages before
   3288 		 * freeing them since otherwise we could reveal stale
   3289 		 * data from files.
   3290 		 */
   3291 
   3292 		offset = current->offset + (start - current->start);
   3293 		size = MIN(end, current->end) - start;
   3294 		if (uobj != NULL) {
   3295 			simple_lock(&uobj->vmobjlock);
   3296 			if (uobj->pgops->pgo_put != NULL)
   3297 				error = (uobj->pgops->pgo_put)(uobj, offset,
   3298 				    offset + size, flags | PGO_CLEANIT);
   3299 			else
   3300 				error = 0;
   3301 		}
   3302 		start += size;
   3303 	}
   3304 	vm_map_unlock_read(map);
   3305 	return (error);
   3306 }
   3307 
   3308 
   3309 /*
   3310  * uvm_map_checkprot: check protection in map
   3311  *
   3312  * => must allow specified protection in a fully allocated region.
   3313  * => map must be read or write locked by caller.
   3314  */
   3315 
   3316 boolean_t
   3317 uvm_map_checkprot(struct vm_map *map, vaddr_t start, vaddr_t end,
   3318     vm_prot_t protection)
   3319 {
   3320 	struct vm_map_entry *entry;
   3321 	struct vm_map_entry *tmp_entry;
   3322 
   3323 	if (!uvm_map_lookup_entry(map, start, &tmp_entry)) {
   3324 		return (FALSE);
   3325 	}
   3326 	entry = tmp_entry;
   3327 	while (start < end) {
   3328 		if (entry == &map->header) {
   3329 			return (FALSE);
   3330 		}
   3331 
   3332 		/*
   3333 		 * no holes allowed
   3334 		 */
   3335 
   3336 		if (start < entry->start) {
   3337 			return (FALSE);
   3338 		}
   3339 
   3340 		/*
   3341 		 * check protection associated with entry
   3342 		 */
   3343 
   3344 		if ((entry->protection & protection) != protection) {
   3345 			return (FALSE);
   3346 		}
   3347 		start = entry->end;
   3348 		entry = entry->next;
   3349 	}
   3350 	return (TRUE);
   3351 }
   3352 
   3353 /*
   3354  * uvmspace_alloc: allocate a vmspace structure.
   3355  *
   3356  * - structure includes vm_map and pmap
   3357  * - XXX: no locking on this structure
   3358  * - refcnt set to 1, rest must be init'd by caller
   3359  */
   3360 struct vmspace *
   3361 uvmspace_alloc(vaddr_t min, vaddr_t max)
   3362 {
   3363 	struct vmspace *vm;
   3364 	UVMHIST_FUNC("uvmspace_alloc"); UVMHIST_CALLED(maphist);
   3365 
   3366 	vm = pool_get(&uvm_vmspace_pool, PR_WAITOK);
   3367 	uvmspace_init(vm, NULL, min, max);
   3368 	UVMHIST_LOG(maphist,"<- done (vm=0x%x)", vm,0,0,0);
   3369 	return (vm);
   3370 }
   3371 
   3372 /*
   3373  * uvmspace_init: initialize a vmspace structure.
   3374  *
   3375  * - XXX: no locking on this structure
   3376  * - refcnt set to 1, rest must be init'd by caller
   3377  */
   3378 void
   3379 uvmspace_init(struct vmspace *vm, struct pmap *pmap, vaddr_t min, vaddr_t max)
   3380 {
   3381 	UVMHIST_FUNC("uvmspace_init"); UVMHIST_CALLED(maphist);
   3382 
   3383 	memset(vm, 0, sizeof(*vm));
   3384 	uvm_map_setup(&vm->vm_map, min, max, VM_MAP_PAGEABLE
   3385 #ifdef __USING_TOPDOWN_VM
   3386 	    | VM_MAP_TOPDOWN
   3387 #endif
   3388 	    );
   3389 	if (pmap)
   3390 		pmap_reference(pmap);
   3391 	else
   3392 		pmap = pmap_create();
   3393 	vm->vm_map.pmap = pmap;
   3394 	vm->vm_refcnt = 1;
   3395 	UVMHIST_LOG(maphist,"<- done",0,0,0,0);
   3396 }
   3397 
   3398 /*
   3399  * uvmspace_share: share a vmspace between two proceses
   3400  *
   3401  * - XXX: no locking on vmspace
   3402  * - used for vfork, threads(?)
   3403  */
   3404 
   3405 void
   3406 uvmspace_share(struct proc *p1, struct proc *p2)
   3407 {
   3408 
   3409 	p2->p_vmspace = p1->p_vmspace;
   3410 	p1->p_vmspace->vm_refcnt++;
   3411 }
   3412 
   3413 /*
   3414  * uvmspace_unshare: ensure that process "p" has its own, unshared, vmspace
   3415  *
   3416  * - XXX: no locking on vmspace
   3417  */
   3418 
   3419 void
   3420 uvmspace_unshare(struct lwp *l)
   3421 {
   3422 	struct proc *p = l->l_proc;
   3423 	struct vmspace *nvm, *ovm = p->p_vmspace;
   3424 
   3425 	if (ovm->vm_refcnt == 1)
   3426 		/* nothing to do: vmspace isn't shared in the first place */
   3427 		return;
   3428 
   3429 	/* make a new vmspace, still holding old one */
   3430 	nvm = uvmspace_fork(ovm);
   3431 
   3432 	pmap_deactivate(l);		/* unbind old vmspace */
   3433 	p->p_vmspace = nvm;
   3434 	pmap_activate(l);		/* switch to new vmspace */
   3435 
   3436 	uvmspace_free(ovm);		/* drop reference to old vmspace */
   3437 }
   3438 
   3439 /*
   3440  * uvmspace_exec: the process wants to exec a new program
   3441  *
   3442  * - XXX: no locking on vmspace
   3443  */
   3444 
   3445 void
   3446 uvmspace_exec(struct lwp *l, vaddr_t start, vaddr_t end)
   3447 {
   3448 	struct proc *p = l->l_proc;
   3449 	struct vmspace *nvm, *ovm = p->p_vmspace;
   3450 	struct vm_map *map = &ovm->vm_map;
   3451 
   3452 #ifdef __sparc__
   3453 	/* XXX cgd 960926: the sparc #ifdef should be a MD hook */
   3454 	kill_user_windows(l);   /* before stack addresses go away */
   3455 #endif
   3456 
   3457 	/*
   3458 	 * see if more than one process is using this vmspace...
   3459 	 */
   3460 
   3461 	if (ovm->vm_refcnt == 1) {
   3462 
   3463 		/*
   3464 		 * if p is the only process using its vmspace then we can safely
   3465 		 * recycle that vmspace for the program that is being exec'd.
   3466 		 */
   3467 
   3468 #ifdef SYSVSHM
   3469 		/*
   3470 		 * SYSV SHM semantics require us to kill all segments on an exec
   3471 		 */
   3472 
   3473 		if (ovm->vm_shm)
   3474 			shmexit(ovm);
   3475 #endif
   3476 
   3477 		/*
   3478 		 * POSIX 1003.1b -- "lock future mappings" is revoked
   3479 		 * when a process execs another program image.
   3480 		 */
   3481 
   3482 		vm_map_modflags(map, 0, VM_MAP_WIREFUTURE);
   3483 
   3484 		/*
   3485 		 * now unmap the old program
   3486 		 */
   3487 
   3488 		pmap_remove_all(map->pmap);
   3489 		uvm_unmap(map, map->min_offset, map->max_offset);
   3490 		KASSERT(map->header.prev == &map->header);
   3491 		KASSERT(map->nentries == 0);
   3492 
   3493 		/*
   3494 		 * resize the map
   3495 		 */
   3496 
   3497 		map->min_offset = start;
   3498 		map->max_offset = end;
   3499 	} else {
   3500 
   3501 		/*
   3502 		 * p's vmspace is being shared, so we can't reuse it for p since
   3503 		 * it is still being used for others.   allocate a new vmspace
   3504 		 * for p
   3505 		 */
   3506 
   3507 		nvm = uvmspace_alloc(start, end);
   3508 
   3509 		/*
   3510 		 * install new vmspace and drop our ref to the old one.
   3511 		 */
   3512 
   3513 		pmap_deactivate(l);
   3514 		p->p_vmspace = nvm;
   3515 		pmap_activate(l);
   3516 
   3517 		uvmspace_free(ovm);
   3518 	}
   3519 }
   3520 
   3521 /*
   3522  * uvmspace_free: free a vmspace data structure
   3523  *
   3524  * - XXX: no locking on vmspace
   3525  */
   3526 
   3527 void
   3528 uvmspace_free(struct vmspace *vm)
   3529 {
   3530 	struct vm_map_entry *dead_entries;
   3531 	struct vm_map *map;
   3532 	UVMHIST_FUNC("uvmspace_free"); UVMHIST_CALLED(maphist);
   3533 
   3534 	UVMHIST_LOG(maphist,"(vm=0x%x) ref=%d", vm, vm->vm_refcnt,0,0);
   3535 	if (--vm->vm_refcnt > 0) {
   3536 		return;
   3537 	}
   3538 
   3539 	/*
   3540 	 * at this point, there should be no other references to the map.
   3541 	 * delete all of the mappings, then destroy the pmap.
   3542 	 */
   3543 
   3544 	map = &vm->vm_map;
   3545 	map->flags |= VM_MAP_DYING;
   3546 	pmap_remove_all(map->pmap);
   3547 #ifdef SYSVSHM
   3548 	/* Get rid of any SYSV shared memory segments. */
   3549 	if (vm->vm_shm != NULL)
   3550 		shmexit(vm);
   3551 #endif
   3552 	if (map->nentries) {
   3553 		uvm_unmap_remove(map, map->min_offset, map->max_offset,
   3554 		    &dead_entries);
   3555 		if (dead_entries != NULL)
   3556 			uvm_unmap_detach(dead_entries, 0);
   3557 	}
   3558 	KASSERT(map->nentries == 0);
   3559 	KASSERT(map->size == 0);
   3560 	pmap_destroy(map->pmap);
   3561 	pool_put(&uvm_vmspace_pool, vm);
   3562 }
   3563 
   3564 /*
   3565  *   F O R K   -   m a i n   e n t r y   p o i n t
   3566  */
   3567 /*
   3568  * uvmspace_fork: fork a process' main map
   3569  *
   3570  * => create a new vmspace for child process from parent.
   3571  * => parent's map must not be locked.
   3572  */
   3573 
   3574 struct vmspace *
   3575 uvmspace_fork(struct vmspace *vm1)
   3576 {
   3577 	struct vmspace *vm2;
   3578 	struct vm_map *old_map = &vm1->vm_map;
   3579 	struct vm_map *new_map;
   3580 	struct vm_map_entry *old_entry;
   3581 	struct vm_map_entry *new_entry;
   3582 	UVMHIST_FUNC("uvmspace_fork"); UVMHIST_CALLED(maphist);
   3583 
   3584 	vm_map_lock(old_map);
   3585 
   3586 	vm2 = uvmspace_alloc(old_map->min_offset, old_map->max_offset);
   3587 	memcpy(&vm2->vm_startcopy, &vm1->vm_startcopy,
   3588 	    (caddr_t) (vm1 + 1) - (caddr_t) &vm1->vm_startcopy);
   3589 	new_map = &vm2->vm_map;		  /* XXX */
   3590 
   3591 	old_entry = old_map->header.next;
   3592 
   3593 	/*
   3594 	 * go entry-by-entry
   3595 	 */
   3596 
   3597 	while (old_entry != &old_map->header) {
   3598 
   3599 		/*
   3600 		 * first, some sanity checks on the old entry
   3601 		 */
   3602 
   3603 		KASSERT(!UVM_ET_ISSUBMAP(old_entry));
   3604 		KASSERT(UVM_ET_ISCOPYONWRITE(old_entry) ||
   3605 			!UVM_ET_ISNEEDSCOPY(old_entry));
   3606 
   3607 		switch (old_entry->inheritance) {
   3608 		case MAP_INHERIT_NONE:
   3609 
   3610 			/*
   3611 			 * drop the mapping
   3612 			 */
   3613 
   3614 			break;
   3615 
   3616 		case MAP_INHERIT_SHARE:
   3617 
   3618 			/*
   3619 			 * share the mapping: this means we want the old and
   3620 			 * new entries to share amaps and backing objects.
   3621 			 */
   3622 			/*
   3623 			 * if the old_entry needs a new amap (due to prev fork)
   3624 			 * then we need to allocate it now so that we have
   3625 			 * something we own to share with the new_entry.   [in
   3626 			 * other words, we need to clear needs_copy]
   3627 			 */
   3628 
   3629 			if (UVM_ET_ISNEEDSCOPY(old_entry)) {
   3630 				/* get our own amap, clears needs_copy */
   3631 				amap_copy(old_map, old_entry, M_WAITOK, FALSE,
   3632 				    0, 0);
   3633 				/* XXXCDC: WAITOK??? */
   3634 			}
   3635 
   3636 			new_entry = uvm_mapent_alloc(new_map, 0);
   3637 			/* old_entry -> new_entry */
   3638 			uvm_mapent_copy(old_entry, new_entry);
   3639 
   3640 			/* new pmap has nothing wired in it */
   3641 			new_entry->wired_count = 0;
   3642 
   3643 			/*
   3644 			 * gain reference to object backing the map (can't
   3645 			 * be a submap, already checked this case).
   3646 			 */
   3647 
   3648 			if (new_entry->aref.ar_amap)
   3649 				uvm_map_reference_amap(new_entry, AMAP_SHARED);
   3650 
   3651 			if (new_entry->object.uvm_obj &&
   3652 			    new_entry->object.uvm_obj->pgops->pgo_reference)
   3653 				new_entry->object.uvm_obj->
   3654 				    pgops->pgo_reference(
   3655 				        new_entry->object.uvm_obj);
   3656 
   3657 			/* insert entry at end of new_map's entry list */
   3658 			uvm_map_entry_link(new_map, new_map->header.prev,
   3659 			    new_entry);
   3660 
   3661 			break;
   3662 
   3663 		case MAP_INHERIT_COPY:
   3664 
   3665 			/*
   3666 			 * copy-on-write the mapping (using mmap's
   3667 			 * MAP_PRIVATE semantics)
   3668 			 *
   3669 			 * allocate new_entry, adjust reference counts.
   3670 			 * (note that new references are read-only).
   3671 			 */
   3672 
   3673 			new_entry = uvm_mapent_alloc(new_map, 0);
   3674 			/* old_entry -> new_entry */
   3675 			uvm_mapent_copy(old_entry, new_entry);
   3676 
   3677 			if (new_entry->aref.ar_amap)
   3678 				uvm_map_reference_amap(new_entry, 0);
   3679 
   3680 			if (new_entry->object.uvm_obj &&
   3681 			    new_entry->object.uvm_obj->pgops->pgo_reference)
   3682 				new_entry->object.uvm_obj->pgops->pgo_reference
   3683 				    (new_entry->object.uvm_obj);
   3684 
   3685 			/* new pmap has nothing wired in it */
   3686 			new_entry->wired_count = 0;
   3687 
   3688 			new_entry->etype |=
   3689 			    (UVM_ET_COPYONWRITE|UVM_ET_NEEDSCOPY);
   3690 			uvm_map_entry_link(new_map, new_map->header.prev,
   3691 			    new_entry);
   3692 
   3693 			/*
   3694 			 * the new entry will need an amap.  it will either
   3695 			 * need to be copied from the old entry or created
   3696 			 * from scratch (if the old entry does not have an
   3697 			 * amap).  can we defer this process until later
   3698 			 * (by setting "needs_copy") or do we need to copy
   3699 			 * the amap now?
   3700 			 *
   3701 			 * we must copy the amap now if any of the following
   3702 			 * conditions hold:
   3703 			 * 1. the old entry has an amap and that amap is
   3704 			 *    being shared.  this means that the old (parent)
   3705 			 *    process is sharing the amap with another
   3706 			 *    process.  if we do not clear needs_copy here
   3707 			 *    we will end up in a situation where both the
   3708 			 *    parent and child process are refering to the
   3709 			 *    same amap with "needs_copy" set.  if the
   3710 			 *    parent write-faults, the fault routine will
   3711 			 *    clear "needs_copy" in the parent by allocating
   3712 			 *    a new amap.   this is wrong because the
   3713 			 *    parent is supposed to be sharing the old amap
   3714 			 *    and the new amap will break that.
   3715 			 *
   3716 			 * 2. if the old entry has an amap and a non-zero
   3717 			 *    wire count then we are going to have to call
   3718 			 *    amap_cow_now to avoid page faults in the
   3719 			 *    parent process.   since amap_cow_now requires
   3720 			 *    "needs_copy" to be clear we might as well
   3721 			 *    clear it here as well.
   3722 			 *
   3723 			 */
   3724 
   3725 			if (old_entry->aref.ar_amap != NULL) {
   3726 				if ((amap_flags(old_entry->aref.ar_amap) &
   3727 				     AMAP_SHARED) != 0 ||
   3728 				    VM_MAPENT_ISWIRED(old_entry)) {
   3729 
   3730 					amap_copy(new_map, new_entry, M_WAITOK,
   3731 					    FALSE, 0, 0);
   3732 					/* XXXCDC: M_WAITOK ... ok? */
   3733 				}
   3734 			}
   3735 
   3736 			/*
   3737 			 * if the parent's entry is wired down, then the
   3738 			 * parent process does not want page faults on
   3739 			 * access to that memory.  this means that we
   3740 			 * cannot do copy-on-write because we can't write
   3741 			 * protect the old entry.   in this case we
   3742 			 * resolve all copy-on-write faults now, using
   3743 			 * amap_cow_now.   note that we have already
   3744 			 * allocated any needed amap (above).
   3745 			 */
   3746 
   3747 			if (VM_MAPENT_ISWIRED(old_entry)) {
   3748 
   3749 			  /*
   3750 			   * resolve all copy-on-write faults now
   3751 			   * (note that there is nothing to do if
   3752 			   * the old mapping does not have an amap).
   3753 			   */
   3754 			  if (old_entry->aref.ar_amap)
   3755 			    amap_cow_now(new_map, new_entry);
   3756 
   3757 			} else {
   3758 
   3759 			  /*
   3760 			   * setup mappings to trigger copy-on-write faults
   3761 			   * we must write-protect the parent if it has
   3762 			   * an amap and it is not already "needs_copy"...
   3763 			   * if it is already "needs_copy" then the parent
   3764 			   * has already been write-protected by a previous
   3765 			   * fork operation.
   3766 			   */
   3767 
   3768 			  if (old_entry->aref.ar_amap &&
   3769 			      !UVM_ET_ISNEEDSCOPY(old_entry)) {
   3770 			      if (old_entry->max_protection & VM_PROT_WRITE) {
   3771 				pmap_protect(old_map->pmap,
   3772 					     old_entry->start,
   3773 					     old_entry->end,
   3774 					     old_entry->protection &
   3775 					     ~VM_PROT_WRITE);
   3776 				pmap_update(old_map->pmap);
   3777 			      }
   3778 			      old_entry->etype |= UVM_ET_NEEDSCOPY;
   3779 			  }
   3780 			}
   3781 			break;
   3782 		}  /* end of switch statement */
   3783 		old_entry = old_entry->next;
   3784 	}
   3785 
   3786 	new_map->size = old_map->size;
   3787 	vm_map_unlock(old_map);
   3788 
   3789 #ifdef SYSVSHM
   3790 	if (vm1->vm_shm)
   3791 		shmfork(vm1, vm2);
   3792 #endif
   3793 
   3794 #ifdef PMAP_FORK
   3795 	pmap_fork(vm1->vm_map.pmap, vm2->vm_map.pmap);
   3796 #endif
   3797 
   3798 	UVMHIST_LOG(maphist,"<- done",0,0,0,0);
   3799 	return (vm2);
   3800 }
   3801 
   3802 
   3803 #if defined(DDB)
   3804 
   3805 /*
   3806  * DDB hooks
   3807  */
   3808 
   3809 /*
   3810  * uvm_map_printit: actually prints the map
   3811  */
   3812 
   3813 void
   3814 uvm_map_printit(struct vm_map *map, boolean_t full,
   3815     void (*pr)(const char *, ...))
   3816 {
   3817 	struct vm_map_entry *entry;
   3818 
   3819 	(*pr)("MAP %p: [0x%lx->0x%lx]\n", map, map->min_offset,map->max_offset);
   3820 	(*pr)("\t#ent=%d, sz=%d, ref=%d, version=%d, flags=0x%x\n",
   3821 	    map->nentries, map->size, map->ref_count, map->timestamp,
   3822 	    map->flags);
   3823 	(*pr)("\tpmap=%p(resident=%d)\n", map->pmap,
   3824 	    pmap_resident_count(map->pmap));
   3825 	if (!full)
   3826 		return;
   3827 	for (entry = map->header.next; entry != &map->header;
   3828 	    entry = entry->next) {
   3829 		(*pr)(" - %p: 0x%lx->0x%lx: obj=%p/0x%llx, amap=%p/%d\n",
   3830 		    entry, entry->start, entry->end, entry->object.uvm_obj,
   3831 		    (long long)entry->offset, entry->aref.ar_amap,
   3832 		    entry->aref.ar_pageoff);
   3833 		(*pr)(
   3834 		    "\tsubmap=%c, cow=%c, nc=%c, prot(max)=%d/%d, inh=%d, "
   3835 		    "wc=%d, adv=%d\n",
   3836 		    (entry->etype & UVM_ET_SUBMAP) ? 'T' : 'F',
   3837 		    (entry->etype & UVM_ET_COPYONWRITE) ? 'T' : 'F',
   3838 		    (entry->etype & UVM_ET_NEEDSCOPY) ? 'T' : 'F',
   3839 		    entry->protection, entry->max_protection,
   3840 		    entry->inheritance, entry->wired_count, entry->advice);
   3841 	}
   3842 }
   3843 
   3844 /*
   3845  * uvm_object_printit: actually prints the object
   3846  */
   3847 
   3848 void
   3849 uvm_object_printit(struct uvm_object *uobj, boolean_t full,
   3850     void (*pr)(const char *, ...))
   3851 {
   3852 	struct vm_page *pg;
   3853 	int cnt = 0;
   3854 
   3855 	(*pr)("OBJECT %p: locked=%d, pgops=%p, npages=%d, ",
   3856 	    uobj, uobj->vmobjlock.lock_data, uobj->pgops, uobj->uo_npages);
   3857 	if (UVM_OBJ_IS_KERN_OBJECT(uobj))
   3858 		(*pr)("refs=<SYSTEM>\n");
   3859 	else
   3860 		(*pr)("refs=%d\n", uobj->uo_refs);
   3861 
   3862 	if (!full) {
   3863 		return;
   3864 	}
   3865 	(*pr)("  PAGES <pg,offset>:\n  ");
   3866 	TAILQ_FOREACH(pg, &uobj->memq, listq) {
   3867 		cnt++;
   3868 		(*pr)("<%p,0x%llx> ", pg, (long long)pg->offset);
   3869 		if ((cnt % 3) == 0) {
   3870 			(*pr)("\n  ");
   3871 		}
   3872 	}
   3873 	if ((cnt % 3) != 0) {
   3874 		(*pr)("\n");
   3875 	}
   3876 }
   3877 
   3878 /*
   3879  * uvm_page_printit: actually print the page
   3880  */
   3881 
   3882 static const char page_flagbits[] =
   3883 	"\20\1BUSY\2WANTED\3TABLED\4CLEAN\5PAGEOUT\6RELEASED\7FAKE\10RDONLY"
   3884 	"\11ZERO\15PAGER1";
   3885 static const char page_pqflagbits[] =
   3886 	"\20\1FREE\2INACTIVE\3ACTIVE\5ANON\6AOBJ";
   3887 
   3888 void
   3889 uvm_page_printit(struct vm_page *pg, boolean_t full,
   3890     void (*pr)(const char *, ...))
   3891 {
   3892 	struct vm_page *tpg;
   3893 	struct uvm_object *uobj;
   3894 	struct pglist *pgl;
   3895 	char pgbuf[128];
   3896 	char pqbuf[128];
   3897 
   3898 	(*pr)("PAGE %p:\n", pg);
   3899 	bitmask_snprintf(pg->flags, page_flagbits, pgbuf, sizeof(pgbuf));
   3900 	bitmask_snprintf(pg->pqflags, page_pqflagbits, pqbuf, sizeof(pqbuf));
   3901 	(*pr)("  flags=%s, pqflags=%s, wire_count=%d, pa=0x%lx\n",
   3902 	    pgbuf, pqbuf, pg->wire_count, (long)VM_PAGE_TO_PHYS(pg));
   3903 	(*pr)("  uobject=%p, uanon=%p, offset=0x%llx loan_count=%d\n",
   3904 	    pg->uobject, pg->uanon, (long long)pg->offset, pg->loan_count);
   3905 #if defined(UVM_PAGE_TRKOWN)
   3906 	if (pg->flags & PG_BUSY)
   3907 		(*pr)("  owning process = %d, tag=%s\n",
   3908 		    pg->owner, pg->owner_tag);
   3909 	else
   3910 		(*pr)("  page not busy, no owner\n");
   3911 #else
   3912 	(*pr)("  [page ownership tracking disabled]\n");
   3913 #endif
   3914 
   3915 	if (!full)
   3916 		return;
   3917 
   3918 	/* cross-verify object/anon */
   3919 	if ((pg->pqflags & PQ_FREE) == 0) {
   3920 		if (pg->pqflags & PQ_ANON) {
   3921 			if (pg->uanon == NULL || pg->uanon->u.an_page != pg)
   3922 			    (*pr)("  >>> ANON DOES NOT POINT HERE <<< (%p)\n",
   3923 				(pg->uanon) ? pg->uanon->u.an_page : NULL);
   3924 			else
   3925 				(*pr)("  anon backpointer is OK\n");
   3926 		} else {
   3927 			uobj = pg->uobject;
   3928 			if (uobj) {
   3929 				(*pr)("  checking object list\n");
   3930 				TAILQ_FOREACH(tpg, &uobj->memq, listq) {
   3931 					if (tpg == pg) {
   3932 						break;
   3933 					}
   3934 				}
   3935 				if (tpg)
   3936 					(*pr)("  page found on object list\n");
   3937 				else
   3938 			(*pr)("  >>> PAGE NOT FOUND ON OBJECT LIST! <<<\n");
   3939 			}
   3940 		}
   3941 	}
   3942 
   3943 	/* cross-verify page queue */
   3944 	if (pg->pqflags & PQ_FREE) {
   3945 		int fl = uvm_page_lookup_freelist(pg);
   3946 		int color = VM_PGCOLOR_BUCKET(pg);
   3947 		pgl = &uvm.page_free[fl].pgfl_buckets[color].pgfl_queues[
   3948 		    ((pg)->flags & PG_ZERO) ? PGFL_ZEROS : PGFL_UNKNOWN];
   3949 	} else if (pg->pqflags & PQ_INACTIVE) {
   3950 		pgl = &uvm.page_inactive;
   3951 	} else if (pg->pqflags & PQ_ACTIVE) {
   3952 		pgl = &uvm.page_active;
   3953 	} else {
   3954 		pgl = NULL;
   3955 	}
   3956 
   3957 	if (pgl) {
   3958 		(*pr)("  checking pageq list\n");
   3959 		TAILQ_FOREACH(tpg, pgl, pageq) {
   3960 			if (tpg == pg) {
   3961 				break;
   3962 			}
   3963 		}
   3964 		if (tpg)
   3965 			(*pr)("  page found on pageq list\n");
   3966 		else
   3967 			(*pr)("  >>> PAGE NOT FOUND ON PAGEQ LIST! <<<\n");
   3968 	}
   3969 }
   3970 #endif
   3971