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