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