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