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