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