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