xref: /freebsd/sys/vm/vm_map.c (revision e653b48c80fb85b2a10372d664a4b55dbdc51dae)
1 /*
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * The Mach Operating System project at Carnegie-Mellon University.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	from: @(#)vm_map.c	8.3 (Berkeley) 1/12/94
33  *
34  *
35  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
36  * All rights reserved.
37  *
38  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
39  *
40  * Permission to use, copy, modify and distribute this software and
41  * its documentation is hereby granted, provided that both the copyright
42  * notice and this permission notice appear in all copies of the
43  * software, derivative works or modified versions, and any portions
44  * thereof, and that both notices appear in supporting documentation.
45  *
46  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
47  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
48  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
49  *
50  * Carnegie Mellon requests users of this software to return to
51  *
52  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
53  *  School of Computer Science
54  *  Carnegie Mellon University
55  *  Pittsburgh PA 15213-3890
56  *
57  * any improvements or extensions that they make and grant Carnegie the
58  * rights to redistribute these changes.
59  */
60 
61 /*
62  *	Virtual memory mapping module.
63  */
64 
65 #include <sys/cdefs.h>
66 __FBSDID("$FreeBSD$");
67 
68 #include <sys/param.h>
69 #include <sys/systm.h>
70 #include <sys/ktr.h>
71 #include <sys/lock.h>
72 #include <sys/mutex.h>
73 #include <sys/proc.h>
74 #include <sys/vmmeter.h>
75 #include <sys/mman.h>
76 #include <sys/vnode.h>
77 #include <sys/resourcevar.h>
78 #include <sys/file.h>
79 #include <sys/sysent.h>
80 #include <sys/shm.h>
81 
82 #include <vm/vm.h>
83 #include <vm/vm_param.h>
84 #include <vm/pmap.h>
85 #include <vm/vm_map.h>
86 #include <vm/vm_page.h>
87 #include <vm/vm_object.h>
88 #include <vm/vm_pager.h>
89 #include <vm/vm_kern.h>
90 #include <vm/vm_extern.h>
91 #include <vm/swap_pager.h>
92 #include <vm/uma.h>
93 
94 /*
95  *	Virtual memory maps provide for the mapping, protection,
96  *	and sharing of virtual memory objects.  In addition,
97  *	this module provides for an efficient virtual copy of
98  *	memory from one map to another.
99  *
100  *	Synchronization is required prior to most operations.
101  *
102  *	Maps consist of an ordered doubly-linked list of simple
103  *	entries; a single hint is used to speed up lookups.
104  *
105  *	Since portions of maps are specified by start/end addresses,
106  *	which may not align with existing map entries, all
107  *	routines merely "clip" entries to these start/end values.
108  *	[That is, an entry is split into two, bordering at a
109  *	start or end value.]  Note that these clippings may not
110  *	always be necessary (as the two resulting entries are then
111  *	not changed); however, the clipping is done for convenience.
112  *
113  *	As mentioned above, virtual copy operations are performed
114  *	by copying VM object references from one map to
115  *	another, and then marking both regions as copy-on-write.
116  */
117 
118 /*
119  *	vm_map_startup:
120  *
121  *	Initialize the vm_map module.  Must be called before
122  *	any other vm_map routines.
123  *
124  *	Map and entry structures are allocated from the general
125  *	purpose memory pool with some exceptions:
126  *
127  *	- The kernel map and kmem submap are allocated statically.
128  *	- Kernel map entries are allocated out of a static pool.
129  *
130  *	These restrictions are necessary since malloc() uses the
131  *	maps and requires map entries.
132  */
133 
134 static struct mtx map_sleep_mtx;
135 static uma_zone_t mapentzone;
136 static uma_zone_t kmapentzone;
137 static uma_zone_t mapzone;
138 static uma_zone_t vmspace_zone;
139 static struct vm_object kmapentobj;
140 static int vmspace_zinit(void *mem, int size, int flags);
141 static void vmspace_zfini(void *mem, int size);
142 static int vm_map_zinit(void *mem, int ize, int flags);
143 static void vm_map_zfini(void *mem, int size);
144 static void _vm_map_init(vm_map_t map, vm_offset_t min, vm_offset_t max);
145 
146 #ifdef INVARIANTS
147 static void vm_map_zdtor(void *mem, int size, void *arg);
148 static void vmspace_zdtor(void *mem, int size, void *arg);
149 #endif
150 
151 void
152 vm_map_startup(void)
153 {
154 	mtx_init(&map_sleep_mtx, "vm map sleep mutex", NULL, MTX_DEF);
155 	mapzone = uma_zcreate("MAP", sizeof(struct vm_map), NULL,
156 #ifdef INVARIANTS
157 	    vm_map_zdtor,
158 #else
159 	    NULL,
160 #endif
161 	    vm_map_zinit, vm_map_zfini, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
162 	uma_prealloc(mapzone, MAX_KMAP);
163 	kmapentzone = uma_zcreate("KMAP ENTRY", sizeof(struct vm_map_entry),
164 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
165 	    UMA_ZONE_MTXCLASS | UMA_ZONE_VM);
166 	uma_prealloc(kmapentzone, MAX_KMAPENT);
167 	mapentzone = uma_zcreate("MAP ENTRY", sizeof(struct vm_map_entry),
168 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
169 	uma_prealloc(mapentzone, MAX_MAPENT);
170 }
171 
172 static void
173 vmspace_zfini(void *mem, int size)
174 {
175 	struct vmspace *vm;
176 
177 	vm = (struct vmspace *)mem;
178 	pmap_release(vmspace_pmap(vm));
179 	vm_map_zfini(&vm->vm_map, sizeof(vm->vm_map));
180 }
181 
182 static int
183 vmspace_zinit(void *mem, int size, int flags)
184 {
185 	struct vmspace *vm;
186 
187 	vm = (struct vmspace *)mem;
188 
189 	(void)vm_map_zinit(&vm->vm_map, sizeof(vm->vm_map), flags);
190 	pmap_pinit(vmspace_pmap(vm));
191 	return (0);
192 }
193 
194 static void
195 vm_map_zfini(void *mem, int size)
196 {
197 	vm_map_t map;
198 
199 	map = (vm_map_t)mem;
200 	mtx_destroy(&map->system_mtx);
201 	sx_destroy(&map->lock);
202 }
203 
204 static int
205 vm_map_zinit(void *mem, int size, int flags)
206 {
207 	vm_map_t map;
208 
209 	map = (vm_map_t)mem;
210 	map->nentries = 0;
211 	map->size = 0;
212 	mtx_init(&map->system_mtx, "system map", NULL, MTX_DEF | MTX_DUPOK);
213 	sx_init(&map->lock, "user map");
214 	return (0);
215 }
216 
217 #ifdef INVARIANTS
218 static void
219 vmspace_zdtor(void *mem, int size, void *arg)
220 {
221 	struct vmspace *vm;
222 
223 	vm = (struct vmspace *)mem;
224 
225 	vm_map_zdtor(&vm->vm_map, sizeof(vm->vm_map), arg);
226 }
227 static void
228 vm_map_zdtor(void *mem, int size, void *arg)
229 {
230 	vm_map_t map;
231 
232 	map = (vm_map_t)mem;
233 	KASSERT(map->nentries == 0,
234 	    ("map %p nentries == %d on free.",
235 	    map, map->nentries));
236 	KASSERT(map->size == 0,
237 	    ("map %p size == %lu on free.",
238 	    map, (unsigned long)map->size));
239 }
240 #endif	/* INVARIANTS */
241 
242 /*
243  * Allocate a vmspace structure, including a vm_map and pmap,
244  * and initialize those structures.  The refcnt is set to 1.
245  */
246 struct vmspace *
247 vmspace_alloc(min, max)
248 	vm_offset_t min, max;
249 {
250 	struct vmspace *vm;
251 
252 	vm = uma_zalloc(vmspace_zone, M_WAITOK);
253 	CTR1(KTR_VM, "vmspace_alloc: %p", vm);
254 	_vm_map_init(&vm->vm_map, min, max);
255 	vm->vm_map.pmap = vmspace_pmap(vm);		/* XXX */
256 	vm->vm_refcnt = 1;
257 	vm->vm_shm = NULL;
258 	vm->vm_swrss = 0;
259 	vm->vm_tsize = 0;
260 	vm->vm_dsize = 0;
261 	vm->vm_ssize = 0;
262 	vm->vm_taddr = 0;
263 	vm->vm_daddr = 0;
264 	vm->vm_maxsaddr = 0;
265 	vm->vm_exitingcnt = 0;
266 	return (vm);
267 }
268 
269 void
270 vm_init2(void)
271 {
272 	uma_zone_set_obj(kmapentzone, &kmapentobj, lmin(cnt.v_page_count,
273 	    (VM_MAX_KERNEL_ADDRESS - KERNBASE) / PAGE_SIZE) / 8 +
274 	     maxproc * 2 + maxfiles);
275 	vmspace_zone = uma_zcreate("VMSPACE", sizeof(struct vmspace), NULL,
276 #ifdef INVARIANTS
277 	    vmspace_zdtor,
278 #else
279 	    NULL,
280 #endif
281 	    vmspace_zinit, vmspace_zfini, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
282 	pmap_init2();
283 }
284 
285 static __inline void
286 vmspace_dofree(struct vmspace *vm)
287 {
288 	CTR1(KTR_VM, "vmspace_free: %p", vm);
289 
290 	/*
291 	 * Make sure any SysV shm is freed, it might not have been in
292 	 * exit1().
293 	 */
294 	shmexit(vm);
295 
296 	/*
297 	 * Lock the map, to wait out all other references to it.
298 	 * Delete all of the mappings and pages they hold, then call
299 	 * the pmap module to reclaim anything left.
300 	 */
301 	vm_map_lock(&vm->vm_map);
302 	(void) vm_map_delete(&vm->vm_map, vm->vm_map.min_offset,
303 	    vm->vm_map.max_offset);
304 	vm_map_unlock(&vm->vm_map);
305 
306 	uma_zfree(vmspace_zone, vm);
307 }
308 
309 void
310 vmspace_free(struct vmspace *vm)
311 {
312 	int refcnt;
313 
314 	if (vm->vm_refcnt == 0)
315 		panic("vmspace_free: attempt to free already freed vmspace");
316 
317 	do
318 		refcnt = vm->vm_refcnt;
319 	while (!atomic_cmpset_int(&vm->vm_refcnt, refcnt, refcnt - 1));
320 	if (refcnt == 1 && vm->vm_exitingcnt == 0)
321 		vmspace_dofree(vm);
322 }
323 
324 void
325 vmspace_exitfree(struct proc *p)
326 {
327 	struct vmspace *vm;
328 	int exitingcnt;
329 
330 	vm = p->p_vmspace;
331 	p->p_vmspace = NULL;
332 
333 	/*
334 	 * cleanup by parent process wait()ing on exiting child.  vm_refcnt
335 	 * may not be 0 (e.g. fork() and child exits without exec()ing).
336 	 * exitingcnt may increment above 0 and drop back down to zero
337 	 * several times while vm_refcnt is held non-zero.  vm_refcnt
338 	 * may also increment above 0 and drop back down to zero several
339 	 * times while vm_exitingcnt is held non-zero.
340 	 *
341 	 * The last wait on the exiting child's vmspace will clean up
342 	 * the remainder of the vmspace.
343 	 */
344 	do
345 		exitingcnt = vm->vm_exitingcnt;
346 	while (!atomic_cmpset_int(&vm->vm_exitingcnt, exitingcnt,
347 	    exitingcnt - 1));
348 	if (vm->vm_refcnt == 0 && exitingcnt == 1)
349 		vmspace_dofree(vm);
350 }
351 
352 void
353 _vm_map_lock(vm_map_t map, const char *file, int line)
354 {
355 
356 	if (map->system_map)
357 		_mtx_lock_flags(&map->system_mtx, 0, file, line);
358 	else
359 		_sx_xlock(&map->lock, file, line);
360 	map->timestamp++;
361 }
362 
363 void
364 _vm_map_unlock(vm_map_t map, const char *file, int line)
365 {
366 
367 	if (map->system_map)
368 		_mtx_unlock_flags(&map->system_mtx, 0, file, line);
369 	else
370 		_sx_xunlock(&map->lock, file, line);
371 }
372 
373 void
374 _vm_map_lock_read(vm_map_t map, const char *file, int line)
375 {
376 
377 	if (map->system_map)
378 		_mtx_lock_flags(&map->system_mtx, 0, file, line);
379 	else
380 		_sx_xlock(&map->lock, file, line);
381 }
382 
383 void
384 _vm_map_unlock_read(vm_map_t map, const char *file, int line)
385 {
386 
387 	if (map->system_map)
388 		_mtx_unlock_flags(&map->system_mtx, 0, file, line);
389 	else
390 		_sx_xunlock(&map->lock, file, line);
391 }
392 
393 int
394 _vm_map_trylock(vm_map_t map, const char *file, int line)
395 {
396 	int error;
397 
398 	error = map->system_map ?
399 	    !_mtx_trylock(&map->system_mtx, 0, file, line) :
400 	    !_sx_try_xlock(&map->lock, file, line);
401 	if (error == 0)
402 		map->timestamp++;
403 	return (error == 0);
404 }
405 
406 int
407 _vm_map_trylock_read(vm_map_t map, const char *file, int line)
408 {
409 	int error;
410 
411 	error = map->system_map ?
412 	    !_mtx_trylock(&map->system_mtx, 0, file, line) :
413 	    !_sx_try_xlock(&map->lock, file, line);
414 	return (error == 0);
415 }
416 
417 int
418 _vm_map_lock_upgrade(vm_map_t map, const char *file, int line)
419 {
420 
421 #ifdef INVARIANTS
422 	if (map->system_map) {
423 		_mtx_assert(&map->system_mtx, MA_OWNED, file, line);
424 	} else
425 		_sx_assert(&map->lock, SX_XLOCKED, file, line);
426 #endif
427 	map->timestamp++;
428 	return (0);
429 }
430 
431 void
432 _vm_map_lock_downgrade(vm_map_t map, const char *file, int line)
433 {
434 
435 #ifdef INVARIANTS
436 	if (map->system_map) {
437 		_mtx_assert(&map->system_mtx, MA_OWNED, file, line);
438 	} else
439 		_sx_assert(&map->lock, SX_XLOCKED, file, line);
440 #endif
441 }
442 
443 /*
444  *	vm_map_unlock_and_wait:
445  */
446 int
447 vm_map_unlock_and_wait(vm_map_t map, boolean_t user_wait)
448 {
449 
450 	mtx_lock(&map_sleep_mtx);
451 	vm_map_unlock(map);
452 	return (msleep(&map->root, &map_sleep_mtx, PDROP | PVM, "vmmaps", 0));
453 }
454 
455 /*
456  *	vm_map_wakeup:
457  */
458 void
459 vm_map_wakeup(vm_map_t map)
460 {
461 
462 	/*
463 	 * Acquire and release map_sleep_mtx to prevent a wakeup()
464 	 * from being performed (and lost) between the vm_map_unlock()
465 	 * and the msleep() in vm_map_unlock_and_wait().
466 	 */
467 	mtx_lock(&map_sleep_mtx);
468 	mtx_unlock(&map_sleep_mtx);
469 	wakeup(&map->root);
470 }
471 
472 long
473 vmspace_resident_count(struct vmspace *vmspace)
474 {
475 	return pmap_resident_count(vmspace_pmap(vmspace));
476 }
477 
478 long
479 vmspace_wired_count(struct vmspace *vmspace)
480 {
481 	return pmap_wired_count(vmspace_pmap(vmspace));
482 }
483 
484 /*
485  *	vm_map_create:
486  *
487  *	Creates and returns a new empty VM map with
488  *	the given physical map structure, and having
489  *	the given lower and upper address bounds.
490  */
491 vm_map_t
492 vm_map_create(pmap_t pmap, vm_offset_t min, vm_offset_t max)
493 {
494 	vm_map_t result;
495 
496 	result = uma_zalloc(mapzone, M_WAITOK);
497 	CTR1(KTR_VM, "vm_map_create: %p", result);
498 	_vm_map_init(result, min, max);
499 	result->pmap = pmap;
500 	return (result);
501 }
502 
503 /*
504  * Initialize an existing vm_map structure
505  * such as that in the vmspace structure.
506  * The pmap is set elsewhere.
507  */
508 static void
509 _vm_map_init(vm_map_t map, vm_offset_t min, vm_offset_t max)
510 {
511 
512 	map->header.next = map->header.prev = &map->header;
513 	map->needs_wakeup = FALSE;
514 	map->system_map = 0;
515 	map->min_offset = min;
516 	map->max_offset = max;
517 	map->flags = 0;
518 	map->root = NULL;
519 	map->timestamp = 0;
520 }
521 
522 void
523 vm_map_init(vm_map_t map, vm_offset_t min, vm_offset_t max)
524 {
525 	_vm_map_init(map, min, max);
526 	mtx_init(&map->system_mtx, "system map", NULL, MTX_DEF | MTX_DUPOK);
527 	sx_init(&map->lock, "user map");
528 }
529 
530 /*
531  *	vm_map_entry_dispose:	[ internal use only ]
532  *
533  *	Inverse of vm_map_entry_create.
534  */
535 static void
536 vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry)
537 {
538 	uma_zfree(map->system_map ? kmapentzone : mapentzone, entry);
539 }
540 
541 /*
542  *	vm_map_entry_create:	[ internal use only ]
543  *
544  *	Allocates a VM map entry for insertion.
545  *	No entry fields are filled in.
546  */
547 static vm_map_entry_t
548 vm_map_entry_create(vm_map_t map)
549 {
550 	vm_map_entry_t new_entry;
551 
552 	if (map->system_map)
553 		new_entry = uma_zalloc(kmapentzone, M_NOWAIT);
554 	else
555 		new_entry = uma_zalloc(mapentzone, M_WAITOK);
556 	if (new_entry == NULL)
557 		panic("vm_map_entry_create: kernel resources exhausted");
558 	return (new_entry);
559 }
560 
561 /*
562  *	vm_map_entry_set_behavior:
563  *
564  *	Set the expected access behavior, either normal, random, or
565  *	sequential.
566  */
567 static __inline void
568 vm_map_entry_set_behavior(vm_map_entry_t entry, u_char behavior)
569 {
570 	entry->eflags = (entry->eflags & ~MAP_ENTRY_BEHAV_MASK) |
571 	    (behavior & MAP_ENTRY_BEHAV_MASK);
572 }
573 
574 /*
575  *	vm_map_entry_set_max_free:
576  *
577  *	Set the max_free field in a vm_map_entry.
578  */
579 static __inline void
580 vm_map_entry_set_max_free(vm_map_entry_t entry)
581 {
582 
583 	entry->max_free = entry->adj_free;
584 	if (entry->left != NULL && entry->left->max_free > entry->max_free)
585 		entry->max_free = entry->left->max_free;
586 	if (entry->right != NULL && entry->right->max_free > entry->max_free)
587 		entry->max_free = entry->right->max_free;
588 }
589 
590 /*
591  *	vm_map_entry_splay:
592  *
593  *	The Sleator and Tarjan top-down splay algorithm with the
594  *	following variation.  Max_free must be computed bottom-up, so
595  *	on the downward pass, maintain the left and right spines in
596  *	reverse order.  Then, make a second pass up each side to fix
597  *	the pointers and compute max_free.  The time bound is O(log n)
598  *	amortized.
599  *
600  *	The new root is the vm_map_entry containing "addr", or else an
601  *	adjacent entry (lower or higher) if addr is not in the tree.
602  *
603  *	The map must be locked, and leaves it so.
604  *
605  *	Returns: the new root.
606  */
607 static vm_map_entry_t
608 vm_map_entry_splay(vm_offset_t addr, vm_map_entry_t root)
609 {
610 	vm_map_entry_t llist, rlist;
611 	vm_map_entry_t ltree, rtree;
612 	vm_map_entry_t y;
613 
614 	/* Special case of empty tree. */
615 	if (root == NULL)
616 		return (root);
617 
618 	/*
619 	 * Pass One: Splay down the tree until we find addr or a NULL
620 	 * pointer where addr would go.  llist and rlist are the two
621 	 * sides in reverse order (bottom-up), with llist linked by
622 	 * the right pointer and rlist linked by the left pointer in
623 	 * the vm_map_entry.  Wait until Pass Two to set max_free on
624 	 * the two spines.
625 	 */
626 	llist = NULL;
627 	rlist = NULL;
628 	for (;;) {
629 		/* root is never NULL in here. */
630 		if (addr < root->start) {
631 			y = root->left;
632 			if (y == NULL)
633 				break;
634 			if (addr < y->start && y->left != NULL) {
635 				/* Rotate right and put y on rlist. */
636 				root->left = y->right;
637 				y->right = root;
638 				vm_map_entry_set_max_free(root);
639 				root = y->left;
640 				y->left = rlist;
641 				rlist = y;
642 			} else {
643 				/* Put root on rlist. */
644 				root->left = rlist;
645 				rlist = root;
646 				root = y;
647 			}
648 		} else {
649 			y = root->right;
650 			if (addr < root->end || y == NULL)
651 				break;
652 			if (addr >= y->end && y->right != NULL) {
653 				/* Rotate left and put y on llist. */
654 				root->right = y->left;
655 				y->left = root;
656 				vm_map_entry_set_max_free(root);
657 				root = y->right;
658 				y->right = llist;
659 				llist = y;
660 			} else {
661 				/* Put root on llist. */
662 				root->right = llist;
663 				llist = root;
664 				root = y;
665 			}
666 		}
667 	}
668 
669 	/*
670 	 * Pass Two: Walk back up the two spines, flip the pointers
671 	 * and set max_free.  The subtrees of the root go at the
672 	 * bottom of llist and rlist.
673 	 */
674 	ltree = root->left;
675 	while (llist != NULL) {
676 		y = llist->right;
677 		llist->right = ltree;
678 		vm_map_entry_set_max_free(llist);
679 		ltree = llist;
680 		llist = y;
681 	}
682 	rtree = root->right;
683 	while (rlist != NULL) {
684 		y = rlist->left;
685 		rlist->left = rtree;
686 		vm_map_entry_set_max_free(rlist);
687 		rtree = rlist;
688 		rlist = y;
689 	}
690 
691 	/*
692 	 * Final assembly: add ltree and rtree as subtrees of root.
693 	 */
694 	root->left = ltree;
695 	root->right = rtree;
696 	vm_map_entry_set_max_free(root);
697 
698 	return (root);
699 }
700 
701 /*
702  *	vm_map_entry_{un,}link:
703  *
704  *	Insert/remove entries from maps.
705  */
706 static void
707 vm_map_entry_link(vm_map_t map,
708 		  vm_map_entry_t after_where,
709 		  vm_map_entry_t entry)
710 {
711 
712 	CTR4(KTR_VM,
713 	    "vm_map_entry_link: map %p, nentries %d, entry %p, after %p", map,
714 	    map->nentries, entry, after_where);
715 	map->nentries++;
716 	entry->prev = after_where;
717 	entry->next = after_where->next;
718 	entry->next->prev = entry;
719 	after_where->next = entry;
720 
721 	if (after_where != &map->header) {
722 		if (after_where != map->root)
723 			vm_map_entry_splay(after_where->start, map->root);
724 		entry->right = after_where->right;
725 		entry->left = after_where;
726 		after_where->right = NULL;
727 		after_where->adj_free = entry->start - after_where->end;
728 		vm_map_entry_set_max_free(after_where);
729 	} else {
730 		entry->right = map->root;
731 		entry->left = NULL;
732 	}
733 	entry->adj_free = (entry->next == &map->header ? map->max_offset :
734 	    entry->next->start) - entry->end;
735 	vm_map_entry_set_max_free(entry);
736 	map->root = entry;
737 }
738 
739 static void
740 vm_map_entry_unlink(vm_map_t map,
741 		    vm_map_entry_t entry)
742 {
743 	vm_map_entry_t next, prev, root;
744 
745 	if (entry != map->root)
746 		vm_map_entry_splay(entry->start, map->root);
747 	if (entry->left == NULL)
748 		root = entry->right;
749 	else {
750 		root = vm_map_entry_splay(entry->start, entry->left);
751 		root->right = entry->right;
752 		root->adj_free = (entry->next == &map->header ? map->max_offset :
753 		    entry->next->start) - root->end;
754 		vm_map_entry_set_max_free(root);
755 	}
756 	map->root = root;
757 
758 	prev = entry->prev;
759 	next = entry->next;
760 	next->prev = prev;
761 	prev->next = next;
762 	map->nentries--;
763 	CTR3(KTR_VM, "vm_map_entry_unlink: map %p, nentries %d, entry %p", map,
764 	    map->nentries, entry);
765 }
766 
767 /*
768  *	vm_map_entry_resize_free:
769  *
770  *	Recompute the amount of free space following a vm_map_entry
771  *	and propagate that value up the tree.  Call this function after
772  *	resizing a map entry in-place, that is, without a call to
773  *	vm_map_entry_link() or _unlink().
774  *
775  *	The map must be locked, and leaves it so.
776  */
777 static void
778 vm_map_entry_resize_free(vm_map_t map, vm_map_entry_t entry)
779 {
780 
781 	/*
782 	 * Using splay trees without parent pointers, propagating
783 	 * max_free up the tree is done by moving the entry to the
784 	 * root and making the change there.
785 	 */
786 	if (entry != map->root)
787 		map->root = vm_map_entry_splay(entry->start, map->root);
788 
789 	entry->adj_free = (entry->next == &map->header ? map->max_offset :
790 	    entry->next->start) - entry->end;
791 	vm_map_entry_set_max_free(entry);
792 }
793 
794 /*
795  *	vm_map_lookup_entry:	[ internal use only ]
796  *
797  *	Finds the map entry containing (or
798  *	immediately preceding) the specified address
799  *	in the given map; the entry is returned
800  *	in the "entry" parameter.  The boolean
801  *	result indicates whether the address is
802  *	actually contained in the map.
803  */
804 boolean_t
805 vm_map_lookup_entry(
806 	vm_map_t map,
807 	vm_offset_t address,
808 	vm_map_entry_t *entry)	/* OUT */
809 {
810 	vm_map_entry_t cur;
811 
812 	cur = vm_map_entry_splay(address, map->root);
813 	if (cur == NULL)
814 		*entry = &map->header;
815 	else {
816 		map->root = cur;
817 
818 		if (address >= cur->start) {
819 			*entry = cur;
820 			if (cur->end > address)
821 				return (TRUE);
822 		} else
823 			*entry = cur->prev;
824 	}
825 	return (FALSE);
826 }
827 
828 /*
829  *	vm_map_insert:
830  *
831  *	Inserts the given whole VM object into the target
832  *	map at the specified address range.  The object's
833  *	size should match that of the address range.
834  *
835  *	Requires that the map be locked, and leaves it so.
836  *
837  *	If object is non-NULL, ref count must be bumped by caller
838  *	prior to making call to account for the new entry.
839  */
840 int
841 vm_map_insert(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
842 	      vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max,
843 	      int cow)
844 {
845 	vm_map_entry_t new_entry;
846 	vm_map_entry_t prev_entry;
847 	vm_map_entry_t temp_entry;
848 	vm_eflags_t protoeflags;
849 
850 	/*
851 	 * Check that the start and end points are not bogus.
852 	 */
853 	if ((start < map->min_offset) || (end > map->max_offset) ||
854 	    (start >= end))
855 		return (KERN_INVALID_ADDRESS);
856 
857 	/*
858 	 * Find the entry prior to the proposed starting address; if it's part
859 	 * of an existing entry, this range is bogus.
860 	 */
861 	if (vm_map_lookup_entry(map, start, &temp_entry))
862 		return (KERN_NO_SPACE);
863 
864 	prev_entry = temp_entry;
865 
866 	/*
867 	 * Assert that the next entry doesn't overlap the end point.
868 	 */
869 	if ((prev_entry->next != &map->header) &&
870 	    (prev_entry->next->start < end))
871 		return (KERN_NO_SPACE);
872 
873 	protoeflags = 0;
874 
875 	if (cow & MAP_COPY_ON_WRITE)
876 		protoeflags |= MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY;
877 
878 	if (cow & MAP_NOFAULT) {
879 		protoeflags |= MAP_ENTRY_NOFAULT;
880 
881 		KASSERT(object == NULL,
882 			("vm_map_insert: paradoxical MAP_NOFAULT request"));
883 	}
884 	if (cow & MAP_DISABLE_SYNCER)
885 		protoeflags |= MAP_ENTRY_NOSYNC;
886 	if (cow & MAP_DISABLE_COREDUMP)
887 		protoeflags |= MAP_ENTRY_NOCOREDUMP;
888 
889 	if (object != NULL) {
890 		/*
891 		 * OBJ_ONEMAPPING must be cleared unless this mapping
892 		 * is trivially proven to be the only mapping for any
893 		 * of the object's pages.  (Object granularity
894 		 * reference counting is insufficient to recognize
895 		 * aliases with precision.)
896 		 */
897 		VM_OBJECT_LOCK(object);
898 		if (object->ref_count > 1 || object->shadow_count != 0)
899 			vm_object_clear_flag(object, OBJ_ONEMAPPING);
900 		VM_OBJECT_UNLOCK(object);
901 	}
902 	else if ((prev_entry != &map->header) &&
903 		 (prev_entry->eflags == protoeflags) &&
904 		 (prev_entry->end == start) &&
905 		 (prev_entry->wired_count == 0) &&
906 		 ((prev_entry->object.vm_object == NULL) ||
907 		  vm_object_coalesce(prev_entry->object.vm_object,
908 				     prev_entry->offset,
909 				     (vm_size_t)(prev_entry->end - prev_entry->start),
910 				     (vm_size_t)(end - prev_entry->end)))) {
911 		/*
912 		 * We were able to extend the object.  Determine if we
913 		 * can extend the previous map entry to include the
914 		 * new range as well.
915 		 */
916 		if ((prev_entry->inheritance == VM_INHERIT_DEFAULT) &&
917 		    (prev_entry->protection == prot) &&
918 		    (prev_entry->max_protection == max)) {
919 			map->size += (end - prev_entry->end);
920 			prev_entry->end = end;
921 			vm_map_entry_resize_free(map, prev_entry);
922 			vm_map_simplify_entry(map, prev_entry);
923 			return (KERN_SUCCESS);
924 		}
925 
926 		/*
927 		 * If we can extend the object but cannot extend the
928 		 * map entry, we have to create a new map entry.  We
929 		 * must bump the ref count on the extended object to
930 		 * account for it.  object may be NULL.
931 		 */
932 		object = prev_entry->object.vm_object;
933 		offset = prev_entry->offset +
934 			(prev_entry->end - prev_entry->start);
935 		vm_object_reference(object);
936 	}
937 
938 	/*
939 	 * NOTE: if conditionals fail, object can be NULL here.  This occurs
940 	 * in things like the buffer map where we manage kva but do not manage
941 	 * backing objects.
942 	 */
943 
944 	/*
945 	 * Create a new entry
946 	 */
947 	new_entry = vm_map_entry_create(map);
948 	new_entry->start = start;
949 	new_entry->end = end;
950 
951 	new_entry->eflags = protoeflags;
952 	new_entry->object.vm_object = object;
953 	new_entry->offset = offset;
954 	new_entry->avail_ssize = 0;
955 
956 	new_entry->inheritance = VM_INHERIT_DEFAULT;
957 	new_entry->protection = prot;
958 	new_entry->max_protection = max;
959 	new_entry->wired_count = 0;
960 
961 	/*
962 	 * Insert the new entry into the list
963 	 */
964 	vm_map_entry_link(map, prev_entry, new_entry);
965 	map->size += new_entry->end - new_entry->start;
966 
967 #if 0
968 	/*
969 	 * Temporarily removed to avoid MAP_STACK panic, due to
970 	 * MAP_STACK being a huge hack.  Will be added back in
971 	 * when MAP_STACK (and the user stack mapping) is fixed.
972 	 */
973 	/*
974 	 * It may be possible to simplify the entry
975 	 */
976 	vm_map_simplify_entry(map, new_entry);
977 #endif
978 
979 	if (cow & (MAP_PREFAULT|MAP_PREFAULT_PARTIAL)) {
980 		vm_map_pmap_enter(map, start, prot,
981 				    object, OFF_TO_IDX(offset), end - start,
982 				    cow & MAP_PREFAULT_PARTIAL);
983 	}
984 
985 	return (KERN_SUCCESS);
986 }
987 
988 /*
989  *	vm_map_findspace:
990  *
991  *	Find the first fit (lowest VM address) for "length" free bytes
992  *	beginning at address >= start in the given map.
993  *
994  *	In a vm_map_entry, "adj_free" is the amount of free space
995  *	adjacent (higher address) to this entry, and "max_free" is the
996  *	maximum amount of contiguous free space in its subtree.  This
997  *	allows finding a free region in one path down the tree, so
998  *	O(log n) amortized with splay trees.
999  *
1000  *	The map must be locked, and leaves it so.
1001  *
1002  *	Returns: 0 on success, and starting address in *addr,
1003  *		 1 if insufficient space.
1004  */
1005 int
1006 vm_map_findspace(vm_map_t map, vm_offset_t start, vm_size_t length,
1007     vm_offset_t *addr)	/* OUT */
1008 {
1009 	vm_map_entry_t entry;
1010 	vm_offset_t end, st;
1011 
1012 	/* Request must fit within min/max VM address. */
1013 	if (start < map->min_offset)
1014 		start = map->min_offset;
1015 	if (start + length > map->max_offset)
1016 		return (1);
1017 
1018 	/* Empty tree means wide open address space. */
1019 	if (map->root == NULL) {
1020 		*addr = start;
1021 		goto found;
1022 	}
1023 
1024 	/*
1025 	 * After splay, if start comes before root node, then there
1026 	 * must be a gap from start to the root.
1027 	 */
1028 	map->root = vm_map_entry_splay(start, map->root);
1029 	if (start + length <= map->root->start) {
1030 		*addr = start;
1031 		goto found;
1032 	}
1033 
1034 	/*
1035 	 * Root is the last node that might begin its gap before
1036 	 * start.
1037 	 */
1038 	st = (start > map->root->end) ? start : map->root->end;
1039 	if (st + length <= map->root->end + map->root->adj_free) {
1040 		*addr = st;
1041 		goto found;
1042 	}
1043 
1044 	/* With max_free, can immediately tell if no solution. */
1045 	entry = map->root->right;
1046 	if (entry == NULL || length > entry->max_free)
1047 		return (1);
1048 
1049 	/*
1050 	 * Search the right subtree in the order: left subtree, root,
1051 	 * right subtree (first fit).  The previous splay implies that
1052 	 * all regions in the right subtree have addresses > start.
1053 	 */
1054 	while (entry != NULL) {
1055 		if (entry->left != NULL && entry->left->max_free >= length)
1056 			entry = entry->left;
1057 		else if (entry->adj_free >= length) {
1058 			*addr = entry->end;
1059 			goto found;
1060 		} else
1061 			entry = entry->right;
1062 	}
1063 
1064 	/* Can't get here, so panic if we do. */
1065 	panic("vm_map_findspace: max_free corrupt");
1066 
1067 found:
1068 	/* Expand the kernel pmap, if necessary. */
1069 	if (map == kernel_map) {
1070 		end = round_page(*addr + length);
1071 		if (end > kernel_vm_end)
1072 			pmap_growkernel(end);
1073 	}
1074 	return (0);
1075 }
1076 
1077 /*
1078  *	vm_map_find finds an unallocated region in the target address
1079  *	map with the given length.  The search is defined to be
1080  *	first-fit from the specified address; the region found is
1081  *	returned in the same parameter.
1082  *
1083  *	If object is non-NULL, ref count must be bumped by caller
1084  *	prior to making call to account for the new entry.
1085  */
1086 int
1087 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1088 	    vm_offset_t *addr,	/* IN/OUT */
1089 	    vm_size_t length, boolean_t find_space, vm_prot_t prot,
1090 	    vm_prot_t max, int cow)
1091 {
1092 	vm_offset_t start;
1093 	int result;
1094 
1095 	start = *addr;
1096 	vm_map_lock(map);
1097 	if (find_space) {
1098 		if (vm_map_findspace(map, start, length, addr)) {
1099 			vm_map_unlock(map);
1100 			return (KERN_NO_SPACE);
1101 		}
1102 		start = *addr;
1103 	}
1104 	result = vm_map_insert(map, object, offset,
1105 		start, start + length, prot, max, cow);
1106 	vm_map_unlock(map);
1107 	return (result);
1108 }
1109 
1110 /*
1111  *	vm_map_simplify_entry:
1112  *
1113  *	Simplify the given map entry by merging with either neighbor.  This
1114  *	routine also has the ability to merge with both neighbors.
1115  *
1116  *	The map must be locked.
1117  *
1118  *	This routine guarentees that the passed entry remains valid (though
1119  *	possibly extended).  When merging, this routine may delete one or
1120  *	both neighbors.
1121  */
1122 void
1123 vm_map_simplify_entry(vm_map_t map, vm_map_entry_t entry)
1124 {
1125 	vm_map_entry_t next, prev;
1126 	vm_size_t prevsize, esize;
1127 
1128 	if (entry->eflags & (MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_IS_SUB_MAP))
1129 		return;
1130 
1131 	prev = entry->prev;
1132 	if (prev != &map->header) {
1133 		prevsize = prev->end - prev->start;
1134 		if ( (prev->end == entry->start) &&
1135 		     (prev->object.vm_object == entry->object.vm_object) &&
1136 		     (!prev->object.vm_object ||
1137 			(prev->offset + prevsize == entry->offset)) &&
1138 		     (prev->eflags == entry->eflags) &&
1139 		     (prev->protection == entry->protection) &&
1140 		     (prev->max_protection == entry->max_protection) &&
1141 		     (prev->inheritance == entry->inheritance) &&
1142 		     (prev->wired_count == entry->wired_count)) {
1143 			vm_map_entry_unlink(map, prev);
1144 			entry->start = prev->start;
1145 			entry->offset = prev->offset;
1146 			if (entry->prev != &map->header)
1147 				vm_map_entry_resize_free(map, entry->prev);
1148 			if (prev->object.vm_object)
1149 				vm_object_deallocate(prev->object.vm_object);
1150 			vm_map_entry_dispose(map, prev);
1151 		}
1152 	}
1153 
1154 	next = entry->next;
1155 	if (next != &map->header) {
1156 		esize = entry->end - entry->start;
1157 		if ((entry->end == next->start) &&
1158 		    (next->object.vm_object == entry->object.vm_object) &&
1159 		     (!entry->object.vm_object ||
1160 			(entry->offset + esize == next->offset)) &&
1161 		    (next->eflags == entry->eflags) &&
1162 		    (next->protection == entry->protection) &&
1163 		    (next->max_protection == entry->max_protection) &&
1164 		    (next->inheritance == entry->inheritance) &&
1165 		    (next->wired_count == entry->wired_count)) {
1166 			vm_map_entry_unlink(map, next);
1167 			entry->end = next->end;
1168 			vm_map_entry_resize_free(map, entry);
1169 			if (next->object.vm_object)
1170 				vm_object_deallocate(next->object.vm_object);
1171 			vm_map_entry_dispose(map, next);
1172 		}
1173 	}
1174 }
1175 /*
1176  *	vm_map_clip_start:	[ internal use only ]
1177  *
1178  *	Asserts that the given entry begins at or after
1179  *	the specified address; if necessary,
1180  *	it splits the entry into two.
1181  */
1182 #define vm_map_clip_start(map, entry, startaddr) \
1183 { \
1184 	if (startaddr > entry->start) \
1185 		_vm_map_clip_start(map, entry, startaddr); \
1186 }
1187 
1188 /*
1189  *	This routine is called only when it is known that
1190  *	the entry must be split.
1191  */
1192 static void
1193 _vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t start)
1194 {
1195 	vm_map_entry_t new_entry;
1196 
1197 	/*
1198 	 * Split off the front portion -- note that we must insert the new
1199 	 * entry BEFORE this one, so that this entry has the specified
1200 	 * starting address.
1201 	 */
1202 	vm_map_simplify_entry(map, entry);
1203 
1204 	/*
1205 	 * If there is no object backing this entry, we might as well create
1206 	 * one now.  If we defer it, an object can get created after the map
1207 	 * is clipped, and individual objects will be created for the split-up
1208 	 * map.  This is a bit of a hack, but is also about the best place to
1209 	 * put this improvement.
1210 	 */
1211 	if (entry->object.vm_object == NULL && !map->system_map) {
1212 		vm_object_t object;
1213 		object = vm_object_allocate(OBJT_DEFAULT,
1214 				atop(entry->end - entry->start));
1215 		entry->object.vm_object = object;
1216 		entry->offset = 0;
1217 	}
1218 
1219 	new_entry = vm_map_entry_create(map);
1220 	*new_entry = *entry;
1221 
1222 	new_entry->end = start;
1223 	entry->offset += (start - entry->start);
1224 	entry->start = start;
1225 
1226 	vm_map_entry_link(map, entry->prev, new_entry);
1227 
1228 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1229 		vm_object_reference(new_entry->object.vm_object);
1230 	}
1231 }
1232 
1233 /*
1234  *	vm_map_clip_end:	[ internal use only ]
1235  *
1236  *	Asserts that the given entry ends at or before
1237  *	the specified address; if necessary,
1238  *	it splits the entry into two.
1239  */
1240 #define vm_map_clip_end(map, entry, endaddr) \
1241 { \
1242 	if ((endaddr) < (entry->end)) \
1243 		_vm_map_clip_end((map), (entry), (endaddr)); \
1244 }
1245 
1246 /*
1247  *	This routine is called only when it is known that
1248  *	the entry must be split.
1249  */
1250 static void
1251 _vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t end)
1252 {
1253 	vm_map_entry_t new_entry;
1254 
1255 	/*
1256 	 * If there is no object backing this entry, we might as well create
1257 	 * one now.  If we defer it, an object can get created after the map
1258 	 * is clipped, and individual objects will be created for the split-up
1259 	 * map.  This is a bit of a hack, but is also about the best place to
1260 	 * put this improvement.
1261 	 */
1262 	if (entry->object.vm_object == NULL && !map->system_map) {
1263 		vm_object_t object;
1264 		object = vm_object_allocate(OBJT_DEFAULT,
1265 				atop(entry->end - entry->start));
1266 		entry->object.vm_object = object;
1267 		entry->offset = 0;
1268 	}
1269 
1270 	/*
1271 	 * Create a new entry and insert it AFTER the specified entry
1272 	 */
1273 	new_entry = vm_map_entry_create(map);
1274 	*new_entry = *entry;
1275 
1276 	new_entry->start = entry->end = end;
1277 	new_entry->offset += (end - entry->start);
1278 
1279 	vm_map_entry_link(map, entry, new_entry);
1280 
1281 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1282 		vm_object_reference(new_entry->object.vm_object);
1283 	}
1284 }
1285 
1286 /*
1287  *	VM_MAP_RANGE_CHECK:	[ internal use only ]
1288  *
1289  *	Asserts that the starting and ending region
1290  *	addresses fall within the valid range of the map.
1291  */
1292 #define	VM_MAP_RANGE_CHECK(map, start, end)		\
1293 		{					\
1294 		if (start < vm_map_min(map))		\
1295 			start = vm_map_min(map);	\
1296 		if (end > vm_map_max(map))		\
1297 			end = vm_map_max(map);		\
1298 		if (start > end)			\
1299 			start = end;			\
1300 		}
1301 
1302 /*
1303  *	vm_map_submap:		[ kernel use only ]
1304  *
1305  *	Mark the given range as handled by a subordinate map.
1306  *
1307  *	This range must have been created with vm_map_find,
1308  *	and no other operations may have been performed on this
1309  *	range prior to calling vm_map_submap.
1310  *
1311  *	Only a limited number of operations can be performed
1312  *	within this rage after calling vm_map_submap:
1313  *		vm_fault
1314  *	[Don't try vm_map_copy!]
1315  *
1316  *	To remove a submapping, one must first remove the
1317  *	range from the superior map, and then destroy the
1318  *	submap (if desired).  [Better yet, don't try it.]
1319  */
1320 int
1321 vm_map_submap(
1322 	vm_map_t map,
1323 	vm_offset_t start,
1324 	vm_offset_t end,
1325 	vm_map_t submap)
1326 {
1327 	vm_map_entry_t entry;
1328 	int result = KERN_INVALID_ARGUMENT;
1329 
1330 	vm_map_lock(map);
1331 
1332 	VM_MAP_RANGE_CHECK(map, start, end);
1333 
1334 	if (vm_map_lookup_entry(map, start, &entry)) {
1335 		vm_map_clip_start(map, entry, start);
1336 	} else
1337 		entry = entry->next;
1338 
1339 	vm_map_clip_end(map, entry, end);
1340 
1341 	if ((entry->start == start) && (entry->end == end) &&
1342 	    ((entry->eflags & MAP_ENTRY_COW) == 0) &&
1343 	    (entry->object.vm_object == NULL)) {
1344 		entry->object.sub_map = submap;
1345 		entry->eflags |= MAP_ENTRY_IS_SUB_MAP;
1346 		result = KERN_SUCCESS;
1347 	}
1348 	vm_map_unlock(map);
1349 
1350 	return (result);
1351 }
1352 
1353 /*
1354  * The maximum number of pages to map
1355  */
1356 #define	MAX_INIT_PT	96
1357 
1358 /*
1359  *	vm_map_pmap_enter:
1360  *
1361  *	Preload read-only mappings for the given object into the specified
1362  *	map.  This eliminates the soft faults on process startup and
1363  *	immediately after an mmap(2).
1364  */
1365 void
1366 vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
1367     vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags)
1368 {
1369 	vm_offset_t tmpidx;
1370 	int psize;
1371 	vm_page_t p, mpte;
1372 
1373 	if ((prot & VM_PROT_READ) == 0 || object == NULL)
1374 		return;
1375 	VM_OBJECT_LOCK(object);
1376 	if (object->type == OBJT_DEVICE) {
1377 		pmap_object_init_pt(map->pmap, addr, object, pindex, size);
1378 		goto unlock_return;
1379 	}
1380 
1381 	psize = atop(size);
1382 
1383 	if (object->type != OBJT_VNODE ||
1384 	    ((flags & MAP_PREFAULT_PARTIAL) && (psize > MAX_INIT_PT) &&
1385 	     (object->resident_page_count > MAX_INIT_PT))) {
1386 		goto unlock_return;
1387 	}
1388 
1389 	if (psize + pindex > object->size) {
1390 		if (object->size < pindex)
1391 			goto unlock_return;
1392 		psize = object->size - pindex;
1393 	}
1394 
1395 	mpte = NULL;
1396 
1397 	if ((p = TAILQ_FIRST(&object->memq)) != NULL) {
1398 		if (p->pindex < pindex) {
1399 			p = vm_page_splay(pindex, object->root);
1400 			if ((object->root = p)->pindex < pindex)
1401 				p = TAILQ_NEXT(p, listq);
1402 		}
1403 	}
1404 	/*
1405 	 * Assert: the variable p is either (1) the page with the
1406 	 * least pindex greater than or equal to the parameter pindex
1407 	 * or (2) NULL.
1408 	 */
1409 	for (;
1410 	     p != NULL && (tmpidx = p->pindex - pindex) < psize;
1411 	     p = TAILQ_NEXT(p, listq)) {
1412 		/*
1413 		 * don't allow an madvise to blow away our really
1414 		 * free pages allocating pv entries.
1415 		 */
1416 		if ((flags & MAP_PREFAULT_MADVISE) &&
1417 		    cnt.v_free_count < cnt.v_free_reserved) {
1418 			break;
1419 		}
1420 		if ((p->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL &&
1421 		    (p->busy == 0) &&
1422 		    (p->flags & (PG_BUSY | PG_FICTITIOUS)) == 0) {
1423 			if ((p->queue - p->pc) == PQ_CACHE) {
1424 				vm_page_lock_queues();
1425 				vm_page_deactivate(p);
1426 				vm_page_unlock_queues();
1427 			}
1428 			mpte = pmap_enter_quick(map->pmap,
1429 				addr + ptoa(tmpidx), p, mpte);
1430 		}
1431 	}
1432 unlock_return:
1433 	VM_OBJECT_UNLOCK(object);
1434 }
1435 
1436 /*
1437  *	vm_map_protect:
1438  *
1439  *	Sets the protection of the specified address
1440  *	region in the target map.  If "set_max" is
1441  *	specified, the maximum protection is to be set;
1442  *	otherwise, only the current protection is affected.
1443  */
1444 int
1445 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
1446 	       vm_prot_t new_prot, boolean_t set_max)
1447 {
1448 	vm_map_entry_t current;
1449 	vm_map_entry_t entry;
1450 
1451 	vm_map_lock(map);
1452 
1453 	VM_MAP_RANGE_CHECK(map, start, end);
1454 
1455 	if (vm_map_lookup_entry(map, start, &entry)) {
1456 		vm_map_clip_start(map, entry, start);
1457 	} else {
1458 		entry = entry->next;
1459 	}
1460 
1461 	/*
1462 	 * Make a first pass to check for protection violations.
1463 	 */
1464 	current = entry;
1465 	while ((current != &map->header) && (current->start < end)) {
1466 		if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
1467 			vm_map_unlock(map);
1468 			return (KERN_INVALID_ARGUMENT);
1469 		}
1470 		if ((new_prot & current->max_protection) != new_prot) {
1471 			vm_map_unlock(map);
1472 			return (KERN_PROTECTION_FAILURE);
1473 		}
1474 		current = current->next;
1475 	}
1476 
1477 	/*
1478 	 * Go back and fix up protections. [Note that clipping is not
1479 	 * necessary the second time.]
1480 	 */
1481 	current = entry;
1482 	while ((current != &map->header) && (current->start < end)) {
1483 		vm_prot_t old_prot;
1484 
1485 		vm_map_clip_end(map, current, end);
1486 
1487 		old_prot = current->protection;
1488 		if (set_max)
1489 			current->protection =
1490 			    (current->max_protection = new_prot) &
1491 			    old_prot;
1492 		else
1493 			current->protection = new_prot;
1494 
1495 		/*
1496 		 * Update physical map if necessary. Worry about copy-on-write
1497 		 * here -- CHECK THIS XXX
1498 		 */
1499 		if (current->protection != old_prot) {
1500 #define MASK(entry)	(((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
1501 							VM_PROT_ALL)
1502 			pmap_protect(map->pmap, current->start,
1503 			    current->end,
1504 			    current->protection & MASK(current));
1505 #undef	MASK
1506 		}
1507 		vm_map_simplify_entry(map, current);
1508 		current = current->next;
1509 	}
1510 	vm_map_unlock(map);
1511 	return (KERN_SUCCESS);
1512 }
1513 
1514 /*
1515  *	vm_map_madvise:
1516  *
1517  *	This routine traverses a processes map handling the madvise
1518  *	system call.  Advisories are classified as either those effecting
1519  *	the vm_map_entry structure, or those effecting the underlying
1520  *	objects.
1521  */
1522 int
1523 vm_map_madvise(
1524 	vm_map_t map,
1525 	vm_offset_t start,
1526 	vm_offset_t end,
1527 	int behav)
1528 {
1529 	vm_map_entry_t current, entry;
1530 	int modify_map = 0;
1531 
1532 	/*
1533 	 * Some madvise calls directly modify the vm_map_entry, in which case
1534 	 * we need to use an exclusive lock on the map and we need to perform
1535 	 * various clipping operations.  Otherwise we only need a read-lock
1536 	 * on the map.
1537 	 */
1538 	switch(behav) {
1539 	case MADV_NORMAL:
1540 	case MADV_SEQUENTIAL:
1541 	case MADV_RANDOM:
1542 	case MADV_NOSYNC:
1543 	case MADV_AUTOSYNC:
1544 	case MADV_NOCORE:
1545 	case MADV_CORE:
1546 		modify_map = 1;
1547 		vm_map_lock(map);
1548 		break;
1549 	case MADV_WILLNEED:
1550 	case MADV_DONTNEED:
1551 	case MADV_FREE:
1552 		vm_map_lock_read(map);
1553 		break;
1554 	default:
1555 		return (KERN_INVALID_ARGUMENT);
1556 	}
1557 
1558 	/*
1559 	 * Locate starting entry and clip if necessary.
1560 	 */
1561 	VM_MAP_RANGE_CHECK(map, start, end);
1562 
1563 	if (vm_map_lookup_entry(map, start, &entry)) {
1564 		if (modify_map)
1565 			vm_map_clip_start(map, entry, start);
1566 	} else {
1567 		entry = entry->next;
1568 	}
1569 
1570 	if (modify_map) {
1571 		/*
1572 		 * madvise behaviors that are implemented in the vm_map_entry.
1573 		 *
1574 		 * We clip the vm_map_entry so that behavioral changes are
1575 		 * limited to the specified address range.
1576 		 */
1577 		for (current = entry;
1578 		     (current != &map->header) && (current->start < end);
1579 		     current = current->next
1580 		) {
1581 			if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
1582 				continue;
1583 
1584 			vm_map_clip_end(map, current, end);
1585 
1586 			switch (behav) {
1587 			case MADV_NORMAL:
1588 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_NORMAL);
1589 				break;
1590 			case MADV_SEQUENTIAL:
1591 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_SEQUENTIAL);
1592 				break;
1593 			case MADV_RANDOM:
1594 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_RANDOM);
1595 				break;
1596 			case MADV_NOSYNC:
1597 				current->eflags |= MAP_ENTRY_NOSYNC;
1598 				break;
1599 			case MADV_AUTOSYNC:
1600 				current->eflags &= ~MAP_ENTRY_NOSYNC;
1601 				break;
1602 			case MADV_NOCORE:
1603 				current->eflags |= MAP_ENTRY_NOCOREDUMP;
1604 				break;
1605 			case MADV_CORE:
1606 				current->eflags &= ~MAP_ENTRY_NOCOREDUMP;
1607 				break;
1608 			default:
1609 				break;
1610 			}
1611 			vm_map_simplify_entry(map, current);
1612 		}
1613 		vm_map_unlock(map);
1614 	} else {
1615 		vm_pindex_t pindex;
1616 		int count;
1617 
1618 		/*
1619 		 * madvise behaviors that are implemented in the underlying
1620 		 * vm_object.
1621 		 *
1622 		 * Since we don't clip the vm_map_entry, we have to clip
1623 		 * the vm_object pindex and count.
1624 		 */
1625 		for (current = entry;
1626 		     (current != &map->header) && (current->start < end);
1627 		     current = current->next
1628 		) {
1629 			vm_offset_t useStart;
1630 
1631 			if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
1632 				continue;
1633 
1634 			pindex = OFF_TO_IDX(current->offset);
1635 			count = atop(current->end - current->start);
1636 			useStart = current->start;
1637 
1638 			if (current->start < start) {
1639 				pindex += atop(start - current->start);
1640 				count -= atop(start - current->start);
1641 				useStart = start;
1642 			}
1643 			if (current->end > end)
1644 				count -= atop(current->end - end);
1645 
1646 			if (count <= 0)
1647 				continue;
1648 
1649 			vm_object_madvise(current->object.vm_object,
1650 					  pindex, count, behav);
1651 			if (behav == MADV_WILLNEED) {
1652 				vm_map_pmap_enter(map,
1653 				    useStart,
1654 				    current->protection,
1655 				    current->object.vm_object,
1656 				    pindex,
1657 				    (count << PAGE_SHIFT),
1658 				    MAP_PREFAULT_MADVISE
1659 				);
1660 			}
1661 		}
1662 		vm_map_unlock_read(map);
1663 	}
1664 	return (0);
1665 }
1666 
1667 
1668 /*
1669  *	vm_map_inherit:
1670  *
1671  *	Sets the inheritance of the specified address
1672  *	range in the target map.  Inheritance
1673  *	affects how the map will be shared with
1674  *	child maps at the time of vm_map_fork.
1675  */
1676 int
1677 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
1678 	       vm_inherit_t new_inheritance)
1679 {
1680 	vm_map_entry_t entry;
1681 	vm_map_entry_t temp_entry;
1682 
1683 	switch (new_inheritance) {
1684 	case VM_INHERIT_NONE:
1685 	case VM_INHERIT_COPY:
1686 	case VM_INHERIT_SHARE:
1687 		break;
1688 	default:
1689 		return (KERN_INVALID_ARGUMENT);
1690 	}
1691 	vm_map_lock(map);
1692 	VM_MAP_RANGE_CHECK(map, start, end);
1693 	if (vm_map_lookup_entry(map, start, &temp_entry)) {
1694 		entry = temp_entry;
1695 		vm_map_clip_start(map, entry, start);
1696 	} else
1697 		entry = temp_entry->next;
1698 	while ((entry != &map->header) && (entry->start < end)) {
1699 		vm_map_clip_end(map, entry, end);
1700 		entry->inheritance = new_inheritance;
1701 		vm_map_simplify_entry(map, entry);
1702 		entry = entry->next;
1703 	}
1704 	vm_map_unlock(map);
1705 	return (KERN_SUCCESS);
1706 }
1707 
1708 /*
1709  *	vm_map_unwire:
1710  *
1711  *	Implements both kernel and user unwiring.
1712  */
1713 int
1714 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t end,
1715     int flags)
1716 {
1717 	vm_map_entry_t entry, first_entry, tmp_entry;
1718 	vm_offset_t saved_start;
1719 	unsigned int last_timestamp;
1720 	int rv;
1721 	boolean_t need_wakeup, result, user_unwire;
1722 
1723 	user_unwire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
1724 	vm_map_lock(map);
1725 	VM_MAP_RANGE_CHECK(map, start, end);
1726 	if (!vm_map_lookup_entry(map, start, &first_entry)) {
1727 		if (flags & VM_MAP_WIRE_HOLESOK)
1728 			first_entry = first_entry->next;
1729 		else {
1730 			vm_map_unlock(map);
1731 			return (KERN_INVALID_ADDRESS);
1732 		}
1733 	}
1734 	last_timestamp = map->timestamp;
1735 	entry = first_entry;
1736 	while (entry != &map->header && entry->start < end) {
1737 		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
1738 			/*
1739 			 * We have not yet clipped the entry.
1740 			 */
1741 			saved_start = (start >= entry->start) ? start :
1742 			    entry->start;
1743 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
1744 			if (vm_map_unlock_and_wait(map, user_unwire)) {
1745 				/*
1746 				 * Allow interruption of user unwiring?
1747 				 */
1748 			}
1749 			vm_map_lock(map);
1750 			if (last_timestamp+1 != map->timestamp) {
1751 				/*
1752 				 * Look again for the entry because the map was
1753 				 * modified while it was unlocked.
1754 				 * Specifically, the entry may have been
1755 				 * clipped, merged, or deleted.
1756 				 */
1757 				if (!vm_map_lookup_entry(map, saved_start,
1758 				    &tmp_entry)) {
1759 					if (flags & VM_MAP_WIRE_HOLESOK)
1760 						tmp_entry = tmp_entry->next;
1761 					else {
1762 						if (saved_start == start) {
1763 							/*
1764 							 * First_entry has been deleted.
1765 							 */
1766 							vm_map_unlock(map);
1767 							return (KERN_INVALID_ADDRESS);
1768 						}
1769 						end = saved_start;
1770 						rv = KERN_INVALID_ADDRESS;
1771 						goto done;
1772 					}
1773 				}
1774 				if (entry == first_entry)
1775 					first_entry = tmp_entry;
1776 				else
1777 					first_entry = NULL;
1778 				entry = tmp_entry;
1779 			}
1780 			last_timestamp = map->timestamp;
1781 			continue;
1782 		}
1783 		vm_map_clip_start(map, entry, start);
1784 		vm_map_clip_end(map, entry, end);
1785 		/*
1786 		 * Mark the entry in case the map lock is released.  (See
1787 		 * above.)
1788 		 */
1789 		entry->eflags |= MAP_ENTRY_IN_TRANSITION;
1790 		/*
1791 		 * Check the map for holes in the specified region.
1792 		 * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
1793 		 */
1794 		if (((flags & VM_MAP_WIRE_HOLESOK) == 0) &&
1795 		    (entry->end < end && (entry->next == &map->header ||
1796 		    entry->next->start > entry->end))) {
1797 			end = entry->end;
1798 			rv = KERN_INVALID_ADDRESS;
1799 			goto done;
1800 		}
1801 		/*
1802 		 * If system unwiring, require that the entry is system wired.
1803 		 */
1804 		if (!user_unwire &&
1805 		    vm_map_entry_system_wired_count(entry) == 0) {
1806 			end = entry->end;
1807 			rv = KERN_INVALID_ARGUMENT;
1808 			goto done;
1809 		}
1810 		entry = entry->next;
1811 	}
1812 	rv = KERN_SUCCESS;
1813 done:
1814 	need_wakeup = FALSE;
1815 	if (first_entry == NULL) {
1816 		result = vm_map_lookup_entry(map, start, &first_entry);
1817 		if (!result && (flags & VM_MAP_WIRE_HOLESOK))
1818 			first_entry = first_entry->next;
1819 		else
1820 			KASSERT(result, ("vm_map_unwire: lookup failed"));
1821 	}
1822 	entry = first_entry;
1823 	while (entry != &map->header && entry->start < end) {
1824 		if (rv == KERN_SUCCESS && (!user_unwire ||
1825 		    (entry->eflags & MAP_ENTRY_USER_WIRED))) {
1826 			if (user_unwire)
1827 				entry->eflags &= ~MAP_ENTRY_USER_WIRED;
1828 			entry->wired_count--;
1829 			if (entry->wired_count == 0) {
1830 				/*
1831 				 * Retain the map lock.
1832 				 */
1833 				vm_fault_unwire(map, entry->start, entry->end,
1834 				    entry->object.vm_object != NULL &&
1835 				    entry->object.vm_object->type == OBJT_DEVICE);
1836 			}
1837 		}
1838 		KASSERT(entry->eflags & MAP_ENTRY_IN_TRANSITION,
1839 			("vm_map_unwire: in-transition flag missing"));
1840 		entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
1841 		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
1842 			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
1843 			need_wakeup = TRUE;
1844 		}
1845 		vm_map_simplify_entry(map, entry);
1846 		entry = entry->next;
1847 	}
1848 	vm_map_unlock(map);
1849 	if (need_wakeup)
1850 		vm_map_wakeup(map);
1851 	return (rv);
1852 }
1853 
1854 /*
1855  *	vm_map_wire:
1856  *
1857  *	Implements both kernel and user wiring.
1858  */
1859 int
1860 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t end,
1861     int flags)
1862 {
1863 	vm_map_entry_t entry, first_entry, tmp_entry;
1864 	vm_offset_t saved_end, saved_start;
1865 	unsigned int last_timestamp;
1866 	int rv;
1867 	boolean_t fictitious, need_wakeup, result, user_wire;
1868 
1869 	user_wire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
1870 	vm_map_lock(map);
1871 	VM_MAP_RANGE_CHECK(map, start, end);
1872 	if (!vm_map_lookup_entry(map, start, &first_entry)) {
1873 		if (flags & VM_MAP_WIRE_HOLESOK)
1874 			first_entry = first_entry->next;
1875 		else {
1876 			vm_map_unlock(map);
1877 			return (KERN_INVALID_ADDRESS);
1878 		}
1879 	}
1880 	last_timestamp = map->timestamp;
1881 	entry = first_entry;
1882 	while (entry != &map->header && entry->start < end) {
1883 		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
1884 			/*
1885 			 * We have not yet clipped the entry.
1886 			 */
1887 			saved_start = (start >= entry->start) ? start :
1888 			    entry->start;
1889 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
1890 			if (vm_map_unlock_and_wait(map, user_wire)) {
1891 				/*
1892 				 * Allow interruption of user wiring?
1893 				 */
1894 			}
1895 			vm_map_lock(map);
1896 			if (last_timestamp + 1 != map->timestamp) {
1897 				/*
1898 				 * Look again for the entry because the map was
1899 				 * modified while it was unlocked.
1900 				 * Specifically, the entry may have been
1901 				 * clipped, merged, or deleted.
1902 				 */
1903 				if (!vm_map_lookup_entry(map, saved_start,
1904 				    &tmp_entry)) {
1905 					if (flags & VM_MAP_WIRE_HOLESOK)
1906 						tmp_entry = tmp_entry->next;
1907 					else {
1908 						if (saved_start == start) {
1909 							/*
1910 							 * first_entry has been deleted.
1911 							 */
1912 							vm_map_unlock(map);
1913 							return (KERN_INVALID_ADDRESS);
1914 						}
1915 						end = saved_start;
1916 						rv = KERN_INVALID_ADDRESS;
1917 						goto done;
1918 					}
1919 				}
1920 				if (entry == first_entry)
1921 					first_entry = tmp_entry;
1922 				else
1923 					first_entry = NULL;
1924 				entry = tmp_entry;
1925 			}
1926 			last_timestamp = map->timestamp;
1927 			continue;
1928 		}
1929 		vm_map_clip_start(map, entry, start);
1930 		vm_map_clip_end(map, entry, end);
1931 		/*
1932 		 * Mark the entry in case the map lock is released.  (See
1933 		 * above.)
1934 		 */
1935 		entry->eflags |= MAP_ENTRY_IN_TRANSITION;
1936 		/*
1937 		 *
1938 		 */
1939 		if (entry->wired_count == 0) {
1940 			entry->wired_count++;
1941 			saved_start = entry->start;
1942 			saved_end = entry->end;
1943 			fictitious = entry->object.vm_object != NULL &&
1944 			    entry->object.vm_object->type == OBJT_DEVICE;
1945 			/*
1946 			 * Release the map lock, relying on the in-transition
1947 			 * mark.
1948 			 */
1949 			vm_map_unlock(map);
1950 			rv = vm_fault_wire(map, saved_start, saved_end,
1951 			    user_wire, fictitious);
1952 			vm_map_lock(map);
1953 			if (last_timestamp + 1 != map->timestamp) {
1954 				/*
1955 				 * Look again for the entry because the map was
1956 				 * modified while it was unlocked.  The entry
1957 				 * may have been clipped, but NOT merged or
1958 				 * deleted.
1959 				 */
1960 				result = vm_map_lookup_entry(map, saved_start,
1961 				    &tmp_entry);
1962 				KASSERT(result, ("vm_map_wire: lookup failed"));
1963 				if (entry == first_entry)
1964 					first_entry = tmp_entry;
1965 				else
1966 					first_entry = NULL;
1967 				entry = tmp_entry;
1968 				while (entry->end < saved_end) {
1969 					if (rv != KERN_SUCCESS) {
1970 						KASSERT(entry->wired_count == 1,
1971 						    ("vm_map_wire: bad count"));
1972 						entry->wired_count = -1;
1973 					}
1974 					entry = entry->next;
1975 				}
1976 			}
1977 			last_timestamp = map->timestamp;
1978 			if (rv != KERN_SUCCESS) {
1979 				KASSERT(entry->wired_count == 1,
1980 				    ("vm_map_wire: bad count"));
1981 				/*
1982 				 * Assign an out-of-range value to represent
1983 				 * the failure to wire this entry.
1984 				 */
1985 				entry->wired_count = -1;
1986 				end = entry->end;
1987 				goto done;
1988 			}
1989 		} else if (!user_wire ||
1990 			   (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
1991 			entry->wired_count++;
1992 		}
1993 		/*
1994 		 * Check the map for holes in the specified region.
1995 		 * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
1996 		 */
1997 		if (((flags & VM_MAP_WIRE_HOLESOK) == 0) &&
1998 		    (entry->end < end && (entry->next == &map->header ||
1999 		    entry->next->start > entry->end))) {
2000 			end = entry->end;
2001 			rv = KERN_INVALID_ADDRESS;
2002 			goto done;
2003 		}
2004 		entry = entry->next;
2005 	}
2006 	rv = KERN_SUCCESS;
2007 done:
2008 	need_wakeup = FALSE;
2009 	if (first_entry == NULL) {
2010 		result = vm_map_lookup_entry(map, start, &first_entry);
2011 		if (!result && (flags & VM_MAP_WIRE_HOLESOK))
2012 			first_entry = first_entry->next;
2013 		else
2014 			KASSERT(result, ("vm_map_wire: lookup failed"));
2015 	}
2016 	entry = first_entry;
2017 	while (entry != &map->header && entry->start < end) {
2018 		if (rv == KERN_SUCCESS) {
2019 			if (user_wire)
2020 				entry->eflags |= MAP_ENTRY_USER_WIRED;
2021 		} else if (entry->wired_count == -1) {
2022 			/*
2023 			 * Wiring failed on this entry.  Thus, unwiring is
2024 			 * unnecessary.
2025 			 */
2026 			entry->wired_count = 0;
2027 		} else {
2028 			if (!user_wire ||
2029 			    (entry->eflags & MAP_ENTRY_USER_WIRED) == 0)
2030 				entry->wired_count--;
2031 			if (entry->wired_count == 0) {
2032 				/*
2033 				 * Retain the map lock.
2034 				 */
2035 				vm_fault_unwire(map, entry->start, entry->end,
2036 				    entry->object.vm_object != NULL &&
2037 				    entry->object.vm_object->type == OBJT_DEVICE);
2038 			}
2039 		}
2040 		KASSERT(entry->eflags & MAP_ENTRY_IN_TRANSITION,
2041 			("vm_map_wire: in-transition flag missing"));
2042 		entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
2043 		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
2044 			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
2045 			need_wakeup = TRUE;
2046 		}
2047 		vm_map_simplify_entry(map, entry);
2048 		entry = entry->next;
2049 	}
2050 	vm_map_unlock(map);
2051 	if (need_wakeup)
2052 		vm_map_wakeup(map);
2053 	return (rv);
2054 }
2055 
2056 /*
2057  * vm_map_sync
2058  *
2059  * Push any dirty cached pages in the address range to their pager.
2060  * If syncio is TRUE, dirty pages are written synchronously.
2061  * If invalidate is TRUE, any cached pages are freed as well.
2062  *
2063  * If the size of the region from start to end is zero, we are
2064  * supposed to flush all modified pages within the region containing
2065  * start.  Unfortunately, a region can be split or coalesced with
2066  * neighboring regions, making it difficult to determine what the
2067  * original region was.  Therefore, we approximate this requirement by
2068  * flushing the current region containing start.
2069  *
2070  * Returns an error if any part of the specified range is not mapped.
2071  */
2072 int
2073 vm_map_sync(
2074 	vm_map_t map,
2075 	vm_offset_t start,
2076 	vm_offset_t end,
2077 	boolean_t syncio,
2078 	boolean_t invalidate)
2079 {
2080 	vm_map_entry_t current;
2081 	vm_map_entry_t entry;
2082 	vm_size_t size;
2083 	vm_object_t object;
2084 	vm_ooffset_t offset;
2085 
2086 	vm_map_lock_read(map);
2087 	VM_MAP_RANGE_CHECK(map, start, end);
2088 	if (!vm_map_lookup_entry(map, start, &entry)) {
2089 		vm_map_unlock_read(map);
2090 		return (KERN_INVALID_ADDRESS);
2091 	} else if (start == end) {
2092 		start = entry->start;
2093 		end = entry->end;
2094 	}
2095 	/*
2096 	 * Make a first pass to check for user-wired memory and holes.
2097 	 */
2098 	for (current = entry; current->start < end; current = current->next) {
2099 		if (invalidate && (current->eflags & MAP_ENTRY_USER_WIRED)) {
2100 			vm_map_unlock_read(map);
2101 			return (KERN_INVALID_ARGUMENT);
2102 		}
2103 		if (end > current->end &&
2104 		    (current->next == &map->header ||
2105 			current->end != current->next->start)) {
2106 			vm_map_unlock_read(map);
2107 			return (KERN_INVALID_ADDRESS);
2108 		}
2109 	}
2110 
2111 	if (invalidate) {
2112 		VM_LOCK_GIANT();
2113 		pmap_remove(map->pmap, start, end);
2114 		VM_UNLOCK_GIANT();
2115 	}
2116 	/*
2117 	 * Make a second pass, cleaning/uncaching pages from the indicated
2118 	 * objects as we go.
2119 	 */
2120 	for (current = entry; current->start < end; current = current->next) {
2121 		offset = current->offset + (start - current->start);
2122 		size = (end <= current->end ? end : current->end) - start;
2123 		if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
2124 			vm_map_t smap;
2125 			vm_map_entry_t tentry;
2126 			vm_size_t tsize;
2127 
2128 			smap = current->object.sub_map;
2129 			vm_map_lock_read(smap);
2130 			(void) vm_map_lookup_entry(smap, offset, &tentry);
2131 			tsize = tentry->end - offset;
2132 			if (tsize < size)
2133 				size = tsize;
2134 			object = tentry->object.vm_object;
2135 			offset = tentry->offset + (offset - tentry->start);
2136 			vm_map_unlock_read(smap);
2137 		} else {
2138 			object = current->object.vm_object;
2139 		}
2140 		vm_object_sync(object, offset, size, syncio, invalidate);
2141 		start += size;
2142 	}
2143 
2144 	vm_map_unlock_read(map);
2145 	return (KERN_SUCCESS);
2146 }
2147 
2148 /*
2149  *	vm_map_entry_unwire:	[ internal use only ]
2150  *
2151  *	Make the region specified by this entry pageable.
2152  *
2153  *	The map in question should be locked.
2154  *	[This is the reason for this routine's existence.]
2155  */
2156 static void
2157 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
2158 {
2159 	vm_fault_unwire(map, entry->start, entry->end,
2160 	    entry->object.vm_object != NULL &&
2161 	    entry->object.vm_object->type == OBJT_DEVICE);
2162 	entry->wired_count = 0;
2163 }
2164 
2165 /*
2166  *	vm_map_entry_delete:	[ internal use only ]
2167  *
2168  *	Deallocate the given entry from the target map.
2169  */
2170 static void
2171 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry)
2172 {
2173 	vm_object_t object;
2174 	vm_pindex_t offidxstart, offidxend, count;
2175 
2176 	vm_map_entry_unlink(map, entry);
2177 	map->size -= entry->end - entry->start;
2178 
2179 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0 &&
2180 	    (object = entry->object.vm_object) != NULL) {
2181 		count = OFF_TO_IDX(entry->end - entry->start);
2182 		offidxstart = OFF_TO_IDX(entry->offset);
2183 		offidxend = offidxstart + count;
2184 		VM_OBJECT_LOCK(object);
2185 		if (object->ref_count != 1 &&
2186 		    ((object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING ||
2187 		     object == kernel_object || object == kmem_object) &&
2188 		    (object->type == OBJT_DEFAULT || object->type == OBJT_SWAP)) {
2189 			vm_object_collapse(object);
2190 			vm_object_page_remove(object, offidxstart, offidxend, FALSE);
2191 			if (object->type == OBJT_SWAP)
2192 				swap_pager_freespace(object, offidxstart, count);
2193 			if (offidxend >= object->size &&
2194 			    offidxstart < object->size)
2195 				object->size = offidxstart;
2196 		}
2197 		VM_OBJECT_UNLOCK(object);
2198 		vm_object_deallocate(object);
2199 	}
2200 
2201 	vm_map_entry_dispose(map, entry);
2202 }
2203 
2204 /*
2205  *	vm_map_delete:	[ internal use only ]
2206  *
2207  *	Deallocates the given address range from the target
2208  *	map.
2209  */
2210 int
2211 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
2212 {
2213 	vm_map_entry_t entry;
2214 	vm_map_entry_t first_entry;
2215 
2216 	/*
2217 	 * Find the start of the region, and clip it
2218 	 */
2219 	if (!vm_map_lookup_entry(map, start, &first_entry))
2220 		entry = first_entry->next;
2221 	else {
2222 		entry = first_entry;
2223 		vm_map_clip_start(map, entry, start);
2224 	}
2225 
2226 	/*
2227 	 * Step through all entries in this region
2228 	 */
2229 	while ((entry != &map->header) && (entry->start < end)) {
2230 		vm_map_entry_t next;
2231 
2232 		/*
2233 		 * Wait for wiring or unwiring of an entry to complete.
2234 		 * Also wait for any system wirings to disappear on
2235 		 * user maps.
2236 		 */
2237 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 ||
2238 		    (vm_map_pmap(map) != kernel_pmap &&
2239 		    vm_map_entry_system_wired_count(entry) != 0)) {
2240 			unsigned int last_timestamp;
2241 			vm_offset_t saved_start;
2242 			vm_map_entry_t tmp_entry;
2243 
2244 			saved_start = entry->start;
2245 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2246 			last_timestamp = map->timestamp;
2247 			(void) vm_map_unlock_and_wait(map, FALSE);
2248 			vm_map_lock(map);
2249 			if (last_timestamp + 1 != map->timestamp) {
2250 				/*
2251 				 * Look again for the entry because the map was
2252 				 * modified while it was unlocked.
2253 				 * Specifically, the entry may have been
2254 				 * clipped, merged, or deleted.
2255 				 */
2256 				if (!vm_map_lookup_entry(map, saved_start,
2257 							 &tmp_entry))
2258 					entry = tmp_entry->next;
2259 				else {
2260 					entry = tmp_entry;
2261 					vm_map_clip_start(map, entry,
2262 							  saved_start);
2263 				}
2264 			}
2265 			continue;
2266 		}
2267 		vm_map_clip_end(map, entry, end);
2268 
2269 		next = entry->next;
2270 
2271 		/*
2272 		 * Unwire before removing addresses from the pmap; otherwise,
2273 		 * unwiring will put the entries back in the pmap.
2274 		 */
2275 		if (entry->wired_count != 0) {
2276 			vm_map_entry_unwire(map, entry);
2277 		}
2278 
2279 		if (!map->system_map)
2280 			VM_LOCK_GIANT();
2281 		pmap_remove(map->pmap, entry->start, entry->end);
2282 		if (!map->system_map)
2283 			VM_UNLOCK_GIANT();
2284 
2285 		/*
2286 		 * Delete the entry (which may delete the object) only after
2287 		 * removing all pmap entries pointing to its pages.
2288 		 * (Otherwise, its page frames may be reallocated, and any
2289 		 * modify bits will be set in the wrong object!)
2290 		 */
2291 		vm_map_entry_delete(map, entry);
2292 		entry = next;
2293 	}
2294 	return (KERN_SUCCESS);
2295 }
2296 
2297 /*
2298  *	vm_map_remove:
2299  *
2300  *	Remove the given address range from the target map.
2301  *	This is the exported form of vm_map_delete.
2302  */
2303 int
2304 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
2305 {
2306 	int result;
2307 
2308 	vm_map_lock(map);
2309 	VM_MAP_RANGE_CHECK(map, start, end);
2310 	result = vm_map_delete(map, start, end);
2311 	vm_map_unlock(map);
2312 	return (result);
2313 }
2314 
2315 /*
2316  *	vm_map_check_protection:
2317  *
2318  *	Assert that the target map allows the specified privilege on the
2319  *	entire address region given.  The entire region must be allocated.
2320  *
2321  *	WARNING!  This code does not and should not check whether the
2322  *	contents of the region is accessible.  For example a smaller file
2323  *	might be mapped into a larger address space.
2324  *
2325  *	NOTE!  This code is also called by munmap().
2326  *
2327  *	The map must be locked.  A read lock is sufficient.
2328  */
2329 boolean_t
2330 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
2331 			vm_prot_t protection)
2332 {
2333 	vm_map_entry_t entry;
2334 	vm_map_entry_t tmp_entry;
2335 
2336 	if (!vm_map_lookup_entry(map, start, &tmp_entry))
2337 		return (FALSE);
2338 	entry = tmp_entry;
2339 
2340 	while (start < end) {
2341 		if (entry == &map->header)
2342 			return (FALSE);
2343 		/*
2344 		 * No holes allowed!
2345 		 */
2346 		if (start < entry->start)
2347 			return (FALSE);
2348 		/*
2349 		 * Check protection associated with entry.
2350 		 */
2351 		if ((entry->protection & protection) != protection)
2352 			return (FALSE);
2353 		/* go to next entry */
2354 		start = entry->end;
2355 		entry = entry->next;
2356 	}
2357 	return (TRUE);
2358 }
2359 
2360 /*
2361  *	vm_map_copy_entry:
2362  *
2363  *	Copies the contents of the source entry to the destination
2364  *	entry.  The entries *must* be aligned properly.
2365  */
2366 static void
2367 vm_map_copy_entry(
2368 	vm_map_t src_map,
2369 	vm_map_t dst_map,
2370 	vm_map_entry_t src_entry,
2371 	vm_map_entry_t dst_entry)
2372 {
2373 	vm_object_t src_object;
2374 
2375 	if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
2376 		return;
2377 
2378 	if (src_entry->wired_count == 0) {
2379 
2380 		/*
2381 		 * If the source entry is marked needs_copy, it is already
2382 		 * write-protected.
2383 		 */
2384 		if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) {
2385 			pmap_protect(src_map->pmap,
2386 			    src_entry->start,
2387 			    src_entry->end,
2388 			    src_entry->protection & ~VM_PROT_WRITE);
2389 		}
2390 
2391 		/*
2392 		 * Make a copy of the object.
2393 		 */
2394 		if ((src_object = src_entry->object.vm_object) != NULL) {
2395 			VM_OBJECT_LOCK(src_object);
2396 			if ((src_object->handle == NULL) &&
2397 				(src_object->type == OBJT_DEFAULT ||
2398 				 src_object->type == OBJT_SWAP)) {
2399 				vm_object_collapse(src_object);
2400 				if ((src_object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING) {
2401 					vm_object_split(src_entry);
2402 					src_object = src_entry->object.vm_object;
2403 				}
2404 			}
2405 			vm_object_reference_locked(src_object);
2406 			vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
2407 			VM_OBJECT_UNLOCK(src_object);
2408 			dst_entry->object.vm_object = src_object;
2409 			src_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
2410 			dst_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
2411 			dst_entry->offset = src_entry->offset;
2412 		} else {
2413 			dst_entry->object.vm_object = NULL;
2414 			dst_entry->offset = 0;
2415 		}
2416 
2417 		pmap_copy(dst_map->pmap, src_map->pmap, dst_entry->start,
2418 		    dst_entry->end - dst_entry->start, src_entry->start);
2419 	} else {
2420 		/*
2421 		 * Of course, wired down pages can't be set copy-on-write.
2422 		 * Cause wired pages to be copied into the new map by
2423 		 * simulating faults (the new pages are pageable)
2424 		 */
2425 		vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry);
2426 	}
2427 }
2428 
2429 /*
2430  * vmspace_map_entry_forked:
2431  * Update the newly-forked vmspace each time a map entry is inherited
2432  * or copied.  The values for vm_dsize and vm_tsize are approximate
2433  * (and mostly-obsolete ideas in the face of mmap(2) et al.)
2434  */
2435 static void
2436 vmspace_map_entry_forked(const struct vmspace *vm1, struct vmspace *vm2,
2437     vm_map_entry_t entry)
2438 {
2439 	vm_size_t entrysize;
2440 	vm_offset_t newend;
2441 
2442 	entrysize = entry->end - entry->start;
2443 	vm2->vm_map.size += entrysize;
2444 	if (entry->eflags & (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP)) {
2445 		vm2->vm_ssize += btoc(entrysize);
2446 	} else if (entry->start >= (vm_offset_t)vm1->vm_daddr &&
2447 	    entry->start < (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize)) {
2448 		newend = MIN(entry->end,
2449 		    (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize));
2450 		vm2->vm_dsize += btoc(newend - entry->start);
2451 	} else if (entry->start >= (vm_offset_t)vm1->vm_taddr &&
2452 	    entry->start < (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize)) {
2453 		newend = MIN(entry->end,
2454 		    (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize));
2455 		vm2->vm_tsize += btoc(newend - entry->start);
2456 	}
2457 }
2458 
2459 /*
2460  * vmspace_fork:
2461  * Create a new process vmspace structure and vm_map
2462  * based on those of an existing process.  The new map
2463  * is based on the old map, according to the inheritance
2464  * values on the regions in that map.
2465  *
2466  * XXX It might be worth coalescing the entries added to the new vmspace.
2467  *
2468  * The source map must not be locked.
2469  */
2470 struct vmspace *
2471 vmspace_fork(struct vmspace *vm1)
2472 {
2473 	struct vmspace *vm2;
2474 	vm_map_t old_map = &vm1->vm_map;
2475 	vm_map_t new_map;
2476 	vm_map_entry_t old_entry;
2477 	vm_map_entry_t new_entry;
2478 	vm_object_t object;
2479 
2480 	vm_map_lock(old_map);
2481 
2482 	vm2 = vmspace_alloc(old_map->min_offset, old_map->max_offset);
2483 	vm2->vm_taddr = vm1->vm_taddr;
2484 	vm2->vm_daddr = vm1->vm_daddr;
2485 	vm2->vm_maxsaddr = vm1->vm_maxsaddr;
2486 	new_map = &vm2->vm_map;	/* XXX */
2487 	new_map->timestamp = 1;
2488 
2489 	/* Do not inherit the MAP_WIREFUTURE property. */
2490 	if ((new_map->flags & MAP_WIREFUTURE) == MAP_WIREFUTURE)
2491 		new_map->flags &= ~MAP_WIREFUTURE;
2492 
2493 	old_entry = old_map->header.next;
2494 
2495 	while (old_entry != &old_map->header) {
2496 		if (old_entry->eflags & MAP_ENTRY_IS_SUB_MAP)
2497 			panic("vm_map_fork: encountered a submap");
2498 
2499 		switch (old_entry->inheritance) {
2500 		case VM_INHERIT_NONE:
2501 			break;
2502 
2503 		case VM_INHERIT_SHARE:
2504 			/*
2505 			 * Clone the entry, creating the shared object if necessary.
2506 			 */
2507 			object = old_entry->object.vm_object;
2508 			if (object == NULL) {
2509 				object = vm_object_allocate(OBJT_DEFAULT,
2510 					atop(old_entry->end - old_entry->start));
2511 				old_entry->object.vm_object = object;
2512 				old_entry->offset = (vm_offset_t) 0;
2513 			}
2514 
2515 			/*
2516 			 * Add the reference before calling vm_object_shadow
2517 			 * to insure that a shadow object is created.
2518 			 */
2519 			vm_object_reference(object);
2520 			if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
2521 				vm_object_shadow(&old_entry->object.vm_object,
2522 					&old_entry->offset,
2523 					atop(old_entry->end - old_entry->start));
2524 				old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
2525 				/* Transfer the second reference too. */
2526 				vm_object_reference(
2527 				    old_entry->object.vm_object);
2528 				vm_object_deallocate(object);
2529 				object = old_entry->object.vm_object;
2530 			}
2531 			VM_OBJECT_LOCK(object);
2532 			vm_object_clear_flag(object, OBJ_ONEMAPPING);
2533 			VM_OBJECT_UNLOCK(object);
2534 
2535 			/*
2536 			 * Clone the entry, referencing the shared object.
2537 			 */
2538 			new_entry = vm_map_entry_create(new_map);
2539 			*new_entry = *old_entry;
2540 			new_entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2541 			new_entry->wired_count = 0;
2542 
2543 			/*
2544 			 * Insert the entry into the new map -- we know we're
2545 			 * inserting at the end of the new map.
2546 			 */
2547 			vm_map_entry_link(new_map, new_map->header.prev,
2548 			    new_entry);
2549 			vmspace_map_entry_forked(vm1, vm2, new_entry);
2550 
2551 			/*
2552 			 * Update the physical map
2553 			 */
2554 			pmap_copy(new_map->pmap, old_map->pmap,
2555 			    new_entry->start,
2556 			    (old_entry->end - old_entry->start),
2557 			    old_entry->start);
2558 			break;
2559 
2560 		case VM_INHERIT_COPY:
2561 			/*
2562 			 * Clone the entry and link into the map.
2563 			 */
2564 			new_entry = vm_map_entry_create(new_map);
2565 			*new_entry = *old_entry;
2566 			new_entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2567 			new_entry->wired_count = 0;
2568 			new_entry->object.vm_object = NULL;
2569 			vm_map_entry_link(new_map, new_map->header.prev,
2570 			    new_entry);
2571 			vmspace_map_entry_forked(vm1, vm2, new_entry);
2572 			vm_map_copy_entry(old_map, new_map, old_entry,
2573 			    new_entry);
2574 			break;
2575 		}
2576 		old_entry = old_entry->next;
2577 	}
2578 
2579 	vm_map_unlock(old_map);
2580 
2581 	return (vm2);
2582 }
2583 
2584 int
2585 vm_map_stack(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
2586     vm_prot_t prot, vm_prot_t max, int cow)
2587 {
2588 	vm_map_entry_t new_entry, prev_entry;
2589 	vm_offset_t bot, top;
2590 	vm_size_t init_ssize;
2591 	int orient, rv;
2592 	rlim_t vmemlim;
2593 
2594 	/*
2595 	 * The stack orientation is piggybacked with the cow argument.
2596 	 * Extract it into orient and mask the cow argument so that we
2597 	 * don't pass it around further.
2598 	 * NOTE: We explicitly allow bi-directional stacks.
2599 	 */
2600 	orient = cow & (MAP_STACK_GROWS_DOWN|MAP_STACK_GROWS_UP);
2601 	cow &= ~orient;
2602 	KASSERT(orient != 0, ("No stack grow direction"));
2603 
2604 	if (addrbos < vm_map_min(map) || addrbos > map->max_offset)
2605 		return (KERN_NO_SPACE);
2606 
2607 	init_ssize = (max_ssize < sgrowsiz) ? max_ssize : sgrowsiz;
2608 
2609 	PROC_LOCK(curthread->td_proc);
2610 	vmemlim = lim_cur(curthread->td_proc, RLIMIT_VMEM);
2611 	PROC_UNLOCK(curthread->td_proc);
2612 
2613 	vm_map_lock(map);
2614 
2615 	/* If addr is already mapped, no go */
2616 	if (vm_map_lookup_entry(map, addrbos, &prev_entry)) {
2617 		vm_map_unlock(map);
2618 		return (KERN_NO_SPACE);
2619 	}
2620 
2621 	/* If we would blow our VMEM resource limit, no go */
2622 	if (map->size + init_ssize > vmemlim) {
2623 		vm_map_unlock(map);
2624 		return (KERN_NO_SPACE);
2625 	}
2626 
2627 	/*
2628 	 * If we can't accomodate max_ssize in the current mapping, no go.
2629 	 * However, we need to be aware that subsequent user mappings might
2630 	 * map into the space we have reserved for stack, and currently this
2631 	 * space is not protected.
2632 	 *
2633 	 * Hopefully we will at least detect this condition when we try to
2634 	 * grow the stack.
2635 	 */
2636 	if ((prev_entry->next != &map->header) &&
2637 	    (prev_entry->next->start < addrbos + max_ssize)) {
2638 		vm_map_unlock(map);
2639 		return (KERN_NO_SPACE);
2640 	}
2641 
2642 	/*
2643 	 * We initially map a stack of only init_ssize.  We will grow as
2644 	 * needed later.  Depending on the orientation of the stack (i.e.
2645 	 * the grow direction) we either map at the top of the range, the
2646 	 * bottom of the range or in the middle.
2647 	 *
2648 	 * Note: we would normally expect prot and max to be VM_PROT_ALL,
2649 	 * and cow to be 0.  Possibly we should eliminate these as input
2650 	 * parameters, and just pass these values here in the insert call.
2651 	 */
2652 	if (orient == MAP_STACK_GROWS_DOWN)
2653 		bot = addrbos + max_ssize - init_ssize;
2654 	else if (orient == MAP_STACK_GROWS_UP)
2655 		bot = addrbos;
2656 	else
2657 		bot = round_page(addrbos + max_ssize/2 - init_ssize/2);
2658 	top = bot + init_ssize;
2659 	rv = vm_map_insert(map, NULL, 0, bot, top, prot, max, cow);
2660 
2661 	/* Now set the avail_ssize amount. */
2662 	if (rv == KERN_SUCCESS) {
2663 		if (prev_entry != &map->header)
2664 			vm_map_clip_end(map, prev_entry, bot);
2665 		new_entry = prev_entry->next;
2666 		if (new_entry->end != top || new_entry->start != bot)
2667 			panic("Bad entry start/end for new stack entry");
2668 
2669 		new_entry->avail_ssize = max_ssize - init_ssize;
2670 		if (orient & MAP_STACK_GROWS_DOWN)
2671 			new_entry->eflags |= MAP_ENTRY_GROWS_DOWN;
2672 		if (orient & MAP_STACK_GROWS_UP)
2673 			new_entry->eflags |= MAP_ENTRY_GROWS_UP;
2674 	}
2675 
2676 	vm_map_unlock(map);
2677 	return (rv);
2678 }
2679 
2680 /* Attempts to grow a vm stack entry.  Returns KERN_SUCCESS if the
2681  * desired address is already mapped, or if we successfully grow
2682  * the stack.  Also returns KERN_SUCCESS if addr is outside the
2683  * stack range (this is strange, but preserves compatibility with
2684  * the grow function in vm_machdep.c).
2685  */
2686 int
2687 vm_map_growstack(struct proc *p, vm_offset_t addr)
2688 {
2689 	vm_map_entry_t next_entry, prev_entry;
2690 	vm_map_entry_t new_entry, stack_entry;
2691 	struct vmspace *vm = p->p_vmspace;
2692 	vm_map_t map = &vm->vm_map;
2693 	vm_offset_t end;
2694 	size_t grow_amount, max_grow;
2695 	rlim_t stacklim, vmemlim;
2696 	int is_procstack, rv;
2697 
2698 Retry:
2699 	PROC_LOCK(p);
2700 	stacklim = lim_cur(p, RLIMIT_STACK);
2701 	vmemlim = lim_cur(p, RLIMIT_VMEM);
2702 	PROC_UNLOCK(p);
2703 
2704 	vm_map_lock_read(map);
2705 
2706 	/* If addr is already in the entry range, no need to grow.*/
2707 	if (vm_map_lookup_entry(map, addr, &prev_entry)) {
2708 		vm_map_unlock_read(map);
2709 		return (KERN_SUCCESS);
2710 	}
2711 
2712 	next_entry = prev_entry->next;
2713 	if (!(prev_entry->eflags & MAP_ENTRY_GROWS_UP)) {
2714 		/*
2715 		 * This entry does not grow upwards. Since the address lies
2716 		 * beyond this entry, the next entry (if one exists) has to
2717 		 * be a downward growable entry. The entry list header is
2718 		 * never a growable entry, so it suffices to check the flags.
2719 		 */
2720 		if (!(next_entry->eflags & MAP_ENTRY_GROWS_DOWN)) {
2721 			vm_map_unlock_read(map);
2722 			return (KERN_SUCCESS);
2723 		}
2724 		stack_entry = next_entry;
2725 	} else {
2726 		/*
2727 		 * This entry grows upward. If the next entry does not at
2728 		 * least grow downwards, this is the entry we need to grow.
2729 		 * otherwise we have two possible choices and we have to
2730 		 * select one.
2731 		 */
2732 		if (next_entry->eflags & MAP_ENTRY_GROWS_DOWN) {
2733 			/*
2734 			 * We have two choices; grow the entry closest to
2735 			 * the address to minimize the amount of growth.
2736 			 */
2737 			if (addr - prev_entry->end <= next_entry->start - addr)
2738 				stack_entry = prev_entry;
2739 			else
2740 				stack_entry = next_entry;
2741 		} else
2742 			stack_entry = prev_entry;
2743 	}
2744 
2745 	if (stack_entry == next_entry) {
2746 		KASSERT(stack_entry->eflags & MAP_ENTRY_GROWS_DOWN, ("foo"));
2747 		KASSERT(addr < stack_entry->start, ("foo"));
2748 		end = (prev_entry != &map->header) ? prev_entry->end :
2749 		    stack_entry->start - stack_entry->avail_ssize;
2750 		grow_amount = roundup(stack_entry->start - addr, PAGE_SIZE);
2751 		max_grow = stack_entry->start - end;
2752 	} else {
2753 		KASSERT(stack_entry->eflags & MAP_ENTRY_GROWS_UP, ("foo"));
2754 		KASSERT(addr >= stack_entry->end, ("foo"));
2755 		end = (next_entry != &map->header) ? next_entry->start :
2756 		    stack_entry->end + stack_entry->avail_ssize;
2757 		grow_amount = roundup(addr + 1 - stack_entry->end, PAGE_SIZE);
2758 		max_grow = end - stack_entry->end;
2759 	}
2760 
2761 	if (grow_amount > stack_entry->avail_ssize) {
2762 		vm_map_unlock_read(map);
2763 		return (KERN_NO_SPACE);
2764 	}
2765 
2766 	/*
2767 	 * If there is no longer enough space between the entries nogo, and
2768 	 * adjust the available space.  Note: this  should only happen if the
2769 	 * user has mapped into the stack area after the stack was created,
2770 	 * and is probably an error.
2771 	 *
2772 	 * This also effectively destroys any guard page the user might have
2773 	 * intended by limiting the stack size.
2774 	 */
2775 	if (grow_amount > max_grow) {
2776 		if (vm_map_lock_upgrade(map))
2777 			goto Retry;
2778 
2779 		stack_entry->avail_ssize = max_grow;
2780 
2781 		vm_map_unlock(map);
2782 		return (KERN_NO_SPACE);
2783 	}
2784 
2785 	is_procstack = (addr >= (vm_offset_t)vm->vm_maxsaddr) ? 1 : 0;
2786 
2787 	/*
2788 	 * If this is the main process stack, see if we're over the stack
2789 	 * limit.
2790 	 */
2791 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
2792 		vm_map_unlock_read(map);
2793 		return (KERN_NO_SPACE);
2794 	}
2795 
2796 	/* Round up the grow amount modulo SGROWSIZ */
2797 	grow_amount = roundup (grow_amount, sgrowsiz);
2798 	if (grow_amount > stack_entry->avail_ssize)
2799 		grow_amount = stack_entry->avail_ssize;
2800 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
2801 		grow_amount = stacklim - ctob(vm->vm_ssize);
2802 	}
2803 
2804 	/* If we would blow our VMEM resource limit, no go */
2805 	if (map->size + grow_amount > vmemlim) {
2806 		vm_map_unlock_read(map);
2807 		return (KERN_NO_SPACE);
2808 	}
2809 
2810 	if (vm_map_lock_upgrade(map))
2811 		goto Retry;
2812 
2813 	if (stack_entry == next_entry) {
2814 		/*
2815 		 * Growing downward.
2816 		 */
2817 		/* Get the preliminary new entry start value */
2818 		addr = stack_entry->start - grow_amount;
2819 
2820 		/*
2821 		 * If this puts us into the previous entry, cut back our
2822 		 * growth to the available space. Also, see the note above.
2823 		 */
2824 		if (addr < end) {
2825 			stack_entry->avail_ssize = max_grow;
2826 			addr = end;
2827 		}
2828 
2829 		rv = vm_map_insert(map, NULL, 0, addr, stack_entry->start,
2830 		    p->p_sysent->sv_stackprot, VM_PROT_ALL, 0);
2831 
2832 		/* Adjust the available stack space by the amount we grew. */
2833 		if (rv == KERN_SUCCESS) {
2834 			if (prev_entry != &map->header)
2835 				vm_map_clip_end(map, prev_entry, addr);
2836 			new_entry = prev_entry->next;
2837 			KASSERT(new_entry == stack_entry->prev, ("foo"));
2838 			KASSERT(new_entry->end == stack_entry->start, ("foo"));
2839 			KASSERT(new_entry->start == addr, ("foo"));
2840 			grow_amount = new_entry->end - new_entry->start;
2841 			new_entry->avail_ssize = stack_entry->avail_ssize -
2842 			    grow_amount;
2843 			stack_entry->eflags &= ~MAP_ENTRY_GROWS_DOWN;
2844 			new_entry->eflags |= MAP_ENTRY_GROWS_DOWN;
2845 		}
2846 	} else {
2847 		/*
2848 		 * Growing upward.
2849 		 */
2850 		addr = stack_entry->end + grow_amount;
2851 
2852 		/*
2853 		 * If this puts us into the next entry, cut back our growth
2854 		 * to the available space. Also, see the note above.
2855 		 */
2856 		if (addr > end) {
2857 			stack_entry->avail_ssize = end - stack_entry->end;
2858 			addr = end;
2859 		}
2860 
2861 		grow_amount = addr - stack_entry->end;
2862 
2863 		/* Grow the underlying object if applicable. */
2864 		if (stack_entry->object.vm_object == NULL ||
2865 		    vm_object_coalesce(stack_entry->object.vm_object,
2866 		    stack_entry->offset,
2867 		    (vm_size_t)(stack_entry->end - stack_entry->start),
2868 		    (vm_size_t)grow_amount)) {
2869 			map->size += (addr - stack_entry->end);
2870 			/* Update the current entry. */
2871 			stack_entry->end = addr;
2872 			stack_entry->avail_ssize -= grow_amount;
2873 			vm_map_entry_resize_free(map, stack_entry);
2874 			rv = KERN_SUCCESS;
2875 
2876 			if (next_entry != &map->header)
2877 				vm_map_clip_start(map, next_entry, addr);
2878 		} else
2879 			rv = KERN_FAILURE;
2880 	}
2881 
2882 	if (rv == KERN_SUCCESS && is_procstack)
2883 		vm->vm_ssize += btoc(grow_amount);
2884 
2885 	vm_map_unlock(map);
2886 
2887 	/*
2888 	 * Heed the MAP_WIREFUTURE flag if it was set for this process.
2889 	 */
2890 	if (rv == KERN_SUCCESS && (map->flags & MAP_WIREFUTURE)) {
2891 		vm_map_wire(map,
2892 		    (stack_entry == next_entry) ? addr : addr - grow_amount,
2893 		    (stack_entry == next_entry) ? stack_entry->start : addr,
2894 		    (p->p_flag & P_SYSTEM)
2895 		    ? VM_MAP_WIRE_SYSTEM|VM_MAP_WIRE_NOHOLES
2896 		    : VM_MAP_WIRE_USER|VM_MAP_WIRE_NOHOLES);
2897 	}
2898 
2899 	return (rv);
2900 }
2901 
2902 /*
2903  * Unshare the specified VM space for exec.  If other processes are
2904  * mapped to it, then create a new one.  The new vmspace is null.
2905  */
2906 void
2907 vmspace_exec(struct proc *p, vm_offset_t minuser, vm_offset_t maxuser)
2908 {
2909 	struct vmspace *oldvmspace = p->p_vmspace;
2910 	struct vmspace *newvmspace;
2911 
2912 	GIANT_REQUIRED;
2913 	newvmspace = vmspace_alloc(minuser, maxuser);
2914 	newvmspace->vm_swrss = oldvmspace->vm_swrss;
2915 	/*
2916 	 * This code is written like this for prototype purposes.  The
2917 	 * goal is to avoid running down the vmspace here, but let the
2918 	 * other process's that are still using the vmspace to finally
2919 	 * run it down.  Even though there is little or no chance of blocking
2920 	 * here, it is a good idea to keep this form for future mods.
2921 	 */
2922 	p->p_vmspace = newvmspace;
2923 	if (p == curthread->td_proc)		/* XXXKSE ? */
2924 		pmap_activate(curthread);
2925 	vmspace_free(oldvmspace);
2926 }
2927 
2928 /*
2929  * Unshare the specified VM space for forcing COW.  This
2930  * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
2931  */
2932 void
2933 vmspace_unshare(struct proc *p)
2934 {
2935 	struct vmspace *oldvmspace = p->p_vmspace;
2936 	struct vmspace *newvmspace;
2937 
2938 	if (oldvmspace->vm_refcnt == 1)
2939 		return;
2940 	newvmspace = vmspace_fork(oldvmspace);
2941 	p->p_vmspace = newvmspace;
2942 	if (p == curthread->td_proc)		/* XXXKSE ? */
2943 		pmap_activate(curthread);
2944 	vmspace_free(oldvmspace);
2945 }
2946 
2947 /*
2948  *	vm_map_lookup:
2949  *
2950  *	Finds the VM object, offset, and
2951  *	protection for a given virtual address in the
2952  *	specified map, assuming a page fault of the
2953  *	type specified.
2954  *
2955  *	Leaves the map in question locked for read; return
2956  *	values are guaranteed until a vm_map_lookup_done
2957  *	call is performed.  Note that the map argument
2958  *	is in/out; the returned map must be used in
2959  *	the call to vm_map_lookup_done.
2960  *
2961  *	A handle (out_entry) is returned for use in
2962  *	vm_map_lookup_done, to make that fast.
2963  *
2964  *	If a lookup is requested with "write protection"
2965  *	specified, the map may be changed to perform virtual
2966  *	copying operations, although the data referenced will
2967  *	remain the same.
2968  */
2969 int
2970 vm_map_lookup(vm_map_t *var_map,		/* IN/OUT */
2971 	      vm_offset_t vaddr,
2972 	      vm_prot_t fault_typea,
2973 	      vm_map_entry_t *out_entry,	/* OUT */
2974 	      vm_object_t *object,		/* OUT */
2975 	      vm_pindex_t *pindex,		/* OUT */
2976 	      vm_prot_t *out_prot,		/* OUT */
2977 	      boolean_t *wired)			/* OUT */
2978 {
2979 	vm_map_entry_t entry;
2980 	vm_map_t map = *var_map;
2981 	vm_prot_t prot;
2982 	vm_prot_t fault_type = fault_typea;
2983 
2984 RetryLookup:;
2985 	/*
2986 	 * Lookup the faulting address.
2987 	 */
2988 
2989 	vm_map_lock_read(map);
2990 #define	RETURN(why) \
2991 		{ \
2992 		vm_map_unlock_read(map); \
2993 		return (why); \
2994 		}
2995 
2996 	/*
2997 	 * If the map has an interesting hint, try it before calling full
2998 	 * blown lookup routine.
2999 	 */
3000 	entry = map->root;
3001 	*out_entry = entry;
3002 	if (entry == NULL ||
3003 	    (vaddr < entry->start) || (vaddr >= entry->end)) {
3004 		/*
3005 		 * Entry was either not a valid hint, or the vaddr was not
3006 		 * contained in the entry, so do a full lookup.
3007 		 */
3008 		if (!vm_map_lookup_entry(map, vaddr, out_entry))
3009 			RETURN(KERN_INVALID_ADDRESS);
3010 
3011 		entry = *out_entry;
3012 	}
3013 
3014 	/*
3015 	 * Handle submaps.
3016 	 */
3017 	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
3018 		vm_map_t old_map = map;
3019 
3020 		*var_map = map = entry->object.sub_map;
3021 		vm_map_unlock_read(old_map);
3022 		goto RetryLookup;
3023 	}
3024 
3025 	/*
3026 	 * Check whether this task is allowed to have this page.
3027 	 * Note the special case for MAP_ENTRY_COW
3028 	 * pages with an override.  This is to implement a forced
3029 	 * COW for debuggers.
3030 	 */
3031 	if (fault_type & VM_PROT_OVERRIDE_WRITE)
3032 		prot = entry->max_protection;
3033 	else
3034 		prot = entry->protection;
3035 	fault_type &= (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE);
3036 	if ((fault_type & prot) != fault_type) {
3037 			RETURN(KERN_PROTECTION_FAILURE);
3038 	}
3039 	if ((entry->eflags & MAP_ENTRY_USER_WIRED) &&
3040 	    (entry->eflags & MAP_ENTRY_COW) &&
3041 	    (fault_type & VM_PROT_WRITE) &&
3042 	    (fault_typea & VM_PROT_OVERRIDE_WRITE) == 0) {
3043 		RETURN(KERN_PROTECTION_FAILURE);
3044 	}
3045 
3046 	/*
3047 	 * If this page is not pageable, we have to get it for all possible
3048 	 * accesses.
3049 	 */
3050 	*wired = (entry->wired_count != 0);
3051 	if (*wired)
3052 		prot = fault_type = entry->protection;
3053 
3054 	/*
3055 	 * If the entry was copy-on-write, we either ...
3056 	 */
3057 	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3058 		/*
3059 		 * If we want to write the page, we may as well handle that
3060 		 * now since we've got the map locked.
3061 		 *
3062 		 * If we don't need to write the page, we just demote the
3063 		 * permissions allowed.
3064 		 */
3065 		if (fault_type & VM_PROT_WRITE) {
3066 			/*
3067 			 * Make a new object, and place it in the object
3068 			 * chain.  Note that no new references have appeared
3069 			 * -- one just moved from the map to the new
3070 			 * object.
3071 			 */
3072 			if (vm_map_lock_upgrade(map))
3073 				goto RetryLookup;
3074 
3075 			vm_object_shadow(
3076 			    &entry->object.vm_object,
3077 			    &entry->offset,
3078 			    atop(entry->end - entry->start));
3079 			entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
3080 
3081 			vm_map_lock_downgrade(map);
3082 		} else {
3083 			/*
3084 			 * We're attempting to read a copy-on-write page --
3085 			 * don't allow writes.
3086 			 */
3087 			prot &= ~VM_PROT_WRITE;
3088 		}
3089 	}
3090 
3091 	/*
3092 	 * Create an object if necessary.
3093 	 */
3094 	if (entry->object.vm_object == NULL &&
3095 	    !map->system_map) {
3096 		if (vm_map_lock_upgrade(map))
3097 			goto RetryLookup;
3098 		entry->object.vm_object = vm_object_allocate(OBJT_DEFAULT,
3099 		    atop(entry->end - entry->start));
3100 		entry->offset = 0;
3101 		vm_map_lock_downgrade(map);
3102 	}
3103 
3104 	/*
3105 	 * Return the object/offset from this entry.  If the entry was
3106 	 * copy-on-write or empty, it has been fixed up.
3107 	 */
3108 	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
3109 	*object = entry->object.vm_object;
3110 
3111 	*out_prot = prot;
3112 	return (KERN_SUCCESS);
3113 
3114 #undef	RETURN
3115 }
3116 
3117 /*
3118  *	vm_map_lookup_locked:
3119  *
3120  *	Lookup the faulting address.  A version of vm_map_lookup that returns
3121  *      KERN_FAILURE instead of blocking on map lock or memory allocation.
3122  */
3123 int
3124 vm_map_lookup_locked(vm_map_t *var_map,		/* IN/OUT */
3125 		     vm_offset_t vaddr,
3126 		     vm_prot_t fault_typea,
3127 		     vm_map_entry_t *out_entry,	/* OUT */
3128 		     vm_object_t *object,	/* OUT */
3129 		     vm_pindex_t *pindex,	/* OUT */
3130 		     vm_prot_t *out_prot,	/* OUT */
3131 		     boolean_t *wired)		/* OUT */
3132 {
3133 	vm_map_entry_t entry;
3134 	vm_map_t map = *var_map;
3135 	vm_prot_t prot;
3136 	vm_prot_t fault_type = fault_typea;
3137 
3138 	/*
3139 	 * If the map has an interesting hint, try it before calling full
3140 	 * blown lookup routine.
3141 	 */
3142 	entry = map->root;
3143 	*out_entry = entry;
3144 	if (entry == NULL ||
3145 	    (vaddr < entry->start) || (vaddr >= entry->end)) {
3146 		/*
3147 		 * Entry was either not a valid hint, or the vaddr was not
3148 		 * contained in the entry, so do a full lookup.
3149 		 */
3150 		if (!vm_map_lookup_entry(map, vaddr, out_entry))
3151 			return (KERN_INVALID_ADDRESS);
3152 
3153 		entry = *out_entry;
3154 	}
3155 
3156 	/*
3157 	 * Fail if the entry refers to a submap.
3158 	 */
3159 	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
3160 		return (KERN_FAILURE);
3161 
3162 	/*
3163 	 * Check whether this task is allowed to have this page.
3164 	 * Note the special case for MAP_ENTRY_COW
3165 	 * pages with an override.  This is to implement a forced
3166 	 * COW for debuggers.
3167 	 */
3168 	if (fault_type & VM_PROT_OVERRIDE_WRITE)
3169 		prot = entry->max_protection;
3170 	else
3171 		prot = entry->protection;
3172 	fault_type &= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
3173 	if ((fault_type & prot) != fault_type)
3174 		return (KERN_PROTECTION_FAILURE);
3175 	if ((entry->eflags & MAP_ENTRY_USER_WIRED) &&
3176 	    (entry->eflags & MAP_ENTRY_COW) &&
3177 	    (fault_type & VM_PROT_WRITE) &&
3178 	    (fault_typea & VM_PROT_OVERRIDE_WRITE) == 0)
3179 		return (KERN_PROTECTION_FAILURE);
3180 
3181 	/*
3182 	 * If this page is not pageable, we have to get it for all possible
3183 	 * accesses.
3184 	 */
3185 	*wired = (entry->wired_count != 0);
3186 	if (*wired)
3187 		prot = fault_type = entry->protection;
3188 
3189 	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3190 		/*
3191 		 * Fail if the entry was copy-on-write for a write fault.
3192 		 */
3193 		if (fault_type & VM_PROT_WRITE)
3194 			return (KERN_FAILURE);
3195 		/*
3196 		 * We're attempting to read a copy-on-write page --
3197 		 * don't allow writes.
3198 		 */
3199 		prot &= ~VM_PROT_WRITE;
3200 	}
3201 
3202 	/*
3203 	 * Fail if an object should be created.
3204 	 */
3205 	if (entry->object.vm_object == NULL && !map->system_map)
3206 		return (KERN_FAILURE);
3207 
3208 	/*
3209 	 * Return the object/offset from this entry.  If the entry was
3210 	 * copy-on-write or empty, it has been fixed up.
3211 	 */
3212 	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
3213 	*object = entry->object.vm_object;
3214 
3215 	*out_prot = prot;
3216 	return (KERN_SUCCESS);
3217 }
3218 
3219 /*
3220  *	vm_map_lookup_done:
3221  *
3222  *	Releases locks acquired by a vm_map_lookup
3223  *	(according to the handle returned by that lookup).
3224  */
3225 void
3226 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry)
3227 {
3228 	/*
3229 	 * Unlock the main-level map
3230 	 */
3231 	vm_map_unlock_read(map);
3232 }
3233 
3234 #include "opt_ddb.h"
3235 #ifdef DDB
3236 #include <sys/kernel.h>
3237 
3238 #include <ddb/ddb.h>
3239 
3240 /*
3241  *	vm_map_print:	[ debug ]
3242  */
3243 DB_SHOW_COMMAND(map, vm_map_print)
3244 {
3245 	static int nlines;
3246 	/* XXX convert args. */
3247 	vm_map_t map = (vm_map_t)addr;
3248 	boolean_t full = have_addr;
3249 
3250 	vm_map_entry_t entry;
3251 
3252 	db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
3253 	    (void *)map,
3254 	    (void *)map->pmap, map->nentries, map->timestamp);
3255 	nlines++;
3256 
3257 	if (!full && db_indent)
3258 		return;
3259 
3260 	db_indent += 2;
3261 	for (entry = map->header.next; entry != &map->header;
3262 	    entry = entry->next) {
3263 		db_iprintf("map entry %p: start=%p, end=%p\n",
3264 		    (void *)entry, (void *)entry->start, (void *)entry->end);
3265 		nlines++;
3266 		{
3267 			static char *inheritance_name[4] =
3268 			{"share", "copy", "none", "donate_copy"};
3269 
3270 			db_iprintf(" prot=%x/%x/%s",
3271 			    entry->protection,
3272 			    entry->max_protection,
3273 			    inheritance_name[(int)(unsigned char)entry->inheritance]);
3274 			if (entry->wired_count != 0)
3275 				db_printf(", wired");
3276 		}
3277 		if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
3278 			db_printf(", share=%p, offset=0x%jx\n",
3279 			    (void *)entry->object.sub_map,
3280 			    (uintmax_t)entry->offset);
3281 			nlines++;
3282 			if ((entry->prev == &map->header) ||
3283 			    (entry->prev->object.sub_map !=
3284 				entry->object.sub_map)) {
3285 				db_indent += 2;
3286 				vm_map_print((db_expr_t)(intptr_t)
3287 					     entry->object.sub_map,
3288 					     full, 0, (char *)0);
3289 				db_indent -= 2;
3290 			}
3291 		} else {
3292 			db_printf(", object=%p, offset=0x%jx",
3293 			    (void *)entry->object.vm_object,
3294 			    (uintmax_t)entry->offset);
3295 			if (entry->eflags & MAP_ENTRY_COW)
3296 				db_printf(", copy (%s)",
3297 				    (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
3298 			db_printf("\n");
3299 			nlines++;
3300 
3301 			if ((entry->prev == &map->header) ||
3302 			    (entry->prev->object.vm_object !=
3303 				entry->object.vm_object)) {
3304 				db_indent += 2;
3305 				vm_object_print((db_expr_t)(intptr_t)
3306 						entry->object.vm_object,
3307 						full, 0, (char *)0);
3308 				nlines += 4;
3309 				db_indent -= 2;
3310 			}
3311 		}
3312 	}
3313 	db_indent -= 2;
3314 	if (db_indent == 0)
3315 		nlines = 0;
3316 }
3317 
3318 
3319 DB_SHOW_COMMAND(procvm, procvm)
3320 {
3321 	struct proc *p;
3322 
3323 	if (have_addr) {
3324 		p = (struct proc *) addr;
3325 	} else {
3326 		p = curproc;
3327 	}
3328 
3329 	db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
3330 	    (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
3331 	    (void *)vmspace_pmap(p->p_vmspace));
3332 
3333 	vm_map_print((db_expr_t)(intptr_t)&p->p_vmspace->vm_map, 1, 0, NULL);
3334 }
3335 
3336 #endif /* DDB */
3337