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