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