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