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