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