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