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