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