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