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