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