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