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