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