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