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