xref: /freebsd/sys/vm/vm_map.c (revision a0e793cbf1951d07fc47a0d9ea389d7dacba5213)
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/kernel.h>
71 #include <sys/ktr.h>
72 #include <sys/lock.h>
73 #include <sys/mutex.h>
74 #include <sys/proc.h>
75 #include <sys/vmmeter.h>
76 #include <sys/mman.h>
77 #include <sys/vnode.h>
78 #include <sys/racct.h>
79 #include <sys/resourcevar.h>
80 #include <sys/rwlock.h>
81 #include <sys/file.h>
82 #include <sys/sysctl.h>
83 #include <sys/sysent.h>
84 #include <sys/shm.h>
85 
86 #include <vm/vm.h>
87 #include <vm/vm_param.h>
88 #include <vm/pmap.h>
89 #include <vm/vm_map.h>
90 #include <vm/vm_page.h>
91 #include <vm/vm_object.h>
92 #include <vm/vm_pager.h>
93 #include <vm/vm_kern.h>
94 #include <vm/vm_extern.h>
95 #include <vm/vnode_pager.h>
96 #include <vm/swap_pager.h>
97 #include <vm/uma.h>
98 
99 /*
100  *	Virtual memory maps provide for the mapping, protection,
101  *	and sharing of virtual memory objects.  In addition,
102  *	this module provides for an efficient virtual copy of
103  *	memory from one map to another.
104  *
105  *	Synchronization is required prior to most operations.
106  *
107  *	Maps consist of an ordered doubly-linked list of simple
108  *	entries; a self-adjusting binary search tree of these
109  *	entries is used to speed up lookups.
110  *
111  *	Since portions of maps are specified by start/end addresses,
112  *	which may not align with existing map entries, all
113  *	routines merely "clip" entries to these start/end values.
114  *	[That is, an entry is split into two, bordering at a
115  *	start or end value.]  Note that these clippings may not
116  *	always be necessary (as the two resulting entries are then
117  *	not changed); however, the clipping is done for convenience.
118  *
119  *	As mentioned above, virtual copy operations are performed
120  *	by copying VM object references from one map to
121  *	another, and then marking both regions as copy-on-write.
122  */
123 
124 static struct mtx map_sleep_mtx;
125 static uma_zone_t mapentzone;
126 static uma_zone_t kmapentzone;
127 static uma_zone_t mapzone;
128 static uma_zone_t vmspace_zone;
129 static int vmspace_zinit(void *mem, int size, int flags);
130 static int vm_map_zinit(void *mem, int ize, int flags);
131 static void _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min,
132     vm_offset_t max);
133 static void vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map);
134 static void vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry);
135 static void vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry);
136 #ifdef INVARIANTS
137 static void vm_map_zdtor(void *mem, int size, void *arg);
138 static void vmspace_zdtor(void *mem, int size, void *arg);
139 #endif
140 static int vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos,
141     vm_size_t max_ssize, vm_size_t growsize, vm_prot_t prot, vm_prot_t max,
142     int cow);
143 static void vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
144     vm_offset_t failed_addr);
145 
146 #define	ENTRY_CHARGED(e) ((e)->cred != NULL || \
147     ((e)->object.vm_object != NULL && (e)->object.vm_object->cred != NULL && \
148      !((e)->eflags & MAP_ENTRY_NEEDS_COPY)))
149 
150 /*
151  * PROC_VMSPACE_{UN,}LOCK() can be a noop as long as vmspaces are type
152  * stable.
153  */
154 #define PROC_VMSPACE_LOCK(p) do { } while (0)
155 #define PROC_VMSPACE_UNLOCK(p) do { } while (0)
156 
157 /*
158  *	VM_MAP_RANGE_CHECK:	[ internal use only ]
159  *
160  *	Asserts that the starting and ending region
161  *	addresses fall within the valid range of the map.
162  */
163 #define	VM_MAP_RANGE_CHECK(map, start, end)		\
164 		{					\
165 		if (start < vm_map_min(map))		\
166 			start = vm_map_min(map);	\
167 		if (end > vm_map_max(map))		\
168 			end = vm_map_max(map);		\
169 		if (start > end)			\
170 			start = end;			\
171 		}
172 
173 /*
174  *	vm_map_startup:
175  *
176  *	Initialize the vm_map module.  Must be called before
177  *	any other vm_map routines.
178  *
179  *	Map and entry structures are allocated from the general
180  *	purpose memory pool with some exceptions:
181  *
182  *	- The kernel map and kmem submap are allocated statically.
183  *	- Kernel map entries are allocated out of a static pool.
184  *
185  *	These restrictions are necessary since malloc() uses the
186  *	maps and requires map entries.
187  */
188 
189 void
190 vm_map_startup(void)
191 {
192 	mtx_init(&map_sleep_mtx, "vm map sleep mutex", NULL, MTX_DEF);
193 	mapzone = uma_zcreate("MAP", sizeof(struct vm_map), NULL,
194 #ifdef INVARIANTS
195 	    vm_map_zdtor,
196 #else
197 	    NULL,
198 #endif
199 	    vm_map_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
200 	uma_prealloc(mapzone, MAX_KMAP);
201 	kmapentzone = uma_zcreate("KMAP ENTRY", sizeof(struct vm_map_entry),
202 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
203 	    UMA_ZONE_MTXCLASS | UMA_ZONE_VM);
204 	mapentzone = uma_zcreate("MAP ENTRY", sizeof(struct vm_map_entry),
205 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
206 	vmspace_zone = uma_zcreate("VMSPACE", sizeof(struct vmspace), NULL,
207 #ifdef INVARIANTS
208 	    vmspace_zdtor,
209 #else
210 	    NULL,
211 #endif
212 	    vmspace_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
213 }
214 
215 static int
216 vmspace_zinit(void *mem, int size, int flags)
217 {
218 	struct vmspace *vm;
219 
220 	vm = (struct vmspace *)mem;
221 
222 	vm->vm_map.pmap = NULL;
223 	(void)vm_map_zinit(&vm->vm_map, sizeof(vm->vm_map), flags);
224 	PMAP_LOCK_INIT(vmspace_pmap(vm));
225 	return (0);
226 }
227 
228 static int
229 vm_map_zinit(void *mem, int size, int flags)
230 {
231 	vm_map_t map;
232 
233 	map = (vm_map_t)mem;
234 	memset(map, 0, sizeof(*map));
235 	mtx_init(&map->system_mtx, "vm map (system)", NULL, MTX_DEF | MTX_DUPOK);
236 	sx_init(&map->lock, "vm map (user)");
237 	return (0);
238 }
239 
240 #ifdef INVARIANTS
241 static void
242 vmspace_zdtor(void *mem, int size, void *arg)
243 {
244 	struct vmspace *vm;
245 
246 	vm = (struct vmspace *)mem;
247 
248 	vm_map_zdtor(&vm->vm_map, sizeof(vm->vm_map), arg);
249 }
250 static void
251 vm_map_zdtor(void *mem, int size, void *arg)
252 {
253 	vm_map_t map;
254 
255 	map = (vm_map_t)mem;
256 	KASSERT(map->nentries == 0,
257 	    ("map %p nentries == %d on free.",
258 	    map, map->nentries));
259 	KASSERT(map->size == 0,
260 	    ("map %p size == %lu on free.",
261 	    map, (unsigned long)map->size));
262 }
263 #endif	/* INVARIANTS */
264 
265 /*
266  * Allocate a vmspace structure, including a vm_map and pmap,
267  * and initialize those structures.  The refcnt is set to 1.
268  *
269  * If 'pinit' is NULL then the embedded pmap is initialized via pmap_pinit().
270  */
271 struct vmspace *
272 vmspace_alloc(vm_offset_t min, vm_offset_t max, pmap_pinit_t pinit)
273 {
274 	struct vmspace *vm;
275 
276 	vm = uma_zalloc(vmspace_zone, M_WAITOK);
277 
278 	KASSERT(vm->vm_map.pmap == NULL, ("vm_map.pmap must be NULL"));
279 
280 	if (pinit == NULL)
281 		pinit = &pmap_pinit;
282 
283 	if (!pinit(vmspace_pmap(vm))) {
284 		uma_zfree(vmspace_zone, vm);
285 		return (NULL);
286 	}
287 	CTR1(KTR_VM, "vmspace_alloc: %p", vm);
288 	_vm_map_init(&vm->vm_map, vmspace_pmap(vm), min, max);
289 	vm->vm_refcnt = 1;
290 	vm->vm_shm = NULL;
291 	vm->vm_swrss = 0;
292 	vm->vm_tsize = 0;
293 	vm->vm_dsize = 0;
294 	vm->vm_ssize = 0;
295 	vm->vm_taddr = 0;
296 	vm->vm_daddr = 0;
297 	vm->vm_maxsaddr = 0;
298 	return (vm);
299 }
300 
301 static void
302 vmspace_container_reset(struct proc *p)
303 {
304 
305 #ifdef RACCT
306 	PROC_LOCK(p);
307 	racct_set(p, RACCT_DATA, 0);
308 	racct_set(p, RACCT_STACK, 0);
309 	racct_set(p, RACCT_RSS, 0);
310 	racct_set(p, RACCT_MEMLOCK, 0);
311 	racct_set(p, RACCT_VMEM, 0);
312 	PROC_UNLOCK(p);
313 #endif
314 }
315 
316 static inline void
317 vmspace_dofree(struct vmspace *vm)
318 {
319 
320 	CTR1(KTR_VM, "vmspace_free: %p", vm);
321 
322 	/*
323 	 * Make sure any SysV shm is freed, it might not have been in
324 	 * exit1().
325 	 */
326 	shmexit(vm);
327 
328 	/*
329 	 * Lock the map, to wait out all other references to it.
330 	 * Delete all of the mappings and pages they hold, then call
331 	 * the pmap module to reclaim anything left.
332 	 */
333 	(void)vm_map_remove(&vm->vm_map, vm->vm_map.min_offset,
334 	    vm->vm_map.max_offset);
335 
336 	pmap_release(vmspace_pmap(vm));
337 	vm->vm_map.pmap = NULL;
338 	uma_zfree(vmspace_zone, vm);
339 }
340 
341 void
342 vmspace_free(struct vmspace *vm)
343 {
344 
345 	if (vm->vm_refcnt == 0)
346 		panic("vmspace_free: attempt to free already freed vmspace");
347 
348 	if (atomic_fetchadd_int(&vm->vm_refcnt, -1) == 1)
349 		vmspace_dofree(vm);
350 }
351 
352 void
353 vmspace_exitfree(struct proc *p)
354 {
355 	struct vmspace *vm;
356 
357 	PROC_VMSPACE_LOCK(p);
358 	vm = p->p_vmspace;
359 	p->p_vmspace = NULL;
360 	PROC_VMSPACE_UNLOCK(p);
361 	KASSERT(vm == &vmspace0, ("vmspace_exitfree: wrong vmspace"));
362 	vmspace_free(vm);
363 }
364 
365 void
366 vmspace_exit(struct thread *td)
367 {
368 	int refcnt;
369 	struct vmspace *vm;
370 	struct proc *p;
371 
372 	/*
373 	 * Release user portion of address space.
374 	 * This releases references to vnodes,
375 	 * which could cause I/O if the file has been unlinked.
376 	 * Need to do this early enough that we can still sleep.
377 	 *
378 	 * The last exiting process to reach this point releases as
379 	 * much of the environment as it can. vmspace_dofree() is the
380 	 * slower fallback in case another process had a temporary
381 	 * reference to the vmspace.
382 	 */
383 
384 	p = td->td_proc;
385 	vm = p->p_vmspace;
386 	atomic_add_int(&vmspace0.vm_refcnt, 1);
387 	do {
388 		refcnt = vm->vm_refcnt;
389 		if (refcnt > 1 && p->p_vmspace != &vmspace0) {
390 			/* Switch now since other proc might free vmspace */
391 			PROC_VMSPACE_LOCK(p);
392 			p->p_vmspace = &vmspace0;
393 			PROC_VMSPACE_UNLOCK(p);
394 			pmap_activate(td);
395 		}
396 	} while (!atomic_cmpset_int(&vm->vm_refcnt, refcnt, refcnt - 1));
397 	if (refcnt == 1) {
398 		if (p->p_vmspace != vm) {
399 			/* vmspace not yet freed, switch back */
400 			PROC_VMSPACE_LOCK(p);
401 			p->p_vmspace = vm;
402 			PROC_VMSPACE_UNLOCK(p);
403 			pmap_activate(td);
404 		}
405 		pmap_remove_pages(vmspace_pmap(vm));
406 		/* Switch now since this proc will free vmspace */
407 		PROC_VMSPACE_LOCK(p);
408 		p->p_vmspace = &vmspace0;
409 		PROC_VMSPACE_UNLOCK(p);
410 		pmap_activate(td);
411 		vmspace_dofree(vm);
412 	}
413 	vmspace_container_reset(p);
414 }
415 
416 /* Acquire reference to vmspace owned by another process. */
417 
418 struct vmspace *
419 vmspace_acquire_ref(struct proc *p)
420 {
421 	struct vmspace *vm;
422 	int refcnt;
423 
424 	PROC_VMSPACE_LOCK(p);
425 	vm = p->p_vmspace;
426 	if (vm == NULL) {
427 		PROC_VMSPACE_UNLOCK(p);
428 		return (NULL);
429 	}
430 	do {
431 		refcnt = vm->vm_refcnt;
432 		if (refcnt <= 0) { 	/* Avoid 0->1 transition */
433 			PROC_VMSPACE_UNLOCK(p);
434 			return (NULL);
435 		}
436 	} while (!atomic_cmpset_int(&vm->vm_refcnt, refcnt, refcnt + 1));
437 	if (vm != p->p_vmspace) {
438 		PROC_VMSPACE_UNLOCK(p);
439 		vmspace_free(vm);
440 		return (NULL);
441 	}
442 	PROC_VMSPACE_UNLOCK(p);
443 	return (vm);
444 }
445 
446 void
447 _vm_map_lock(vm_map_t map, const char *file, int line)
448 {
449 
450 	if (map->system_map)
451 		mtx_lock_flags_(&map->system_mtx, 0, file, line);
452 	else
453 		sx_xlock_(&map->lock, file, line);
454 	map->timestamp++;
455 }
456 
457 static void
458 vm_map_process_deferred(void)
459 {
460 	struct thread *td;
461 	vm_map_entry_t entry, next;
462 	vm_object_t object;
463 
464 	td = curthread;
465 	entry = td->td_map_def_user;
466 	td->td_map_def_user = NULL;
467 	while (entry != NULL) {
468 		next = entry->next;
469 		if ((entry->eflags & MAP_ENTRY_VN_WRITECNT) != 0) {
470 			/*
471 			 * Decrement the object's writemappings and
472 			 * possibly the vnode's v_writecount.
473 			 */
474 			KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
475 			    ("Submap with writecount"));
476 			object = entry->object.vm_object;
477 			KASSERT(object != NULL, ("No object for writecount"));
478 			vnode_pager_release_writecount(object, entry->start,
479 			    entry->end);
480 		}
481 		vm_map_entry_deallocate(entry, FALSE);
482 		entry = next;
483 	}
484 }
485 
486 void
487 _vm_map_unlock(vm_map_t map, const char *file, int line)
488 {
489 
490 	if (map->system_map)
491 		mtx_unlock_flags_(&map->system_mtx, 0, file, line);
492 	else {
493 		sx_xunlock_(&map->lock, file, line);
494 		vm_map_process_deferred();
495 	}
496 }
497 
498 void
499 _vm_map_lock_read(vm_map_t map, const char *file, int line)
500 {
501 
502 	if (map->system_map)
503 		mtx_lock_flags_(&map->system_mtx, 0, file, line);
504 	else
505 		sx_slock_(&map->lock, file, line);
506 }
507 
508 void
509 _vm_map_unlock_read(vm_map_t map, const char *file, int line)
510 {
511 
512 	if (map->system_map)
513 		mtx_unlock_flags_(&map->system_mtx, 0, file, line);
514 	else {
515 		sx_sunlock_(&map->lock, file, line);
516 		vm_map_process_deferred();
517 	}
518 }
519 
520 int
521 _vm_map_trylock(vm_map_t map, const char *file, int line)
522 {
523 	int error;
524 
525 	error = map->system_map ?
526 	    !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
527 	    !sx_try_xlock_(&map->lock, file, line);
528 	if (error == 0)
529 		map->timestamp++;
530 	return (error == 0);
531 }
532 
533 int
534 _vm_map_trylock_read(vm_map_t map, const char *file, int line)
535 {
536 	int error;
537 
538 	error = map->system_map ?
539 	    !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
540 	    !sx_try_slock_(&map->lock, file, line);
541 	return (error == 0);
542 }
543 
544 /*
545  *	_vm_map_lock_upgrade:	[ internal use only ]
546  *
547  *	Tries to upgrade a read (shared) lock on the specified map to a write
548  *	(exclusive) lock.  Returns the value "0" if the upgrade succeeds and a
549  *	non-zero value if the upgrade fails.  If the upgrade fails, the map is
550  *	returned without a read or write lock held.
551  *
552  *	Requires that the map be read locked.
553  */
554 int
555 _vm_map_lock_upgrade(vm_map_t map, const char *file, int line)
556 {
557 	unsigned int last_timestamp;
558 
559 	if (map->system_map) {
560 		mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
561 	} else {
562 		if (!sx_try_upgrade_(&map->lock, file, line)) {
563 			last_timestamp = map->timestamp;
564 			sx_sunlock_(&map->lock, file, line);
565 			vm_map_process_deferred();
566 			/*
567 			 * If the map's timestamp does not change while the
568 			 * map is unlocked, then the upgrade succeeds.
569 			 */
570 			sx_xlock_(&map->lock, file, line);
571 			if (last_timestamp != map->timestamp) {
572 				sx_xunlock_(&map->lock, file, line);
573 				return (1);
574 			}
575 		}
576 	}
577 	map->timestamp++;
578 	return (0);
579 }
580 
581 void
582 _vm_map_lock_downgrade(vm_map_t map, const char *file, int line)
583 {
584 
585 	if (map->system_map) {
586 		mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
587 	} else
588 		sx_downgrade_(&map->lock, file, line);
589 }
590 
591 /*
592  *	vm_map_locked:
593  *
594  *	Returns a non-zero value if the caller holds a write (exclusive) lock
595  *	on the specified map and the value "0" otherwise.
596  */
597 int
598 vm_map_locked(vm_map_t map)
599 {
600 
601 	if (map->system_map)
602 		return (mtx_owned(&map->system_mtx));
603 	else
604 		return (sx_xlocked(&map->lock));
605 }
606 
607 #ifdef INVARIANTS
608 static void
609 _vm_map_assert_locked(vm_map_t map, const char *file, int line)
610 {
611 
612 	if (map->system_map)
613 		mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
614 	else
615 		sx_assert_(&map->lock, SA_XLOCKED, file, line);
616 }
617 
618 #define	VM_MAP_ASSERT_LOCKED(map) \
619     _vm_map_assert_locked(map, LOCK_FILE, LOCK_LINE)
620 #else
621 #define	VM_MAP_ASSERT_LOCKED(map)
622 #endif
623 
624 /*
625  *	_vm_map_unlock_and_wait:
626  *
627  *	Atomically releases the lock on the specified map and puts the calling
628  *	thread to sleep.  The calling thread will remain asleep until either
629  *	vm_map_wakeup() is performed on the map or the specified timeout is
630  *	exceeded.
631  *
632  *	WARNING!  This function does not perform deferred deallocations of
633  *	objects and map	entries.  Therefore, the calling thread is expected to
634  *	reacquire the map lock after reawakening and later perform an ordinary
635  *	unlock operation, such as vm_map_unlock(), before completing its
636  *	operation on the map.
637  */
638 int
639 _vm_map_unlock_and_wait(vm_map_t map, int timo, const char *file, int line)
640 {
641 
642 	mtx_lock(&map_sleep_mtx);
643 	if (map->system_map)
644 		mtx_unlock_flags_(&map->system_mtx, 0, file, line);
645 	else
646 		sx_xunlock_(&map->lock, file, line);
647 	return (msleep(&map->root, &map_sleep_mtx, PDROP | PVM, "vmmaps",
648 	    timo));
649 }
650 
651 /*
652  *	vm_map_wakeup:
653  *
654  *	Awaken any threads that have slept on the map using
655  *	vm_map_unlock_and_wait().
656  */
657 void
658 vm_map_wakeup(vm_map_t map)
659 {
660 
661 	/*
662 	 * Acquire and release map_sleep_mtx to prevent a wakeup()
663 	 * from being performed (and lost) between the map unlock
664 	 * and the msleep() in _vm_map_unlock_and_wait().
665 	 */
666 	mtx_lock(&map_sleep_mtx);
667 	mtx_unlock(&map_sleep_mtx);
668 	wakeup(&map->root);
669 }
670 
671 void
672 vm_map_busy(vm_map_t map)
673 {
674 
675 	VM_MAP_ASSERT_LOCKED(map);
676 	map->busy++;
677 }
678 
679 void
680 vm_map_unbusy(vm_map_t map)
681 {
682 
683 	VM_MAP_ASSERT_LOCKED(map);
684 	KASSERT(map->busy, ("vm_map_unbusy: not busy"));
685 	if (--map->busy == 0 && (map->flags & MAP_BUSY_WAKEUP)) {
686 		vm_map_modflags(map, 0, MAP_BUSY_WAKEUP);
687 		wakeup(&map->busy);
688 	}
689 }
690 
691 void
692 vm_map_wait_busy(vm_map_t map)
693 {
694 
695 	VM_MAP_ASSERT_LOCKED(map);
696 	while (map->busy) {
697 		vm_map_modflags(map, MAP_BUSY_WAKEUP, 0);
698 		if (map->system_map)
699 			msleep(&map->busy, &map->system_mtx, 0, "mbusy", 0);
700 		else
701 			sx_sleep(&map->busy, &map->lock, 0, "mbusy", 0);
702 	}
703 	map->timestamp++;
704 }
705 
706 long
707 vmspace_resident_count(struct vmspace *vmspace)
708 {
709 	return pmap_resident_count(vmspace_pmap(vmspace));
710 }
711 
712 /*
713  *	vm_map_create:
714  *
715  *	Creates and returns a new empty VM map with
716  *	the given physical map structure, and having
717  *	the given lower and upper address bounds.
718  */
719 vm_map_t
720 vm_map_create(pmap_t pmap, vm_offset_t min, vm_offset_t max)
721 {
722 	vm_map_t result;
723 
724 	result = uma_zalloc(mapzone, M_WAITOK);
725 	CTR1(KTR_VM, "vm_map_create: %p", result);
726 	_vm_map_init(result, pmap, min, max);
727 	return (result);
728 }
729 
730 /*
731  * Initialize an existing vm_map structure
732  * such as that in the vmspace structure.
733  */
734 static void
735 _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
736 {
737 
738 	map->header.next = map->header.prev = &map->header;
739 	map->needs_wakeup = FALSE;
740 	map->system_map = 0;
741 	map->pmap = pmap;
742 	map->min_offset = min;
743 	map->max_offset = max;
744 	map->flags = 0;
745 	map->root = NULL;
746 	map->timestamp = 0;
747 	map->busy = 0;
748 }
749 
750 void
751 vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
752 {
753 
754 	_vm_map_init(map, pmap, min, max);
755 	mtx_init(&map->system_mtx, "system map", NULL, MTX_DEF | MTX_DUPOK);
756 	sx_init(&map->lock, "user map");
757 }
758 
759 /*
760  *	vm_map_entry_dispose:	[ internal use only ]
761  *
762  *	Inverse of vm_map_entry_create.
763  */
764 static void
765 vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry)
766 {
767 	uma_zfree(map->system_map ? kmapentzone : mapentzone, entry);
768 }
769 
770 /*
771  *	vm_map_entry_create:	[ internal use only ]
772  *
773  *	Allocates a VM map entry for insertion.
774  *	No entry fields are filled in.
775  */
776 static vm_map_entry_t
777 vm_map_entry_create(vm_map_t map)
778 {
779 	vm_map_entry_t new_entry;
780 
781 	if (map->system_map)
782 		new_entry = uma_zalloc(kmapentzone, M_NOWAIT);
783 	else
784 		new_entry = uma_zalloc(mapentzone, M_WAITOK);
785 	if (new_entry == NULL)
786 		panic("vm_map_entry_create: kernel resources exhausted");
787 	return (new_entry);
788 }
789 
790 /*
791  *	vm_map_entry_set_behavior:
792  *
793  *	Set the expected access behavior, either normal, random, or
794  *	sequential.
795  */
796 static inline void
797 vm_map_entry_set_behavior(vm_map_entry_t entry, u_char behavior)
798 {
799 	entry->eflags = (entry->eflags & ~MAP_ENTRY_BEHAV_MASK) |
800 	    (behavior & MAP_ENTRY_BEHAV_MASK);
801 }
802 
803 /*
804  *	vm_map_entry_set_max_free:
805  *
806  *	Set the max_free field in a vm_map_entry.
807  */
808 static inline void
809 vm_map_entry_set_max_free(vm_map_entry_t entry)
810 {
811 
812 	entry->max_free = entry->adj_free;
813 	if (entry->left != NULL && entry->left->max_free > entry->max_free)
814 		entry->max_free = entry->left->max_free;
815 	if (entry->right != NULL && entry->right->max_free > entry->max_free)
816 		entry->max_free = entry->right->max_free;
817 }
818 
819 /*
820  *	vm_map_entry_splay:
821  *
822  *	The Sleator and Tarjan top-down splay algorithm with the
823  *	following variation.  Max_free must be computed bottom-up, so
824  *	on the downward pass, maintain the left and right spines in
825  *	reverse order.  Then, make a second pass up each side to fix
826  *	the pointers and compute max_free.  The time bound is O(log n)
827  *	amortized.
828  *
829  *	The new root is the vm_map_entry containing "addr", or else an
830  *	adjacent entry (lower or higher) if addr is not in the tree.
831  *
832  *	The map must be locked, and leaves it so.
833  *
834  *	Returns: the new root.
835  */
836 static vm_map_entry_t
837 vm_map_entry_splay(vm_offset_t addr, vm_map_entry_t root)
838 {
839 	vm_map_entry_t llist, rlist;
840 	vm_map_entry_t ltree, rtree;
841 	vm_map_entry_t y;
842 
843 	/* Special case of empty tree. */
844 	if (root == NULL)
845 		return (root);
846 
847 	/*
848 	 * Pass One: Splay down the tree until we find addr or a NULL
849 	 * pointer where addr would go.  llist and rlist are the two
850 	 * sides in reverse order (bottom-up), with llist linked by
851 	 * the right pointer and rlist linked by the left pointer in
852 	 * the vm_map_entry.  Wait until Pass Two to set max_free on
853 	 * the two spines.
854 	 */
855 	llist = NULL;
856 	rlist = NULL;
857 	for (;;) {
858 		/* root is never NULL in here. */
859 		if (addr < root->start) {
860 			y = root->left;
861 			if (y == NULL)
862 				break;
863 			if (addr < y->start && y->left != NULL) {
864 				/* Rotate right and put y on rlist. */
865 				root->left = y->right;
866 				y->right = root;
867 				vm_map_entry_set_max_free(root);
868 				root = y->left;
869 				y->left = rlist;
870 				rlist = y;
871 			} else {
872 				/* Put root on rlist. */
873 				root->left = rlist;
874 				rlist = root;
875 				root = y;
876 			}
877 		} else if (addr >= root->end) {
878 			y = root->right;
879 			if (y == NULL)
880 				break;
881 			if (addr >= y->end && y->right != NULL) {
882 				/* Rotate left and put y on llist. */
883 				root->right = y->left;
884 				y->left = root;
885 				vm_map_entry_set_max_free(root);
886 				root = y->right;
887 				y->right = llist;
888 				llist = y;
889 			} else {
890 				/* Put root on llist. */
891 				root->right = llist;
892 				llist = root;
893 				root = y;
894 			}
895 		} else
896 			break;
897 	}
898 
899 	/*
900 	 * Pass Two: Walk back up the two spines, flip the pointers
901 	 * and set max_free.  The subtrees of the root go at the
902 	 * bottom of llist and rlist.
903 	 */
904 	ltree = root->left;
905 	while (llist != NULL) {
906 		y = llist->right;
907 		llist->right = ltree;
908 		vm_map_entry_set_max_free(llist);
909 		ltree = llist;
910 		llist = y;
911 	}
912 	rtree = root->right;
913 	while (rlist != NULL) {
914 		y = rlist->left;
915 		rlist->left = rtree;
916 		vm_map_entry_set_max_free(rlist);
917 		rtree = rlist;
918 		rlist = y;
919 	}
920 
921 	/*
922 	 * Final assembly: add ltree and rtree as subtrees of root.
923 	 */
924 	root->left = ltree;
925 	root->right = rtree;
926 	vm_map_entry_set_max_free(root);
927 
928 	return (root);
929 }
930 
931 /*
932  *	vm_map_entry_{un,}link:
933  *
934  *	Insert/remove entries from maps.
935  */
936 static void
937 vm_map_entry_link(vm_map_t map,
938 		  vm_map_entry_t after_where,
939 		  vm_map_entry_t entry)
940 {
941 
942 	CTR4(KTR_VM,
943 	    "vm_map_entry_link: map %p, nentries %d, entry %p, after %p", map,
944 	    map->nentries, entry, after_where);
945 	VM_MAP_ASSERT_LOCKED(map);
946 	KASSERT(after_where == &map->header ||
947 	    after_where->end <= entry->start,
948 	    ("vm_map_entry_link: prev end %jx new start %jx overlap",
949 	    (uintmax_t)after_where->end, (uintmax_t)entry->start));
950 	KASSERT(after_where->next == &map->header ||
951 	    entry->end <= after_where->next->start,
952 	    ("vm_map_entry_link: new end %jx next start %jx overlap",
953 	    (uintmax_t)entry->end, (uintmax_t)after_where->next->start));
954 
955 	map->nentries++;
956 	entry->prev = after_where;
957 	entry->next = after_where->next;
958 	entry->next->prev = entry;
959 	after_where->next = entry;
960 
961 	if (after_where != &map->header) {
962 		if (after_where != map->root)
963 			vm_map_entry_splay(after_where->start, map->root);
964 		entry->right = after_where->right;
965 		entry->left = after_where;
966 		after_where->right = NULL;
967 		after_where->adj_free = entry->start - after_where->end;
968 		vm_map_entry_set_max_free(after_where);
969 	} else {
970 		entry->right = map->root;
971 		entry->left = NULL;
972 	}
973 	entry->adj_free = (entry->next == &map->header ? map->max_offset :
974 	    entry->next->start) - entry->end;
975 	vm_map_entry_set_max_free(entry);
976 	map->root = entry;
977 }
978 
979 static void
980 vm_map_entry_unlink(vm_map_t map,
981 		    vm_map_entry_t entry)
982 {
983 	vm_map_entry_t next, prev, root;
984 
985 	VM_MAP_ASSERT_LOCKED(map);
986 	if (entry != map->root)
987 		vm_map_entry_splay(entry->start, map->root);
988 	if (entry->left == NULL)
989 		root = entry->right;
990 	else {
991 		root = vm_map_entry_splay(entry->start, entry->left);
992 		root->right = entry->right;
993 		root->adj_free = (entry->next == &map->header ? map->max_offset :
994 		    entry->next->start) - root->end;
995 		vm_map_entry_set_max_free(root);
996 	}
997 	map->root = root;
998 
999 	prev = entry->prev;
1000 	next = entry->next;
1001 	next->prev = prev;
1002 	prev->next = next;
1003 	map->nentries--;
1004 	CTR3(KTR_VM, "vm_map_entry_unlink: map %p, nentries %d, entry %p", map,
1005 	    map->nentries, entry);
1006 }
1007 
1008 /*
1009  *	vm_map_entry_resize_free:
1010  *
1011  *	Recompute the amount of free space following a vm_map_entry
1012  *	and propagate that value up the tree.  Call this function after
1013  *	resizing a map entry in-place, that is, without a call to
1014  *	vm_map_entry_link() or _unlink().
1015  *
1016  *	The map must be locked, and leaves it so.
1017  */
1018 static void
1019 vm_map_entry_resize_free(vm_map_t map, vm_map_entry_t entry)
1020 {
1021 
1022 	/*
1023 	 * Using splay trees without parent pointers, propagating
1024 	 * max_free up the tree is done by moving the entry to the
1025 	 * root and making the change there.
1026 	 */
1027 	if (entry != map->root)
1028 		map->root = vm_map_entry_splay(entry->start, map->root);
1029 
1030 	entry->adj_free = (entry->next == &map->header ? map->max_offset :
1031 	    entry->next->start) - entry->end;
1032 	vm_map_entry_set_max_free(entry);
1033 }
1034 
1035 /*
1036  *	vm_map_lookup_entry:	[ internal use only ]
1037  *
1038  *	Finds the map entry containing (or
1039  *	immediately preceding) the specified address
1040  *	in the given map; the entry is returned
1041  *	in the "entry" parameter.  The boolean
1042  *	result indicates whether the address is
1043  *	actually contained in the map.
1044  */
1045 boolean_t
1046 vm_map_lookup_entry(
1047 	vm_map_t map,
1048 	vm_offset_t address,
1049 	vm_map_entry_t *entry)	/* OUT */
1050 {
1051 	vm_map_entry_t cur;
1052 	boolean_t locked;
1053 
1054 	/*
1055 	 * If the map is empty, then the map entry immediately preceding
1056 	 * "address" is the map's header.
1057 	 */
1058 	cur = map->root;
1059 	if (cur == NULL)
1060 		*entry = &map->header;
1061 	else if (address >= cur->start && cur->end > address) {
1062 		*entry = cur;
1063 		return (TRUE);
1064 	} else if ((locked = vm_map_locked(map)) ||
1065 	    sx_try_upgrade(&map->lock)) {
1066 		/*
1067 		 * Splay requires a write lock on the map.  However, it only
1068 		 * restructures the binary search tree; it does not otherwise
1069 		 * change the map.  Thus, the map's timestamp need not change
1070 		 * on a temporary upgrade.
1071 		 */
1072 		map->root = cur = vm_map_entry_splay(address, cur);
1073 		if (!locked)
1074 			sx_downgrade(&map->lock);
1075 
1076 		/*
1077 		 * If "address" is contained within a map entry, the new root
1078 		 * is that map entry.  Otherwise, the new root is a map entry
1079 		 * immediately before or after "address".
1080 		 */
1081 		if (address >= cur->start) {
1082 			*entry = cur;
1083 			if (cur->end > address)
1084 				return (TRUE);
1085 		} else
1086 			*entry = cur->prev;
1087 	} else
1088 		/*
1089 		 * Since the map is only locked for read access, perform a
1090 		 * standard binary search tree lookup for "address".
1091 		 */
1092 		for (;;) {
1093 			if (address < cur->start) {
1094 				if (cur->left == NULL) {
1095 					*entry = cur->prev;
1096 					break;
1097 				}
1098 				cur = cur->left;
1099 			} else if (cur->end > address) {
1100 				*entry = cur;
1101 				return (TRUE);
1102 			} else {
1103 				if (cur->right == NULL) {
1104 					*entry = cur;
1105 					break;
1106 				}
1107 				cur = cur->right;
1108 			}
1109 		}
1110 	return (FALSE);
1111 }
1112 
1113 /*
1114  *	vm_map_insert:
1115  *
1116  *	Inserts the given whole VM object into the target
1117  *	map at the specified address range.  The object's
1118  *	size should match that of the address range.
1119  *
1120  *	Requires that the map be locked, and leaves it so.
1121  *
1122  *	If object is non-NULL, ref count must be bumped by caller
1123  *	prior to making call to account for the new entry.
1124  */
1125 int
1126 vm_map_insert(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1127     vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max, int cow)
1128 {
1129 	vm_map_entry_t new_entry, prev_entry, temp_entry;
1130 	vm_eflags_t protoeflags;
1131 	struct ucred *cred;
1132 	vm_inherit_t inheritance;
1133 
1134 	VM_MAP_ASSERT_LOCKED(map);
1135 	KASSERT((object != kmem_object && object != kernel_object) ||
1136 	    (cow & MAP_COPY_ON_WRITE) == 0,
1137 	    ("vm_map_insert: kmem or kernel object and COW"));
1138 	KASSERT(object == NULL || (cow & MAP_NOFAULT) == 0,
1139 	    ("vm_map_insert: paradoxical MAP_NOFAULT request"));
1140 
1141 	/*
1142 	 * Check that the start and end points are not bogus.
1143 	 */
1144 	if ((start < map->min_offset) || (end > map->max_offset) ||
1145 	    (start >= end))
1146 		return (KERN_INVALID_ADDRESS);
1147 
1148 	/*
1149 	 * Find the entry prior to the proposed starting address; if it's part
1150 	 * of an existing entry, this range is bogus.
1151 	 */
1152 	if (vm_map_lookup_entry(map, start, &temp_entry))
1153 		return (KERN_NO_SPACE);
1154 
1155 	prev_entry = temp_entry;
1156 
1157 	/*
1158 	 * Assert that the next entry doesn't overlap the end point.
1159 	 */
1160 	if ((prev_entry->next != &map->header) &&
1161 	    (prev_entry->next->start < end))
1162 		return (KERN_NO_SPACE);
1163 
1164 	protoeflags = 0;
1165 	if (cow & MAP_COPY_ON_WRITE)
1166 		protoeflags |= MAP_ENTRY_COW | MAP_ENTRY_NEEDS_COPY;
1167 	if (cow & MAP_NOFAULT)
1168 		protoeflags |= MAP_ENTRY_NOFAULT;
1169 	if (cow & MAP_DISABLE_SYNCER)
1170 		protoeflags |= MAP_ENTRY_NOSYNC;
1171 	if (cow & MAP_DISABLE_COREDUMP)
1172 		protoeflags |= MAP_ENTRY_NOCOREDUMP;
1173 	if (cow & MAP_STACK_GROWS_DOWN)
1174 		protoeflags |= MAP_ENTRY_GROWS_DOWN;
1175 	if (cow & MAP_STACK_GROWS_UP)
1176 		protoeflags |= MAP_ENTRY_GROWS_UP;
1177 	if (cow & MAP_VN_WRITECOUNT)
1178 		protoeflags |= MAP_ENTRY_VN_WRITECNT;
1179 	if (cow & MAP_INHERIT_SHARE)
1180 		inheritance = VM_INHERIT_SHARE;
1181 	else
1182 		inheritance = VM_INHERIT_DEFAULT;
1183 
1184 	cred = NULL;
1185 	if (cow & (MAP_ACC_NO_CHARGE | MAP_NOFAULT))
1186 		goto charged;
1187 	if ((cow & MAP_ACC_CHARGED) || ((prot & VM_PROT_WRITE) &&
1188 	    ((protoeflags & MAP_ENTRY_NEEDS_COPY) || object == NULL))) {
1189 		if (!(cow & MAP_ACC_CHARGED) && !swap_reserve(end - start))
1190 			return (KERN_RESOURCE_SHORTAGE);
1191 		KASSERT(object == NULL || (protoeflags & MAP_ENTRY_NEEDS_COPY) ||
1192 		    object->cred == NULL,
1193 		    ("OVERCOMMIT: vm_map_insert o %p", object));
1194 		cred = curthread->td_ucred;
1195 	}
1196 
1197 charged:
1198 	/* Expand the kernel pmap, if necessary. */
1199 	if (map == kernel_map && end > kernel_vm_end)
1200 		pmap_growkernel(end);
1201 	if (object != NULL) {
1202 		/*
1203 		 * OBJ_ONEMAPPING must be cleared unless this mapping
1204 		 * is trivially proven to be the only mapping for any
1205 		 * of the object's pages.  (Object granularity
1206 		 * reference counting is insufficient to recognize
1207 		 * aliases with precision.)
1208 		 */
1209 		VM_OBJECT_WLOCK(object);
1210 		if (object->ref_count > 1 || object->shadow_count != 0)
1211 			vm_object_clear_flag(object, OBJ_ONEMAPPING);
1212 		VM_OBJECT_WUNLOCK(object);
1213 	}
1214 	else if ((prev_entry != &map->header) &&
1215 		 (prev_entry->eflags == protoeflags) &&
1216 		 (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 &&
1217 		 (prev_entry->end == start) &&
1218 		 (prev_entry->wired_count == 0) &&
1219 		 (prev_entry->cred == cred ||
1220 		  (prev_entry->object.vm_object != NULL &&
1221 		   (prev_entry->object.vm_object->cred == cred))) &&
1222 		   vm_object_coalesce(prev_entry->object.vm_object,
1223 		       prev_entry->offset,
1224 		       (vm_size_t)(prev_entry->end - prev_entry->start),
1225 		       (vm_size_t)(end - prev_entry->end), cred != NULL &&
1226 		       (protoeflags & MAP_ENTRY_NEEDS_COPY) == 0)) {
1227 		/*
1228 		 * We were able to extend the object.  Determine if we
1229 		 * can extend the previous map entry to include the
1230 		 * new range as well.
1231 		 */
1232 		if ((prev_entry->inheritance == inheritance) &&
1233 		    (prev_entry->protection == prot) &&
1234 		    (prev_entry->max_protection == max)) {
1235 			map->size += (end - prev_entry->end);
1236 			prev_entry->end = end;
1237 			vm_map_entry_resize_free(map, prev_entry);
1238 			vm_map_simplify_entry(map, prev_entry);
1239 			return (KERN_SUCCESS);
1240 		}
1241 
1242 		/*
1243 		 * If we can extend the object but cannot extend the
1244 		 * map entry, we have to create a new map entry.  We
1245 		 * must bump the ref count on the extended object to
1246 		 * account for it.  object may be NULL.
1247 		 */
1248 		object = prev_entry->object.vm_object;
1249 		offset = prev_entry->offset +
1250 			(prev_entry->end - prev_entry->start);
1251 		vm_object_reference(object);
1252 		if (cred != NULL && object != NULL && object->cred != NULL &&
1253 		    !(prev_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
1254 			/* Object already accounts for this uid. */
1255 			cred = NULL;
1256 		}
1257 	}
1258 	if (cred != NULL)
1259 		crhold(cred);
1260 
1261 	/*
1262 	 * Create a new entry
1263 	 */
1264 	new_entry = vm_map_entry_create(map);
1265 	new_entry->start = start;
1266 	new_entry->end = end;
1267 	new_entry->cred = NULL;
1268 
1269 	new_entry->eflags = protoeflags;
1270 	new_entry->object.vm_object = object;
1271 	new_entry->offset = offset;
1272 	new_entry->avail_ssize = 0;
1273 
1274 	new_entry->inheritance = inheritance;
1275 	new_entry->protection = prot;
1276 	new_entry->max_protection = max;
1277 	new_entry->wired_count = 0;
1278 	new_entry->wiring_thread = NULL;
1279 	new_entry->read_ahead = VM_FAULT_READ_AHEAD_INIT;
1280 	new_entry->next_read = OFF_TO_IDX(offset);
1281 
1282 	KASSERT(cred == NULL || !ENTRY_CHARGED(new_entry),
1283 	    ("OVERCOMMIT: vm_map_insert leaks vm_map %p", new_entry));
1284 	new_entry->cred = cred;
1285 
1286 	/*
1287 	 * Insert the new entry into the list
1288 	 */
1289 	vm_map_entry_link(map, prev_entry, new_entry);
1290 	map->size += new_entry->end - new_entry->start;
1291 
1292 	/*
1293 	 * Try to coalesce the new entry with both the previous and next
1294 	 * entries in the list.  Previously, we only attempted to coalesce
1295 	 * with the previous entry when object is NULL.  Here, we handle the
1296 	 * other cases, which are less common.
1297 	 */
1298 	vm_map_simplify_entry(map, new_entry);
1299 
1300 	if (cow & (MAP_PREFAULT|MAP_PREFAULT_PARTIAL)) {
1301 		vm_map_pmap_enter(map, start, prot,
1302 				    object, OFF_TO_IDX(offset), end - start,
1303 				    cow & MAP_PREFAULT_PARTIAL);
1304 	}
1305 
1306 	return (KERN_SUCCESS);
1307 }
1308 
1309 /*
1310  *	vm_map_findspace:
1311  *
1312  *	Find the first fit (lowest VM address) for "length" free bytes
1313  *	beginning at address >= start in the given map.
1314  *
1315  *	In a vm_map_entry, "adj_free" is the amount of free space
1316  *	adjacent (higher address) to this entry, and "max_free" is the
1317  *	maximum amount of contiguous free space in its subtree.  This
1318  *	allows finding a free region in one path down the tree, so
1319  *	O(log n) amortized with splay trees.
1320  *
1321  *	The map must be locked, and leaves it so.
1322  *
1323  *	Returns: 0 on success, and starting address in *addr,
1324  *		 1 if insufficient space.
1325  */
1326 int
1327 vm_map_findspace(vm_map_t map, vm_offset_t start, vm_size_t length,
1328     vm_offset_t *addr)	/* OUT */
1329 {
1330 	vm_map_entry_t entry;
1331 	vm_offset_t st;
1332 
1333 	/*
1334 	 * Request must fit within min/max VM address and must avoid
1335 	 * address wrap.
1336 	 */
1337 	if (start < map->min_offset)
1338 		start = map->min_offset;
1339 	if (start + length > map->max_offset || start + length < start)
1340 		return (1);
1341 
1342 	/* Empty tree means wide open address space. */
1343 	if (map->root == NULL) {
1344 		*addr = start;
1345 		return (0);
1346 	}
1347 
1348 	/*
1349 	 * After splay, if start comes before root node, then there
1350 	 * must be a gap from start to the root.
1351 	 */
1352 	map->root = vm_map_entry_splay(start, map->root);
1353 	if (start + length <= map->root->start) {
1354 		*addr = start;
1355 		return (0);
1356 	}
1357 
1358 	/*
1359 	 * Root is the last node that might begin its gap before
1360 	 * start, and this is the last comparison where address
1361 	 * wrap might be a problem.
1362 	 */
1363 	st = (start > map->root->end) ? start : map->root->end;
1364 	if (length <= map->root->end + map->root->adj_free - st) {
1365 		*addr = st;
1366 		return (0);
1367 	}
1368 
1369 	/* With max_free, can immediately tell if no solution. */
1370 	entry = map->root->right;
1371 	if (entry == NULL || length > entry->max_free)
1372 		return (1);
1373 
1374 	/*
1375 	 * Search the right subtree in the order: left subtree, root,
1376 	 * right subtree (first fit).  The previous splay implies that
1377 	 * all regions in the right subtree have addresses > start.
1378 	 */
1379 	while (entry != NULL) {
1380 		if (entry->left != NULL && entry->left->max_free >= length)
1381 			entry = entry->left;
1382 		else if (entry->adj_free >= length) {
1383 			*addr = entry->end;
1384 			return (0);
1385 		} else
1386 			entry = entry->right;
1387 	}
1388 
1389 	/* Can't get here, so panic if we do. */
1390 	panic("vm_map_findspace: max_free corrupt");
1391 }
1392 
1393 int
1394 vm_map_fixed(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1395     vm_offset_t start, vm_size_t length, vm_prot_t prot,
1396     vm_prot_t max, int cow)
1397 {
1398 	vm_offset_t end;
1399 	int result;
1400 
1401 	end = start + length;
1402 	KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
1403 	    object == NULL,
1404 	    ("vm_map_fixed: non-NULL backing object for stack"));
1405 	vm_map_lock(map);
1406 	VM_MAP_RANGE_CHECK(map, start, end);
1407 	if ((cow & MAP_CHECK_EXCL) == 0)
1408 		vm_map_delete(map, start, end);
1409 	if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
1410 		result = vm_map_stack_locked(map, start, length, sgrowsiz,
1411 		    prot, max, cow);
1412 	} else {
1413 		result = vm_map_insert(map, object, offset, start, end,
1414 		    prot, max, cow);
1415 	}
1416 	vm_map_unlock(map);
1417 	return (result);
1418 }
1419 
1420 /*
1421  *	vm_map_find finds an unallocated region in the target address
1422  *	map with the given length.  The search is defined to be
1423  *	first-fit from the specified address; the region found is
1424  *	returned in the same parameter.
1425  *
1426  *	If object is non-NULL, ref count must be bumped by caller
1427  *	prior to making call to account for the new entry.
1428  */
1429 int
1430 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1431 	    vm_offset_t *addr,	/* IN/OUT */
1432 	    vm_size_t length, vm_offset_t max_addr, int find_space,
1433 	    vm_prot_t prot, vm_prot_t max, int cow)
1434 {
1435 	vm_offset_t alignment, initial_addr, start;
1436 	int result;
1437 
1438 	KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
1439 	    object == NULL,
1440 	    ("vm_map_find: non-NULL backing object for stack"));
1441 	if (find_space == VMFS_OPTIMAL_SPACE && (object == NULL ||
1442 	    (object->flags & OBJ_COLORED) == 0))
1443 		find_space = VMFS_ANY_SPACE;
1444 	if (find_space >> 8 != 0) {
1445 		KASSERT((find_space & 0xff) == 0, ("bad VMFS flags"));
1446 		alignment = (vm_offset_t)1 << (find_space >> 8);
1447 	} else
1448 		alignment = 0;
1449 	initial_addr = *addr;
1450 again:
1451 	start = initial_addr;
1452 	vm_map_lock(map);
1453 	do {
1454 		if (find_space != VMFS_NO_SPACE) {
1455 			if (vm_map_findspace(map, start, length, addr) ||
1456 			    (max_addr != 0 && *addr + length > max_addr)) {
1457 				vm_map_unlock(map);
1458 				if (find_space == VMFS_OPTIMAL_SPACE) {
1459 					find_space = VMFS_ANY_SPACE;
1460 					goto again;
1461 				}
1462 				return (KERN_NO_SPACE);
1463 			}
1464 			switch (find_space) {
1465 			case VMFS_SUPER_SPACE:
1466 			case VMFS_OPTIMAL_SPACE:
1467 				pmap_align_superpage(object, offset, addr,
1468 				    length);
1469 				break;
1470 			case VMFS_ANY_SPACE:
1471 				break;
1472 			default:
1473 				if ((*addr & (alignment - 1)) != 0) {
1474 					*addr &= ~(alignment - 1);
1475 					*addr += alignment;
1476 				}
1477 				break;
1478 			}
1479 
1480 			start = *addr;
1481 		}
1482 		if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
1483 			result = vm_map_stack_locked(map, start, length,
1484 			    sgrowsiz, prot, max, cow);
1485 		} else {
1486 			result = vm_map_insert(map, object, offset, start,
1487 			    start + length, prot, max, cow);
1488 		}
1489 	} while (result == KERN_NO_SPACE && find_space != VMFS_NO_SPACE &&
1490 	    find_space != VMFS_ANY_SPACE);
1491 	vm_map_unlock(map);
1492 	return (result);
1493 }
1494 
1495 /*
1496  *	vm_map_simplify_entry:
1497  *
1498  *	Simplify the given map entry by merging with either neighbor.  This
1499  *	routine also has the ability to merge with both neighbors.
1500  *
1501  *	The map must be locked.
1502  *
1503  *	This routine guarentees that the passed entry remains valid (though
1504  *	possibly extended).  When merging, this routine may delete one or
1505  *	both neighbors.
1506  */
1507 void
1508 vm_map_simplify_entry(vm_map_t map, vm_map_entry_t entry)
1509 {
1510 	vm_map_entry_t next, prev;
1511 	vm_size_t prevsize, esize;
1512 
1513 	if ((entry->eflags & (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP |
1514 	    MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_IS_SUB_MAP)) != 0)
1515 		return;
1516 
1517 	prev = entry->prev;
1518 	if (prev != &map->header) {
1519 		prevsize = prev->end - prev->start;
1520 		if ( (prev->end == entry->start) &&
1521 		     (prev->object.vm_object == entry->object.vm_object) &&
1522 		     (!prev->object.vm_object ||
1523 			(prev->offset + prevsize == entry->offset)) &&
1524 		     (prev->eflags == entry->eflags) &&
1525 		     (prev->protection == entry->protection) &&
1526 		     (prev->max_protection == entry->max_protection) &&
1527 		     (prev->inheritance == entry->inheritance) &&
1528 		     (prev->wired_count == entry->wired_count) &&
1529 		     (prev->cred == entry->cred)) {
1530 			vm_map_entry_unlink(map, prev);
1531 			entry->start = prev->start;
1532 			entry->offset = prev->offset;
1533 			if (entry->prev != &map->header)
1534 				vm_map_entry_resize_free(map, entry->prev);
1535 
1536 			/*
1537 			 * If the backing object is a vnode object,
1538 			 * vm_object_deallocate() calls vrele().
1539 			 * However, vrele() does not lock the vnode
1540 			 * because the vnode has additional
1541 			 * references.  Thus, the map lock can be kept
1542 			 * without causing a lock-order reversal with
1543 			 * the vnode lock.
1544 			 *
1545 			 * Since we count the number of virtual page
1546 			 * mappings in object->un_pager.vnp.writemappings,
1547 			 * the writemappings value should not be adjusted
1548 			 * when the entry is disposed of.
1549 			 */
1550 			if (prev->object.vm_object)
1551 				vm_object_deallocate(prev->object.vm_object);
1552 			if (prev->cred != NULL)
1553 				crfree(prev->cred);
1554 			vm_map_entry_dispose(map, prev);
1555 		}
1556 	}
1557 
1558 	next = entry->next;
1559 	if (next != &map->header) {
1560 		esize = entry->end - entry->start;
1561 		if ((entry->end == next->start) &&
1562 		    (next->object.vm_object == entry->object.vm_object) &&
1563 		     (!entry->object.vm_object ||
1564 			(entry->offset + esize == next->offset)) &&
1565 		    (next->eflags == entry->eflags) &&
1566 		    (next->protection == entry->protection) &&
1567 		    (next->max_protection == entry->max_protection) &&
1568 		    (next->inheritance == entry->inheritance) &&
1569 		    (next->wired_count == entry->wired_count) &&
1570 		    (next->cred == entry->cred)) {
1571 			vm_map_entry_unlink(map, next);
1572 			entry->end = next->end;
1573 			vm_map_entry_resize_free(map, entry);
1574 
1575 			/*
1576 			 * See comment above.
1577 			 */
1578 			if (next->object.vm_object)
1579 				vm_object_deallocate(next->object.vm_object);
1580 			if (next->cred != NULL)
1581 				crfree(next->cred);
1582 			vm_map_entry_dispose(map, next);
1583 		}
1584 	}
1585 }
1586 /*
1587  *	vm_map_clip_start:	[ internal use only ]
1588  *
1589  *	Asserts that the given entry begins at or after
1590  *	the specified address; if necessary,
1591  *	it splits the entry into two.
1592  */
1593 #define vm_map_clip_start(map, entry, startaddr) \
1594 { \
1595 	if (startaddr > entry->start) \
1596 		_vm_map_clip_start(map, entry, startaddr); \
1597 }
1598 
1599 /*
1600  *	This routine is called only when it is known that
1601  *	the entry must be split.
1602  */
1603 static void
1604 _vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t start)
1605 {
1606 	vm_map_entry_t new_entry;
1607 
1608 	VM_MAP_ASSERT_LOCKED(map);
1609 
1610 	/*
1611 	 * Split off the front portion -- note that we must insert the new
1612 	 * entry BEFORE this one, so that this entry has the specified
1613 	 * starting address.
1614 	 */
1615 	vm_map_simplify_entry(map, entry);
1616 
1617 	/*
1618 	 * If there is no object backing this entry, we might as well create
1619 	 * one now.  If we defer it, an object can get created after the map
1620 	 * is clipped, and individual objects will be created for the split-up
1621 	 * map.  This is a bit of a hack, but is also about the best place to
1622 	 * put this improvement.
1623 	 */
1624 	if (entry->object.vm_object == NULL && !map->system_map) {
1625 		vm_object_t object;
1626 		object = vm_object_allocate(OBJT_DEFAULT,
1627 				atop(entry->end - entry->start));
1628 		entry->object.vm_object = object;
1629 		entry->offset = 0;
1630 		if (entry->cred != NULL) {
1631 			object->cred = entry->cred;
1632 			object->charge = entry->end - entry->start;
1633 			entry->cred = NULL;
1634 		}
1635 	} else if (entry->object.vm_object != NULL &&
1636 		   ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
1637 		   entry->cred != NULL) {
1638 		VM_OBJECT_WLOCK(entry->object.vm_object);
1639 		KASSERT(entry->object.vm_object->cred == NULL,
1640 		    ("OVERCOMMIT: vm_entry_clip_start: both cred e %p", entry));
1641 		entry->object.vm_object->cred = entry->cred;
1642 		entry->object.vm_object->charge = entry->end - entry->start;
1643 		VM_OBJECT_WUNLOCK(entry->object.vm_object);
1644 		entry->cred = NULL;
1645 	}
1646 
1647 	new_entry = vm_map_entry_create(map);
1648 	*new_entry = *entry;
1649 
1650 	new_entry->end = start;
1651 	entry->offset += (start - entry->start);
1652 	entry->start = start;
1653 	if (new_entry->cred != NULL)
1654 		crhold(entry->cred);
1655 
1656 	vm_map_entry_link(map, entry->prev, new_entry);
1657 
1658 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1659 		vm_object_reference(new_entry->object.vm_object);
1660 		/*
1661 		 * The object->un_pager.vnp.writemappings for the
1662 		 * object of MAP_ENTRY_VN_WRITECNT type entry shall be
1663 		 * kept as is here.  The virtual pages are
1664 		 * re-distributed among the clipped entries, so the sum is
1665 		 * left the same.
1666 		 */
1667 	}
1668 }
1669 
1670 /*
1671  *	vm_map_clip_end:	[ internal use only ]
1672  *
1673  *	Asserts that the given entry ends at or before
1674  *	the specified address; if necessary,
1675  *	it splits the entry into two.
1676  */
1677 #define vm_map_clip_end(map, entry, endaddr) \
1678 { \
1679 	if ((endaddr) < (entry->end)) \
1680 		_vm_map_clip_end((map), (entry), (endaddr)); \
1681 }
1682 
1683 /*
1684  *	This routine is called only when it is known that
1685  *	the entry must be split.
1686  */
1687 static void
1688 _vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t end)
1689 {
1690 	vm_map_entry_t new_entry;
1691 
1692 	VM_MAP_ASSERT_LOCKED(map);
1693 
1694 	/*
1695 	 * If there is no object backing this entry, we might as well create
1696 	 * one now.  If we defer it, an object can get created after the map
1697 	 * is clipped, and individual objects will be created for the split-up
1698 	 * map.  This is a bit of a hack, but is also about the best place to
1699 	 * put this improvement.
1700 	 */
1701 	if (entry->object.vm_object == NULL && !map->system_map) {
1702 		vm_object_t object;
1703 		object = vm_object_allocate(OBJT_DEFAULT,
1704 				atop(entry->end - entry->start));
1705 		entry->object.vm_object = object;
1706 		entry->offset = 0;
1707 		if (entry->cred != NULL) {
1708 			object->cred = entry->cred;
1709 			object->charge = entry->end - entry->start;
1710 			entry->cred = NULL;
1711 		}
1712 	} else if (entry->object.vm_object != NULL &&
1713 		   ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
1714 		   entry->cred != NULL) {
1715 		VM_OBJECT_WLOCK(entry->object.vm_object);
1716 		KASSERT(entry->object.vm_object->cred == NULL,
1717 		    ("OVERCOMMIT: vm_entry_clip_end: both cred e %p", entry));
1718 		entry->object.vm_object->cred = entry->cred;
1719 		entry->object.vm_object->charge = entry->end - entry->start;
1720 		VM_OBJECT_WUNLOCK(entry->object.vm_object);
1721 		entry->cred = NULL;
1722 	}
1723 
1724 	/*
1725 	 * Create a new entry and insert it AFTER the specified entry
1726 	 */
1727 	new_entry = vm_map_entry_create(map);
1728 	*new_entry = *entry;
1729 
1730 	new_entry->start = entry->end = end;
1731 	new_entry->offset += (end - entry->start);
1732 	if (new_entry->cred != NULL)
1733 		crhold(entry->cred);
1734 
1735 	vm_map_entry_link(map, entry, new_entry);
1736 
1737 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1738 		vm_object_reference(new_entry->object.vm_object);
1739 	}
1740 }
1741 
1742 /*
1743  *	vm_map_submap:		[ kernel use only ]
1744  *
1745  *	Mark the given range as handled by a subordinate map.
1746  *
1747  *	This range must have been created with vm_map_find,
1748  *	and no other operations may have been performed on this
1749  *	range prior to calling vm_map_submap.
1750  *
1751  *	Only a limited number of operations can be performed
1752  *	within this rage after calling vm_map_submap:
1753  *		vm_fault
1754  *	[Don't try vm_map_copy!]
1755  *
1756  *	To remove a submapping, one must first remove the
1757  *	range from the superior map, and then destroy the
1758  *	submap (if desired).  [Better yet, don't try it.]
1759  */
1760 int
1761 vm_map_submap(
1762 	vm_map_t map,
1763 	vm_offset_t start,
1764 	vm_offset_t end,
1765 	vm_map_t submap)
1766 {
1767 	vm_map_entry_t entry;
1768 	int result = KERN_INVALID_ARGUMENT;
1769 
1770 	vm_map_lock(map);
1771 
1772 	VM_MAP_RANGE_CHECK(map, start, end);
1773 
1774 	if (vm_map_lookup_entry(map, start, &entry)) {
1775 		vm_map_clip_start(map, entry, start);
1776 	} else
1777 		entry = entry->next;
1778 
1779 	vm_map_clip_end(map, entry, end);
1780 
1781 	if ((entry->start == start) && (entry->end == end) &&
1782 	    ((entry->eflags & MAP_ENTRY_COW) == 0) &&
1783 	    (entry->object.vm_object == NULL)) {
1784 		entry->object.sub_map = submap;
1785 		entry->eflags |= MAP_ENTRY_IS_SUB_MAP;
1786 		result = KERN_SUCCESS;
1787 	}
1788 	vm_map_unlock(map);
1789 
1790 	return (result);
1791 }
1792 
1793 /*
1794  * The maximum number of pages to map if MAP_PREFAULT_PARTIAL is specified
1795  */
1796 #define	MAX_INIT_PT	96
1797 
1798 /*
1799  *	vm_map_pmap_enter:
1800  *
1801  *	Preload the specified map's pmap with mappings to the specified
1802  *	object's memory-resident pages.  No further physical pages are
1803  *	allocated, and no further virtual pages are retrieved from secondary
1804  *	storage.  If the specified flags include MAP_PREFAULT_PARTIAL, then a
1805  *	limited number of page mappings are created at the low-end of the
1806  *	specified address range.  (For this purpose, a superpage mapping
1807  *	counts as one page mapping.)  Otherwise, all resident pages within
1808  *	the specified address range are mapped.  Because these mappings are
1809  *	being created speculatively, cached pages are not reactivated and
1810  *	mapped.
1811  */
1812 void
1813 vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
1814     vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags)
1815 {
1816 	vm_offset_t start;
1817 	vm_page_t p, p_start;
1818 	vm_pindex_t mask, psize, threshold, tmpidx;
1819 
1820 	if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0 || object == NULL)
1821 		return;
1822 	VM_OBJECT_RLOCK(object);
1823 	if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
1824 		VM_OBJECT_RUNLOCK(object);
1825 		VM_OBJECT_WLOCK(object);
1826 		if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
1827 			pmap_object_init_pt(map->pmap, addr, object, pindex,
1828 			    size);
1829 			VM_OBJECT_WUNLOCK(object);
1830 			return;
1831 		}
1832 		VM_OBJECT_LOCK_DOWNGRADE(object);
1833 	}
1834 
1835 	psize = atop(size);
1836 	if (psize + pindex > object->size) {
1837 		if (object->size < pindex) {
1838 			VM_OBJECT_RUNLOCK(object);
1839 			return;
1840 		}
1841 		psize = object->size - pindex;
1842 	}
1843 
1844 	start = 0;
1845 	p_start = NULL;
1846 	threshold = MAX_INIT_PT;
1847 
1848 	p = vm_page_find_least(object, pindex);
1849 	/*
1850 	 * Assert: the variable p is either (1) the page with the
1851 	 * least pindex greater than or equal to the parameter pindex
1852 	 * or (2) NULL.
1853 	 */
1854 	for (;
1855 	     p != NULL && (tmpidx = p->pindex - pindex) < psize;
1856 	     p = TAILQ_NEXT(p, listq)) {
1857 		/*
1858 		 * don't allow an madvise to blow away our really
1859 		 * free pages allocating pv entries.
1860 		 */
1861 		if (((flags & MAP_PREFAULT_MADVISE) != 0 &&
1862 		    vm_cnt.v_free_count < vm_cnt.v_free_reserved) ||
1863 		    ((flags & MAP_PREFAULT_PARTIAL) != 0 &&
1864 		    tmpidx >= threshold)) {
1865 			psize = tmpidx;
1866 			break;
1867 		}
1868 		if (p->valid == VM_PAGE_BITS_ALL) {
1869 			if (p_start == NULL) {
1870 				start = addr + ptoa(tmpidx);
1871 				p_start = p;
1872 			}
1873 			/* Jump ahead if a superpage mapping is possible. */
1874 			if (p->psind > 0 && ((addr + ptoa(tmpidx)) &
1875 			    (pagesizes[p->psind] - 1)) == 0) {
1876 				mask = atop(pagesizes[p->psind]) - 1;
1877 				if (tmpidx + mask < psize &&
1878 				    vm_page_ps_is_valid(p)) {
1879 					p += mask;
1880 					threshold += mask;
1881 				}
1882 			}
1883 		} else if (p_start != NULL) {
1884 			pmap_enter_object(map->pmap, start, addr +
1885 			    ptoa(tmpidx), p_start, prot);
1886 			p_start = NULL;
1887 		}
1888 	}
1889 	if (p_start != NULL)
1890 		pmap_enter_object(map->pmap, start, addr + ptoa(psize),
1891 		    p_start, prot);
1892 	VM_OBJECT_RUNLOCK(object);
1893 }
1894 
1895 /*
1896  *	vm_map_protect:
1897  *
1898  *	Sets the protection of the specified address
1899  *	region in the target map.  If "set_max" is
1900  *	specified, the maximum protection is to be set;
1901  *	otherwise, only the current protection is affected.
1902  */
1903 int
1904 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
1905 	       vm_prot_t new_prot, boolean_t set_max)
1906 {
1907 	vm_map_entry_t current, entry;
1908 	vm_object_t obj;
1909 	struct ucred *cred;
1910 	vm_prot_t old_prot;
1911 
1912 	if (start == end)
1913 		return (KERN_SUCCESS);
1914 
1915 	vm_map_lock(map);
1916 
1917 	VM_MAP_RANGE_CHECK(map, start, end);
1918 
1919 	if (vm_map_lookup_entry(map, start, &entry)) {
1920 		vm_map_clip_start(map, entry, start);
1921 	} else {
1922 		entry = entry->next;
1923 	}
1924 
1925 	/*
1926 	 * Make a first pass to check for protection violations.
1927 	 */
1928 	current = entry;
1929 	while ((current != &map->header) && (current->start < end)) {
1930 		if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
1931 			vm_map_unlock(map);
1932 			return (KERN_INVALID_ARGUMENT);
1933 		}
1934 		if ((new_prot & current->max_protection) != new_prot) {
1935 			vm_map_unlock(map);
1936 			return (KERN_PROTECTION_FAILURE);
1937 		}
1938 		current = current->next;
1939 	}
1940 
1941 
1942 	/*
1943 	 * Do an accounting pass for private read-only mappings that
1944 	 * now will do cow due to allowed write (e.g. debugger sets
1945 	 * breakpoint on text segment)
1946 	 */
1947 	for (current = entry; (current != &map->header) &&
1948 	     (current->start < end); current = current->next) {
1949 
1950 		vm_map_clip_end(map, current, end);
1951 
1952 		if (set_max ||
1953 		    ((new_prot & ~(current->protection)) & VM_PROT_WRITE) == 0 ||
1954 		    ENTRY_CHARGED(current)) {
1955 			continue;
1956 		}
1957 
1958 		cred = curthread->td_ucred;
1959 		obj = current->object.vm_object;
1960 
1961 		if (obj == NULL || (current->eflags & MAP_ENTRY_NEEDS_COPY)) {
1962 			if (!swap_reserve(current->end - current->start)) {
1963 				vm_map_unlock(map);
1964 				return (KERN_RESOURCE_SHORTAGE);
1965 			}
1966 			crhold(cred);
1967 			current->cred = cred;
1968 			continue;
1969 		}
1970 
1971 		VM_OBJECT_WLOCK(obj);
1972 		if (obj->type != OBJT_DEFAULT && obj->type != OBJT_SWAP) {
1973 			VM_OBJECT_WUNLOCK(obj);
1974 			continue;
1975 		}
1976 
1977 		/*
1978 		 * Charge for the whole object allocation now, since
1979 		 * we cannot distinguish between non-charged and
1980 		 * charged clipped mapping of the same object later.
1981 		 */
1982 		KASSERT(obj->charge == 0,
1983 		    ("vm_map_protect: object %p overcharged (entry %p)",
1984 		    obj, current));
1985 		if (!swap_reserve(ptoa(obj->size))) {
1986 			VM_OBJECT_WUNLOCK(obj);
1987 			vm_map_unlock(map);
1988 			return (KERN_RESOURCE_SHORTAGE);
1989 		}
1990 
1991 		crhold(cred);
1992 		obj->cred = cred;
1993 		obj->charge = ptoa(obj->size);
1994 		VM_OBJECT_WUNLOCK(obj);
1995 	}
1996 
1997 	/*
1998 	 * Go back and fix up protections. [Note that clipping is not
1999 	 * necessary the second time.]
2000 	 */
2001 	current = entry;
2002 	while ((current != &map->header) && (current->start < end)) {
2003 		old_prot = current->protection;
2004 
2005 		if (set_max)
2006 			current->protection =
2007 			    (current->max_protection = new_prot) &
2008 			    old_prot;
2009 		else
2010 			current->protection = new_prot;
2011 
2012 		/*
2013 		 * For user wired map entries, the normal lazy evaluation of
2014 		 * write access upgrades through soft page faults is
2015 		 * undesirable.  Instead, immediately copy any pages that are
2016 		 * copy-on-write and enable write access in the physical map.
2017 		 */
2018 		if ((current->eflags & MAP_ENTRY_USER_WIRED) != 0 &&
2019 		    (current->protection & VM_PROT_WRITE) != 0 &&
2020 		    (old_prot & VM_PROT_WRITE) == 0)
2021 			vm_fault_copy_entry(map, map, current, current, NULL);
2022 
2023 		/*
2024 		 * When restricting access, update the physical map.  Worry
2025 		 * about copy-on-write here.
2026 		 */
2027 		if ((old_prot & ~current->protection) != 0) {
2028 #define MASK(entry)	(((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
2029 							VM_PROT_ALL)
2030 			pmap_protect(map->pmap, current->start,
2031 			    current->end,
2032 			    current->protection & MASK(current));
2033 #undef	MASK
2034 		}
2035 		vm_map_simplify_entry(map, current);
2036 		current = current->next;
2037 	}
2038 	vm_map_unlock(map);
2039 	return (KERN_SUCCESS);
2040 }
2041 
2042 /*
2043  *	vm_map_madvise:
2044  *
2045  *	This routine traverses a processes map handling the madvise
2046  *	system call.  Advisories are classified as either those effecting
2047  *	the vm_map_entry structure, or those effecting the underlying
2048  *	objects.
2049  */
2050 int
2051 vm_map_madvise(
2052 	vm_map_t map,
2053 	vm_offset_t start,
2054 	vm_offset_t end,
2055 	int behav)
2056 {
2057 	vm_map_entry_t current, entry;
2058 	int modify_map = 0;
2059 
2060 	/*
2061 	 * Some madvise calls directly modify the vm_map_entry, in which case
2062 	 * we need to use an exclusive lock on the map and we need to perform
2063 	 * various clipping operations.  Otherwise we only need a read-lock
2064 	 * on the map.
2065 	 */
2066 	switch(behav) {
2067 	case MADV_NORMAL:
2068 	case MADV_SEQUENTIAL:
2069 	case MADV_RANDOM:
2070 	case MADV_NOSYNC:
2071 	case MADV_AUTOSYNC:
2072 	case MADV_NOCORE:
2073 	case MADV_CORE:
2074 		if (start == end)
2075 			return (KERN_SUCCESS);
2076 		modify_map = 1;
2077 		vm_map_lock(map);
2078 		break;
2079 	case MADV_WILLNEED:
2080 	case MADV_DONTNEED:
2081 	case MADV_FREE:
2082 		if (start == end)
2083 			return (KERN_SUCCESS);
2084 		vm_map_lock_read(map);
2085 		break;
2086 	default:
2087 		return (KERN_INVALID_ARGUMENT);
2088 	}
2089 
2090 	/*
2091 	 * Locate starting entry and clip if necessary.
2092 	 */
2093 	VM_MAP_RANGE_CHECK(map, start, end);
2094 
2095 	if (vm_map_lookup_entry(map, start, &entry)) {
2096 		if (modify_map)
2097 			vm_map_clip_start(map, entry, start);
2098 	} else {
2099 		entry = entry->next;
2100 	}
2101 
2102 	if (modify_map) {
2103 		/*
2104 		 * madvise behaviors that are implemented in the vm_map_entry.
2105 		 *
2106 		 * We clip the vm_map_entry so that behavioral changes are
2107 		 * limited to the specified address range.
2108 		 */
2109 		for (current = entry;
2110 		     (current != &map->header) && (current->start < end);
2111 		     current = current->next
2112 		) {
2113 			if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
2114 				continue;
2115 
2116 			vm_map_clip_end(map, current, end);
2117 
2118 			switch (behav) {
2119 			case MADV_NORMAL:
2120 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_NORMAL);
2121 				break;
2122 			case MADV_SEQUENTIAL:
2123 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_SEQUENTIAL);
2124 				break;
2125 			case MADV_RANDOM:
2126 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_RANDOM);
2127 				break;
2128 			case MADV_NOSYNC:
2129 				current->eflags |= MAP_ENTRY_NOSYNC;
2130 				break;
2131 			case MADV_AUTOSYNC:
2132 				current->eflags &= ~MAP_ENTRY_NOSYNC;
2133 				break;
2134 			case MADV_NOCORE:
2135 				current->eflags |= MAP_ENTRY_NOCOREDUMP;
2136 				break;
2137 			case MADV_CORE:
2138 				current->eflags &= ~MAP_ENTRY_NOCOREDUMP;
2139 				break;
2140 			default:
2141 				break;
2142 			}
2143 			vm_map_simplify_entry(map, current);
2144 		}
2145 		vm_map_unlock(map);
2146 	} else {
2147 		vm_pindex_t pstart, pend;
2148 
2149 		/*
2150 		 * madvise behaviors that are implemented in the underlying
2151 		 * vm_object.
2152 		 *
2153 		 * Since we don't clip the vm_map_entry, we have to clip
2154 		 * the vm_object pindex and count.
2155 		 */
2156 		for (current = entry;
2157 		     (current != &map->header) && (current->start < end);
2158 		     current = current->next
2159 		) {
2160 			vm_offset_t useEnd, useStart;
2161 
2162 			if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
2163 				continue;
2164 
2165 			pstart = OFF_TO_IDX(current->offset);
2166 			pend = pstart + atop(current->end - current->start);
2167 			useStart = current->start;
2168 			useEnd = current->end;
2169 
2170 			if (current->start < start) {
2171 				pstart += atop(start - current->start);
2172 				useStart = start;
2173 			}
2174 			if (current->end > end) {
2175 				pend -= atop(current->end - end);
2176 				useEnd = end;
2177 			}
2178 
2179 			if (pstart >= pend)
2180 				continue;
2181 
2182 			/*
2183 			 * Perform the pmap_advise() before clearing
2184 			 * PGA_REFERENCED in vm_page_advise().  Otherwise, a
2185 			 * concurrent pmap operation, such as pmap_remove(),
2186 			 * could clear a reference in the pmap and set
2187 			 * PGA_REFERENCED on the page before the pmap_advise()
2188 			 * had completed.  Consequently, the page would appear
2189 			 * referenced based upon an old reference that
2190 			 * occurred before this pmap_advise() ran.
2191 			 */
2192 			if (behav == MADV_DONTNEED || behav == MADV_FREE)
2193 				pmap_advise(map->pmap, useStart, useEnd,
2194 				    behav);
2195 
2196 			vm_object_madvise(current->object.vm_object, pstart,
2197 			    pend, behav);
2198 			if (behav == MADV_WILLNEED) {
2199 				vm_map_pmap_enter(map,
2200 				    useStart,
2201 				    current->protection,
2202 				    current->object.vm_object,
2203 				    pstart,
2204 				    ptoa(pend - pstart),
2205 				    MAP_PREFAULT_MADVISE
2206 				);
2207 			}
2208 		}
2209 		vm_map_unlock_read(map);
2210 	}
2211 	return (0);
2212 }
2213 
2214 
2215 /*
2216  *	vm_map_inherit:
2217  *
2218  *	Sets the inheritance of the specified address
2219  *	range in the target map.  Inheritance
2220  *	affects how the map will be shared with
2221  *	child maps at the time of vmspace_fork.
2222  */
2223 int
2224 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
2225 	       vm_inherit_t new_inheritance)
2226 {
2227 	vm_map_entry_t entry;
2228 	vm_map_entry_t temp_entry;
2229 
2230 	switch (new_inheritance) {
2231 	case VM_INHERIT_NONE:
2232 	case VM_INHERIT_COPY:
2233 	case VM_INHERIT_SHARE:
2234 		break;
2235 	default:
2236 		return (KERN_INVALID_ARGUMENT);
2237 	}
2238 	if (start == end)
2239 		return (KERN_SUCCESS);
2240 	vm_map_lock(map);
2241 	VM_MAP_RANGE_CHECK(map, start, end);
2242 	if (vm_map_lookup_entry(map, start, &temp_entry)) {
2243 		entry = temp_entry;
2244 		vm_map_clip_start(map, entry, start);
2245 	} else
2246 		entry = temp_entry->next;
2247 	while ((entry != &map->header) && (entry->start < end)) {
2248 		vm_map_clip_end(map, entry, end);
2249 		entry->inheritance = new_inheritance;
2250 		vm_map_simplify_entry(map, entry);
2251 		entry = entry->next;
2252 	}
2253 	vm_map_unlock(map);
2254 	return (KERN_SUCCESS);
2255 }
2256 
2257 /*
2258  *	vm_map_unwire:
2259  *
2260  *	Implements both kernel and user unwiring.
2261  */
2262 int
2263 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t end,
2264     int flags)
2265 {
2266 	vm_map_entry_t entry, first_entry, tmp_entry;
2267 	vm_offset_t saved_start;
2268 	unsigned int last_timestamp;
2269 	int rv;
2270 	boolean_t need_wakeup, result, user_unwire;
2271 
2272 	if (start == end)
2273 		return (KERN_SUCCESS);
2274 	user_unwire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
2275 	vm_map_lock(map);
2276 	VM_MAP_RANGE_CHECK(map, start, end);
2277 	if (!vm_map_lookup_entry(map, start, &first_entry)) {
2278 		if (flags & VM_MAP_WIRE_HOLESOK)
2279 			first_entry = first_entry->next;
2280 		else {
2281 			vm_map_unlock(map);
2282 			return (KERN_INVALID_ADDRESS);
2283 		}
2284 	}
2285 	last_timestamp = map->timestamp;
2286 	entry = first_entry;
2287 	while (entry != &map->header && entry->start < end) {
2288 		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
2289 			/*
2290 			 * We have not yet clipped the entry.
2291 			 */
2292 			saved_start = (start >= entry->start) ? start :
2293 			    entry->start;
2294 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2295 			if (vm_map_unlock_and_wait(map, 0)) {
2296 				/*
2297 				 * Allow interruption of user unwiring?
2298 				 */
2299 			}
2300 			vm_map_lock(map);
2301 			if (last_timestamp+1 != map->timestamp) {
2302 				/*
2303 				 * Look again for the entry because the map was
2304 				 * modified while it was unlocked.
2305 				 * Specifically, the entry may have been
2306 				 * clipped, merged, or deleted.
2307 				 */
2308 				if (!vm_map_lookup_entry(map, saved_start,
2309 				    &tmp_entry)) {
2310 					if (flags & VM_MAP_WIRE_HOLESOK)
2311 						tmp_entry = tmp_entry->next;
2312 					else {
2313 						if (saved_start == start) {
2314 							/*
2315 							 * First_entry has been deleted.
2316 							 */
2317 							vm_map_unlock(map);
2318 							return (KERN_INVALID_ADDRESS);
2319 						}
2320 						end = saved_start;
2321 						rv = KERN_INVALID_ADDRESS;
2322 						goto done;
2323 					}
2324 				}
2325 				if (entry == first_entry)
2326 					first_entry = tmp_entry;
2327 				else
2328 					first_entry = NULL;
2329 				entry = tmp_entry;
2330 			}
2331 			last_timestamp = map->timestamp;
2332 			continue;
2333 		}
2334 		vm_map_clip_start(map, entry, start);
2335 		vm_map_clip_end(map, entry, end);
2336 		/*
2337 		 * Mark the entry in case the map lock is released.  (See
2338 		 * above.)
2339 		 */
2340 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
2341 		    entry->wiring_thread == NULL,
2342 		    ("owned map entry %p", entry));
2343 		entry->eflags |= MAP_ENTRY_IN_TRANSITION;
2344 		entry->wiring_thread = curthread;
2345 		/*
2346 		 * Check the map for holes in the specified region.
2347 		 * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
2348 		 */
2349 		if (((flags & VM_MAP_WIRE_HOLESOK) == 0) &&
2350 		    (entry->end < end && (entry->next == &map->header ||
2351 		    entry->next->start > entry->end))) {
2352 			end = entry->end;
2353 			rv = KERN_INVALID_ADDRESS;
2354 			goto done;
2355 		}
2356 		/*
2357 		 * If system unwiring, require that the entry is system wired.
2358 		 */
2359 		if (!user_unwire &&
2360 		    vm_map_entry_system_wired_count(entry) == 0) {
2361 			end = entry->end;
2362 			rv = KERN_INVALID_ARGUMENT;
2363 			goto done;
2364 		}
2365 		entry = entry->next;
2366 	}
2367 	rv = KERN_SUCCESS;
2368 done:
2369 	need_wakeup = FALSE;
2370 	if (first_entry == NULL) {
2371 		result = vm_map_lookup_entry(map, start, &first_entry);
2372 		if (!result && (flags & VM_MAP_WIRE_HOLESOK))
2373 			first_entry = first_entry->next;
2374 		else
2375 			KASSERT(result, ("vm_map_unwire: lookup failed"));
2376 	}
2377 	for (entry = first_entry; entry != &map->header && entry->start < end;
2378 	    entry = entry->next) {
2379 		/*
2380 		 * If VM_MAP_WIRE_HOLESOK was specified, an empty
2381 		 * space in the unwired region could have been mapped
2382 		 * while the map lock was dropped for draining
2383 		 * MAP_ENTRY_IN_TRANSITION.  Moreover, another thread
2384 		 * could be simultaneously wiring this new mapping
2385 		 * entry.  Detect these cases and skip any entries
2386 		 * marked as in transition by us.
2387 		 */
2388 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
2389 		    entry->wiring_thread != curthread) {
2390 			KASSERT((flags & VM_MAP_WIRE_HOLESOK) != 0,
2391 			    ("vm_map_unwire: !HOLESOK and new/changed entry"));
2392 			continue;
2393 		}
2394 
2395 		if (rv == KERN_SUCCESS && (!user_unwire ||
2396 		    (entry->eflags & MAP_ENTRY_USER_WIRED))) {
2397 			if (user_unwire)
2398 				entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2399 			if (entry->wired_count == 1)
2400 				vm_map_entry_unwire(map, entry);
2401 			else
2402 				entry->wired_count--;
2403 		}
2404 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
2405 		    ("vm_map_unwire: in-transition flag missing %p", entry));
2406 		KASSERT(entry->wiring_thread == curthread,
2407 		    ("vm_map_unwire: alien wire %p", entry));
2408 		entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
2409 		entry->wiring_thread = NULL;
2410 		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
2411 			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
2412 			need_wakeup = TRUE;
2413 		}
2414 		vm_map_simplify_entry(map, entry);
2415 	}
2416 	vm_map_unlock(map);
2417 	if (need_wakeup)
2418 		vm_map_wakeup(map);
2419 	return (rv);
2420 }
2421 
2422 /*
2423  *	vm_map_wire_entry_failure:
2424  *
2425  *	Handle a wiring failure on the given entry.
2426  *
2427  *	The map should be locked.
2428  */
2429 static void
2430 vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
2431     vm_offset_t failed_addr)
2432 {
2433 
2434 	VM_MAP_ASSERT_LOCKED(map);
2435 	KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 &&
2436 	    entry->wired_count == 1,
2437 	    ("vm_map_wire_entry_failure: entry %p isn't being wired", entry));
2438 	KASSERT(failed_addr < entry->end,
2439 	    ("vm_map_wire_entry_failure: entry %p was fully wired", entry));
2440 
2441 	/*
2442 	 * If any pages at the start of this entry were successfully wired,
2443 	 * then unwire them.
2444 	 */
2445 	if (failed_addr > entry->start) {
2446 		pmap_unwire(map->pmap, entry->start, failed_addr);
2447 		vm_object_unwire(entry->object.vm_object, entry->offset,
2448 		    failed_addr - entry->start, PQ_ACTIVE);
2449 	}
2450 
2451 	/*
2452 	 * Assign an out-of-range value to represent the failure to wire this
2453 	 * entry.
2454 	 */
2455 	entry->wired_count = -1;
2456 }
2457 
2458 /*
2459  *	vm_map_wire:
2460  *
2461  *	Implements both kernel and user wiring.
2462  */
2463 int
2464 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t end,
2465     int flags)
2466 {
2467 	vm_map_entry_t entry, first_entry, tmp_entry;
2468 	vm_offset_t faddr, saved_end, saved_start;
2469 	unsigned int last_timestamp;
2470 	int rv;
2471 	boolean_t need_wakeup, result, user_wire;
2472 	vm_prot_t prot;
2473 
2474 	if (start == end)
2475 		return (KERN_SUCCESS);
2476 	prot = 0;
2477 	if (flags & VM_MAP_WIRE_WRITE)
2478 		prot |= VM_PROT_WRITE;
2479 	user_wire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
2480 	vm_map_lock(map);
2481 	VM_MAP_RANGE_CHECK(map, start, end);
2482 	if (!vm_map_lookup_entry(map, start, &first_entry)) {
2483 		if (flags & VM_MAP_WIRE_HOLESOK)
2484 			first_entry = first_entry->next;
2485 		else {
2486 			vm_map_unlock(map);
2487 			return (KERN_INVALID_ADDRESS);
2488 		}
2489 	}
2490 	last_timestamp = map->timestamp;
2491 	entry = first_entry;
2492 	while (entry != &map->header && entry->start < end) {
2493 		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
2494 			/*
2495 			 * We have not yet clipped the entry.
2496 			 */
2497 			saved_start = (start >= entry->start) ? start :
2498 			    entry->start;
2499 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2500 			if (vm_map_unlock_and_wait(map, 0)) {
2501 				/*
2502 				 * Allow interruption of user wiring?
2503 				 */
2504 			}
2505 			vm_map_lock(map);
2506 			if (last_timestamp + 1 != map->timestamp) {
2507 				/*
2508 				 * Look again for the entry because the map was
2509 				 * modified while it was unlocked.
2510 				 * Specifically, the entry may have been
2511 				 * clipped, merged, or deleted.
2512 				 */
2513 				if (!vm_map_lookup_entry(map, saved_start,
2514 				    &tmp_entry)) {
2515 					if (flags & VM_MAP_WIRE_HOLESOK)
2516 						tmp_entry = tmp_entry->next;
2517 					else {
2518 						if (saved_start == start) {
2519 							/*
2520 							 * first_entry has been deleted.
2521 							 */
2522 							vm_map_unlock(map);
2523 							return (KERN_INVALID_ADDRESS);
2524 						}
2525 						end = saved_start;
2526 						rv = KERN_INVALID_ADDRESS;
2527 						goto done;
2528 					}
2529 				}
2530 				if (entry == first_entry)
2531 					first_entry = tmp_entry;
2532 				else
2533 					first_entry = NULL;
2534 				entry = tmp_entry;
2535 			}
2536 			last_timestamp = map->timestamp;
2537 			continue;
2538 		}
2539 		vm_map_clip_start(map, entry, start);
2540 		vm_map_clip_end(map, entry, end);
2541 		/*
2542 		 * Mark the entry in case the map lock is released.  (See
2543 		 * above.)
2544 		 */
2545 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
2546 		    entry->wiring_thread == NULL,
2547 		    ("owned map entry %p", entry));
2548 		entry->eflags |= MAP_ENTRY_IN_TRANSITION;
2549 		entry->wiring_thread = curthread;
2550 		if ((entry->protection & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0
2551 		    || (entry->protection & prot) != prot) {
2552 			entry->eflags |= MAP_ENTRY_WIRE_SKIPPED;
2553 			if ((flags & VM_MAP_WIRE_HOLESOK) == 0) {
2554 				end = entry->end;
2555 				rv = KERN_INVALID_ADDRESS;
2556 				goto done;
2557 			}
2558 			goto next_entry;
2559 		}
2560 		if (entry->wired_count == 0) {
2561 			entry->wired_count++;
2562 			saved_start = entry->start;
2563 			saved_end = entry->end;
2564 
2565 			/*
2566 			 * Release the map lock, relying on the in-transition
2567 			 * mark.  Mark the map busy for fork.
2568 			 */
2569 			vm_map_busy(map);
2570 			vm_map_unlock(map);
2571 
2572 			faddr = saved_start;
2573 			do {
2574 				/*
2575 				 * Simulate a fault to get the page and enter
2576 				 * it into the physical map.
2577 				 */
2578 				if ((rv = vm_fault(map, faddr, VM_PROT_NONE,
2579 				    VM_FAULT_CHANGE_WIRING)) != KERN_SUCCESS)
2580 					break;
2581 			} while ((faddr += PAGE_SIZE) < saved_end);
2582 			vm_map_lock(map);
2583 			vm_map_unbusy(map);
2584 			if (last_timestamp + 1 != map->timestamp) {
2585 				/*
2586 				 * Look again for the entry because the map was
2587 				 * modified while it was unlocked.  The entry
2588 				 * may have been clipped, but NOT merged or
2589 				 * deleted.
2590 				 */
2591 				result = vm_map_lookup_entry(map, saved_start,
2592 				    &tmp_entry);
2593 				KASSERT(result, ("vm_map_wire: lookup failed"));
2594 				if (entry == first_entry)
2595 					first_entry = tmp_entry;
2596 				else
2597 					first_entry = NULL;
2598 				entry = tmp_entry;
2599 				while (entry->end < saved_end) {
2600 					/*
2601 					 * In case of failure, handle entries
2602 					 * that were not fully wired here;
2603 					 * fully wired entries are handled
2604 					 * later.
2605 					 */
2606 					if (rv != KERN_SUCCESS &&
2607 					    faddr < entry->end)
2608 						vm_map_wire_entry_failure(map,
2609 						    entry, faddr);
2610 					entry = entry->next;
2611 				}
2612 			}
2613 			last_timestamp = map->timestamp;
2614 			if (rv != KERN_SUCCESS) {
2615 				vm_map_wire_entry_failure(map, entry, faddr);
2616 				end = entry->end;
2617 				goto done;
2618 			}
2619 		} else if (!user_wire ||
2620 			   (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
2621 			entry->wired_count++;
2622 		}
2623 		/*
2624 		 * Check the map for holes in the specified region.
2625 		 * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
2626 		 */
2627 	next_entry:
2628 		if (((flags & VM_MAP_WIRE_HOLESOK) == 0) &&
2629 		    (entry->end < end && (entry->next == &map->header ||
2630 		    entry->next->start > entry->end))) {
2631 			end = entry->end;
2632 			rv = KERN_INVALID_ADDRESS;
2633 			goto done;
2634 		}
2635 		entry = entry->next;
2636 	}
2637 	rv = KERN_SUCCESS;
2638 done:
2639 	need_wakeup = FALSE;
2640 	if (first_entry == NULL) {
2641 		result = vm_map_lookup_entry(map, start, &first_entry);
2642 		if (!result && (flags & VM_MAP_WIRE_HOLESOK))
2643 			first_entry = first_entry->next;
2644 		else
2645 			KASSERT(result, ("vm_map_wire: lookup failed"));
2646 	}
2647 	for (entry = first_entry; entry != &map->header && entry->start < end;
2648 	    entry = entry->next) {
2649 		if ((entry->eflags & MAP_ENTRY_WIRE_SKIPPED) != 0)
2650 			goto next_entry_done;
2651 
2652 		/*
2653 		 * If VM_MAP_WIRE_HOLESOK was specified, an empty
2654 		 * space in the unwired region could have been mapped
2655 		 * while the map lock was dropped for faulting in the
2656 		 * pages or draining MAP_ENTRY_IN_TRANSITION.
2657 		 * Moreover, another thread could be simultaneously
2658 		 * wiring this new mapping entry.  Detect these cases
2659 		 * and skip any entries marked as in transition by us.
2660 		 */
2661 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
2662 		    entry->wiring_thread != curthread) {
2663 			KASSERT((flags & VM_MAP_WIRE_HOLESOK) != 0,
2664 			    ("vm_map_wire: !HOLESOK and new/changed entry"));
2665 			continue;
2666 		}
2667 
2668 		if (rv == KERN_SUCCESS) {
2669 			if (user_wire)
2670 				entry->eflags |= MAP_ENTRY_USER_WIRED;
2671 		} else if (entry->wired_count == -1) {
2672 			/*
2673 			 * Wiring failed on this entry.  Thus, unwiring is
2674 			 * unnecessary.
2675 			 */
2676 			entry->wired_count = 0;
2677 		} else if (!user_wire ||
2678 		    (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
2679 			/*
2680 			 * Undo the wiring.  Wiring succeeded on this entry
2681 			 * but failed on a later entry.
2682 			 */
2683 			if (entry->wired_count == 1)
2684 				vm_map_entry_unwire(map, entry);
2685 			else
2686 				entry->wired_count--;
2687 		}
2688 	next_entry_done:
2689 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
2690 		    ("vm_map_wire: in-transition flag missing %p", entry));
2691 		KASSERT(entry->wiring_thread == curthread,
2692 		    ("vm_map_wire: alien wire %p", entry));
2693 		entry->eflags &= ~(MAP_ENTRY_IN_TRANSITION |
2694 		    MAP_ENTRY_WIRE_SKIPPED);
2695 		entry->wiring_thread = NULL;
2696 		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
2697 			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
2698 			need_wakeup = TRUE;
2699 		}
2700 		vm_map_simplify_entry(map, entry);
2701 	}
2702 	vm_map_unlock(map);
2703 	if (need_wakeup)
2704 		vm_map_wakeup(map);
2705 	return (rv);
2706 }
2707 
2708 /*
2709  * vm_map_sync
2710  *
2711  * Push any dirty cached pages in the address range to their pager.
2712  * If syncio is TRUE, dirty pages are written synchronously.
2713  * If invalidate is TRUE, any cached pages are freed as well.
2714  *
2715  * If the size of the region from start to end is zero, we are
2716  * supposed to flush all modified pages within the region containing
2717  * start.  Unfortunately, a region can be split or coalesced with
2718  * neighboring regions, making it difficult to determine what the
2719  * original region was.  Therefore, we approximate this requirement by
2720  * flushing the current region containing start.
2721  *
2722  * Returns an error if any part of the specified range is not mapped.
2723  */
2724 int
2725 vm_map_sync(
2726 	vm_map_t map,
2727 	vm_offset_t start,
2728 	vm_offset_t end,
2729 	boolean_t syncio,
2730 	boolean_t invalidate)
2731 {
2732 	vm_map_entry_t current;
2733 	vm_map_entry_t entry;
2734 	vm_size_t size;
2735 	vm_object_t object;
2736 	vm_ooffset_t offset;
2737 	unsigned int last_timestamp;
2738 	boolean_t failed;
2739 
2740 	vm_map_lock_read(map);
2741 	VM_MAP_RANGE_CHECK(map, start, end);
2742 	if (!vm_map_lookup_entry(map, start, &entry)) {
2743 		vm_map_unlock_read(map);
2744 		return (KERN_INVALID_ADDRESS);
2745 	} else if (start == end) {
2746 		start = entry->start;
2747 		end = entry->end;
2748 	}
2749 	/*
2750 	 * Make a first pass to check for user-wired memory and holes.
2751 	 */
2752 	for (current = entry; current != &map->header && current->start < end;
2753 	    current = current->next) {
2754 		if (invalidate && (current->eflags & MAP_ENTRY_USER_WIRED)) {
2755 			vm_map_unlock_read(map);
2756 			return (KERN_INVALID_ARGUMENT);
2757 		}
2758 		if (end > current->end &&
2759 		    (current->next == &map->header ||
2760 			current->end != current->next->start)) {
2761 			vm_map_unlock_read(map);
2762 			return (KERN_INVALID_ADDRESS);
2763 		}
2764 	}
2765 
2766 	if (invalidate)
2767 		pmap_remove(map->pmap, start, end);
2768 	failed = FALSE;
2769 
2770 	/*
2771 	 * Make a second pass, cleaning/uncaching pages from the indicated
2772 	 * objects as we go.
2773 	 */
2774 	for (current = entry; current != &map->header && current->start < end;) {
2775 		offset = current->offset + (start - current->start);
2776 		size = (end <= current->end ? end : current->end) - start;
2777 		if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
2778 			vm_map_t smap;
2779 			vm_map_entry_t tentry;
2780 			vm_size_t tsize;
2781 
2782 			smap = current->object.sub_map;
2783 			vm_map_lock_read(smap);
2784 			(void) vm_map_lookup_entry(smap, offset, &tentry);
2785 			tsize = tentry->end - offset;
2786 			if (tsize < size)
2787 				size = tsize;
2788 			object = tentry->object.vm_object;
2789 			offset = tentry->offset + (offset - tentry->start);
2790 			vm_map_unlock_read(smap);
2791 		} else {
2792 			object = current->object.vm_object;
2793 		}
2794 		vm_object_reference(object);
2795 		last_timestamp = map->timestamp;
2796 		vm_map_unlock_read(map);
2797 		if (!vm_object_sync(object, offset, size, syncio, invalidate))
2798 			failed = TRUE;
2799 		start += size;
2800 		vm_object_deallocate(object);
2801 		vm_map_lock_read(map);
2802 		if (last_timestamp == map->timestamp ||
2803 		    !vm_map_lookup_entry(map, start, &current))
2804 			current = current->next;
2805 	}
2806 
2807 	vm_map_unlock_read(map);
2808 	return (failed ? KERN_FAILURE : KERN_SUCCESS);
2809 }
2810 
2811 /*
2812  *	vm_map_entry_unwire:	[ internal use only ]
2813  *
2814  *	Make the region specified by this entry pageable.
2815  *
2816  *	The map in question should be locked.
2817  *	[This is the reason for this routine's existence.]
2818  */
2819 static void
2820 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
2821 {
2822 
2823 	VM_MAP_ASSERT_LOCKED(map);
2824 	KASSERT(entry->wired_count > 0,
2825 	    ("vm_map_entry_unwire: entry %p isn't wired", entry));
2826 	pmap_unwire(map->pmap, entry->start, entry->end);
2827 	vm_object_unwire(entry->object.vm_object, entry->offset, entry->end -
2828 	    entry->start, PQ_ACTIVE);
2829 	entry->wired_count = 0;
2830 }
2831 
2832 static void
2833 vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map)
2834 {
2835 
2836 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0)
2837 		vm_object_deallocate(entry->object.vm_object);
2838 	uma_zfree(system_map ? kmapentzone : mapentzone, entry);
2839 }
2840 
2841 /*
2842  *	vm_map_entry_delete:	[ internal use only ]
2843  *
2844  *	Deallocate the given entry from the target map.
2845  */
2846 static void
2847 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry)
2848 {
2849 	vm_object_t object;
2850 	vm_pindex_t offidxstart, offidxend, count, size1;
2851 	vm_ooffset_t size;
2852 
2853 	vm_map_entry_unlink(map, entry);
2854 	object = entry->object.vm_object;
2855 	size = entry->end - entry->start;
2856 	map->size -= size;
2857 
2858 	if (entry->cred != NULL) {
2859 		swap_release_by_cred(size, entry->cred);
2860 		crfree(entry->cred);
2861 	}
2862 
2863 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0 &&
2864 	    (object != NULL)) {
2865 		KASSERT(entry->cred == NULL || object->cred == NULL ||
2866 		    (entry->eflags & MAP_ENTRY_NEEDS_COPY),
2867 		    ("OVERCOMMIT vm_map_entry_delete: both cred %p", entry));
2868 		count = OFF_TO_IDX(size);
2869 		offidxstart = OFF_TO_IDX(entry->offset);
2870 		offidxend = offidxstart + count;
2871 		VM_OBJECT_WLOCK(object);
2872 		if (object->ref_count != 1 &&
2873 		    ((object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING ||
2874 		    object == kernel_object || object == kmem_object)) {
2875 			vm_object_collapse(object);
2876 
2877 			/*
2878 			 * The option OBJPR_NOTMAPPED can be passed here
2879 			 * because vm_map_delete() already performed
2880 			 * pmap_remove() on the only mapping to this range
2881 			 * of pages.
2882 			 */
2883 			vm_object_page_remove(object, offidxstart, offidxend,
2884 			    OBJPR_NOTMAPPED);
2885 			if (object->type == OBJT_SWAP)
2886 				swap_pager_freespace(object, offidxstart, count);
2887 			if (offidxend >= object->size &&
2888 			    offidxstart < object->size) {
2889 				size1 = object->size;
2890 				object->size = offidxstart;
2891 				if (object->cred != NULL) {
2892 					size1 -= object->size;
2893 					KASSERT(object->charge >= ptoa(size1),
2894 					    ("vm_map_entry_delete: object->charge < 0"));
2895 					swap_release_by_cred(ptoa(size1), object->cred);
2896 					object->charge -= ptoa(size1);
2897 				}
2898 			}
2899 		}
2900 		VM_OBJECT_WUNLOCK(object);
2901 	} else
2902 		entry->object.vm_object = NULL;
2903 	if (map->system_map)
2904 		vm_map_entry_deallocate(entry, TRUE);
2905 	else {
2906 		entry->next = curthread->td_map_def_user;
2907 		curthread->td_map_def_user = entry;
2908 	}
2909 }
2910 
2911 /*
2912  *	vm_map_delete:	[ internal use only ]
2913  *
2914  *	Deallocates the given address range from the target
2915  *	map.
2916  */
2917 int
2918 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
2919 {
2920 	vm_map_entry_t entry;
2921 	vm_map_entry_t first_entry;
2922 
2923 	VM_MAP_ASSERT_LOCKED(map);
2924 	if (start == end)
2925 		return (KERN_SUCCESS);
2926 
2927 	/*
2928 	 * Find the start of the region, and clip it
2929 	 */
2930 	if (!vm_map_lookup_entry(map, start, &first_entry))
2931 		entry = first_entry->next;
2932 	else {
2933 		entry = first_entry;
2934 		vm_map_clip_start(map, entry, start);
2935 	}
2936 
2937 	/*
2938 	 * Step through all entries in this region
2939 	 */
2940 	while ((entry != &map->header) && (entry->start < end)) {
2941 		vm_map_entry_t next;
2942 
2943 		/*
2944 		 * Wait for wiring or unwiring of an entry to complete.
2945 		 * Also wait for any system wirings to disappear on
2946 		 * user maps.
2947 		 */
2948 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 ||
2949 		    (vm_map_pmap(map) != kernel_pmap &&
2950 		    vm_map_entry_system_wired_count(entry) != 0)) {
2951 			unsigned int last_timestamp;
2952 			vm_offset_t saved_start;
2953 			vm_map_entry_t tmp_entry;
2954 
2955 			saved_start = entry->start;
2956 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2957 			last_timestamp = map->timestamp;
2958 			(void) vm_map_unlock_and_wait(map, 0);
2959 			vm_map_lock(map);
2960 			if (last_timestamp + 1 != map->timestamp) {
2961 				/*
2962 				 * Look again for the entry because the map was
2963 				 * modified while it was unlocked.
2964 				 * Specifically, the entry may have been
2965 				 * clipped, merged, or deleted.
2966 				 */
2967 				if (!vm_map_lookup_entry(map, saved_start,
2968 							 &tmp_entry))
2969 					entry = tmp_entry->next;
2970 				else {
2971 					entry = tmp_entry;
2972 					vm_map_clip_start(map, entry,
2973 							  saved_start);
2974 				}
2975 			}
2976 			continue;
2977 		}
2978 		vm_map_clip_end(map, entry, end);
2979 
2980 		next = entry->next;
2981 
2982 		/*
2983 		 * Unwire before removing addresses from the pmap; otherwise,
2984 		 * unwiring will put the entries back in the pmap.
2985 		 */
2986 		if (entry->wired_count != 0) {
2987 			vm_map_entry_unwire(map, entry);
2988 		}
2989 
2990 		pmap_remove(map->pmap, entry->start, entry->end);
2991 
2992 		/*
2993 		 * Delete the entry only after removing all pmap
2994 		 * entries pointing to its pages.  (Otherwise, its
2995 		 * page frames may be reallocated, and any modify bits
2996 		 * will be set in the wrong object!)
2997 		 */
2998 		vm_map_entry_delete(map, entry);
2999 		entry = next;
3000 	}
3001 	return (KERN_SUCCESS);
3002 }
3003 
3004 /*
3005  *	vm_map_remove:
3006  *
3007  *	Remove the given address range from the target map.
3008  *	This is the exported form of vm_map_delete.
3009  */
3010 int
3011 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
3012 {
3013 	int result;
3014 
3015 	vm_map_lock(map);
3016 	VM_MAP_RANGE_CHECK(map, start, end);
3017 	result = vm_map_delete(map, start, end);
3018 	vm_map_unlock(map);
3019 	return (result);
3020 }
3021 
3022 /*
3023  *	vm_map_check_protection:
3024  *
3025  *	Assert that the target map allows the specified privilege on the
3026  *	entire address region given.  The entire region must be allocated.
3027  *
3028  *	WARNING!  This code does not and should not check whether the
3029  *	contents of the region is accessible.  For example a smaller file
3030  *	might be mapped into a larger address space.
3031  *
3032  *	NOTE!  This code is also called by munmap().
3033  *
3034  *	The map must be locked.  A read lock is sufficient.
3035  */
3036 boolean_t
3037 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
3038 			vm_prot_t protection)
3039 {
3040 	vm_map_entry_t entry;
3041 	vm_map_entry_t tmp_entry;
3042 
3043 	if (!vm_map_lookup_entry(map, start, &tmp_entry))
3044 		return (FALSE);
3045 	entry = tmp_entry;
3046 
3047 	while (start < end) {
3048 		if (entry == &map->header)
3049 			return (FALSE);
3050 		/*
3051 		 * No holes allowed!
3052 		 */
3053 		if (start < entry->start)
3054 			return (FALSE);
3055 		/*
3056 		 * Check protection associated with entry.
3057 		 */
3058 		if ((entry->protection & protection) != protection)
3059 			return (FALSE);
3060 		/* go to next entry */
3061 		start = entry->end;
3062 		entry = entry->next;
3063 	}
3064 	return (TRUE);
3065 }
3066 
3067 /*
3068  *	vm_map_copy_entry:
3069  *
3070  *	Copies the contents of the source entry to the destination
3071  *	entry.  The entries *must* be aligned properly.
3072  */
3073 static void
3074 vm_map_copy_entry(
3075 	vm_map_t src_map,
3076 	vm_map_t dst_map,
3077 	vm_map_entry_t src_entry,
3078 	vm_map_entry_t dst_entry,
3079 	vm_ooffset_t *fork_charge)
3080 {
3081 	vm_object_t src_object;
3082 	vm_map_entry_t fake_entry;
3083 	vm_offset_t size;
3084 	struct ucred *cred;
3085 	int charged;
3086 
3087 	VM_MAP_ASSERT_LOCKED(dst_map);
3088 
3089 	if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
3090 		return;
3091 
3092 	if (src_entry->wired_count == 0 ||
3093 	    (src_entry->protection & VM_PROT_WRITE) == 0) {
3094 		/*
3095 		 * If the source entry is marked needs_copy, it is already
3096 		 * write-protected.
3097 		 */
3098 		if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0 &&
3099 		    (src_entry->protection & VM_PROT_WRITE) != 0) {
3100 			pmap_protect(src_map->pmap,
3101 			    src_entry->start,
3102 			    src_entry->end,
3103 			    src_entry->protection & ~VM_PROT_WRITE);
3104 		}
3105 
3106 		/*
3107 		 * Make a copy of the object.
3108 		 */
3109 		size = src_entry->end - src_entry->start;
3110 		if ((src_object = src_entry->object.vm_object) != NULL) {
3111 			VM_OBJECT_WLOCK(src_object);
3112 			charged = ENTRY_CHARGED(src_entry);
3113 			if ((src_object->handle == NULL) &&
3114 				(src_object->type == OBJT_DEFAULT ||
3115 				 src_object->type == OBJT_SWAP)) {
3116 				vm_object_collapse(src_object);
3117 				if ((src_object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING) {
3118 					vm_object_split(src_entry);
3119 					src_object = src_entry->object.vm_object;
3120 				}
3121 			}
3122 			vm_object_reference_locked(src_object);
3123 			vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
3124 			if (src_entry->cred != NULL &&
3125 			    !(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
3126 				KASSERT(src_object->cred == NULL,
3127 				    ("OVERCOMMIT: vm_map_copy_entry: cred %p",
3128 				     src_object));
3129 				src_object->cred = src_entry->cred;
3130 				src_object->charge = size;
3131 			}
3132 			VM_OBJECT_WUNLOCK(src_object);
3133 			dst_entry->object.vm_object = src_object;
3134 			if (charged) {
3135 				cred = curthread->td_ucred;
3136 				crhold(cred);
3137 				dst_entry->cred = cred;
3138 				*fork_charge += size;
3139 				if (!(src_entry->eflags &
3140 				      MAP_ENTRY_NEEDS_COPY)) {
3141 					crhold(cred);
3142 					src_entry->cred = cred;
3143 					*fork_charge += size;
3144 				}
3145 			}
3146 			src_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
3147 			dst_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
3148 			dst_entry->offset = src_entry->offset;
3149 			if (src_entry->eflags & MAP_ENTRY_VN_WRITECNT) {
3150 				/*
3151 				 * MAP_ENTRY_VN_WRITECNT cannot
3152 				 * indicate write reference from
3153 				 * src_entry, since the entry is
3154 				 * marked as needs copy.  Allocate a
3155 				 * fake entry that is used to
3156 				 * decrement object->un_pager.vnp.writecount
3157 				 * at the appropriate time.  Attach
3158 				 * fake_entry to the deferred list.
3159 				 */
3160 				fake_entry = vm_map_entry_create(dst_map);
3161 				fake_entry->eflags = MAP_ENTRY_VN_WRITECNT;
3162 				src_entry->eflags &= ~MAP_ENTRY_VN_WRITECNT;
3163 				vm_object_reference(src_object);
3164 				fake_entry->object.vm_object = src_object;
3165 				fake_entry->start = src_entry->start;
3166 				fake_entry->end = src_entry->end;
3167 				fake_entry->next = curthread->td_map_def_user;
3168 				curthread->td_map_def_user = fake_entry;
3169 			}
3170 		} else {
3171 			dst_entry->object.vm_object = NULL;
3172 			dst_entry->offset = 0;
3173 			if (src_entry->cred != NULL) {
3174 				dst_entry->cred = curthread->td_ucred;
3175 				crhold(dst_entry->cred);
3176 				*fork_charge += size;
3177 			}
3178 		}
3179 
3180 		pmap_copy(dst_map->pmap, src_map->pmap, dst_entry->start,
3181 		    dst_entry->end - dst_entry->start, src_entry->start);
3182 	} else {
3183 		/*
3184 		 * We don't want to make writeable wired pages copy-on-write.
3185 		 * Immediately copy these pages into the new map by simulating
3186 		 * page faults.  The new pages are pageable.
3187 		 */
3188 		vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry,
3189 		    fork_charge);
3190 	}
3191 }
3192 
3193 /*
3194  * vmspace_map_entry_forked:
3195  * Update the newly-forked vmspace each time a map entry is inherited
3196  * or copied.  The values for vm_dsize and vm_tsize are approximate
3197  * (and mostly-obsolete ideas in the face of mmap(2) et al.)
3198  */
3199 static void
3200 vmspace_map_entry_forked(const struct vmspace *vm1, struct vmspace *vm2,
3201     vm_map_entry_t entry)
3202 {
3203 	vm_size_t entrysize;
3204 	vm_offset_t newend;
3205 
3206 	entrysize = entry->end - entry->start;
3207 	vm2->vm_map.size += entrysize;
3208 	if (entry->eflags & (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP)) {
3209 		vm2->vm_ssize += btoc(entrysize);
3210 	} else if (entry->start >= (vm_offset_t)vm1->vm_daddr &&
3211 	    entry->start < (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize)) {
3212 		newend = MIN(entry->end,
3213 		    (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize));
3214 		vm2->vm_dsize += btoc(newend - entry->start);
3215 	} else if (entry->start >= (vm_offset_t)vm1->vm_taddr &&
3216 	    entry->start < (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize)) {
3217 		newend = MIN(entry->end,
3218 		    (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize));
3219 		vm2->vm_tsize += btoc(newend - entry->start);
3220 	}
3221 }
3222 
3223 /*
3224  * vmspace_fork:
3225  * Create a new process vmspace structure and vm_map
3226  * based on those of an existing process.  The new map
3227  * is based on the old map, according to the inheritance
3228  * values on the regions in that map.
3229  *
3230  * XXX It might be worth coalescing the entries added to the new vmspace.
3231  *
3232  * The source map must not be locked.
3233  */
3234 struct vmspace *
3235 vmspace_fork(struct vmspace *vm1, vm_ooffset_t *fork_charge)
3236 {
3237 	struct vmspace *vm2;
3238 	vm_map_t new_map, old_map;
3239 	vm_map_entry_t new_entry, old_entry;
3240 	vm_object_t object;
3241 	int locked;
3242 
3243 	old_map = &vm1->vm_map;
3244 	/* Copy immutable fields of vm1 to vm2. */
3245 	vm2 = vmspace_alloc(old_map->min_offset, old_map->max_offset, NULL);
3246 	if (vm2 == NULL)
3247 		return (NULL);
3248 	vm2->vm_taddr = vm1->vm_taddr;
3249 	vm2->vm_daddr = vm1->vm_daddr;
3250 	vm2->vm_maxsaddr = vm1->vm_maxsaddr;
3251 	vm_map_lock(old_map);
3252 	if (old_map->busy)
3253 		vm_map_wait_busy(old_map);
3254 	new_map = &vm2->vm_map;
3255 	locked = vm_map_trylock(new_map); /* trylock to silence WITNESS */
3256 	KASSERT(locked, ("vmspace_fork: lock failed"));
3257 
3258 	old_entry = old_map->header.next;
3259 
3260 	while (old_entry != &old_map->header) {
3261 		if (old_entry->eflags & MAP_ENTRY_IS_SUB_MAP)
3262 			panic("vm_map_fork: encountered a submap");
3263 
3264 		switch (old_entry->inheritance) {
3265 		case VM_INHERIT_NONE:
3266 			break;
3267 
3268 		case VM_INHERIT_SHARE:
3269 			/*
3270 			 * Clone the entry, creating the shared object if necessary.
3271 			 */
3272 			object = old_entry->object.vm_object;
3273 			if (object == NULL) {
3274 				object = vm_object_allocate(OBJT_DEFAULT,
3275 					atop(old_entry->end - old_entry->start));
3276 				old_entry->object.vm_object = object;
3277 				old_entry->offset = 0;
3278 				if (old_entry->cred != NULL) {
3279 					object->cred = old_entry->cred;
3280 					object->charge = old_entry->end -
3281 					    old_entry->start;
3282 					old_entry->cred = NULL;
3283 				}
3284 			}
3285 
3286 			/*
3287 			 * Add the reference before calling vm_object_shadow
3288 			 * to insure that a shadow object is created.
3289 			 */
3290 			vm_object_reference(object);
3291 			if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3292 				vm_object_shadow(&old_entry->object.vm_object,
3293 				    &old_entry->offset,
3294 				    old_entry->end - old_entry->start);
3295 				old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
3296 				/* Transfer the second reference too. */
3297 				vm_object_reference(
3298 				    old_entry->object.vm_object);
3299 
3300 				/*
3301 				 * As in vm_map_simplify_entry(), the
3302 				 * vnode lock will not be acquired in
3303 				 * this call to vm_object_deallocate().
3304 				 */
3305 				vm_object_deallocate(object);
3306 				object = old_entry->object.vm_object;
3307 			}
3308 			VM_OBJECT_WLOCK(object);
3309 			vm_object_clear_flag(object, OBJ_ONEMAPPING);
3310 			if (old_entry->cred != NULL) {
3311 				KASSERT(object->cred == NULL, ("vmspace_fork both cred"));
3312 				object->cred = old_entry->cred;
3313 				object->charge = old_entry->end - old_entry->start;
3314 				old_entry->cred = NULL;
3315 			}
3316 
3317 			/*
3318 			 * Assert the correct state of the vnode
3319 			 * v_writecount while the object is locked, to
3320 			 * not relock it later for the assertion
3321 			 * correctness.
3322 			 */
3323 			if (old_entry->eflags & MAP_ENTRY_VN_WRITECNT &&
3324 			    object->type == OBJT_VNODE) {
3325 				KASSERT(((struct vnode *)object->handle)->
3326 				    v_writecount > 0,
3327 				    ("vmspace_fork: v_writecount %p", object));
3328 				KASSERT(object->un_pager.vnp.writemappings > 0,
3329 				    ("vmspace_fork: vnp.writecount %p",
3330 				    object));
3331 			}
3332 			VM_OBJECT_WUNLOCK(object);
3333 
3334 			/*
3335 			 * Clone the entry, referencing the shared object.
3336 			 */
3337 			new_entry = vm_map_entry_create(new_map);
3338 			*new_entry = *old_entry;
3339 			new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
3340 			    MAP_ENTRY_IN_TRANSITION);
3341 			new_entry->wiring_thread = NULL;
3342 			new_entry->wired_count = 0;
3343 			if (new_entry->eflags & MAP_ENTRY_VN_WRITECNT) {
3344 				vnode_pager_update_writecount(object,
3345 				    new_entry->start, new_entry->end);
3346 			}
3347 
3348 			/*
3349 			 * Insert the entry into the new map -- we know we're
3350 			 * inserting at the end of the new map.
3351 			 */
3352 			vm_map_entry_link(new_map, new_map->header.prev,
3353 			    new_entry);
3354 			vmspace_map_entry_forked(vm1, vm2, new_entry);
3355 
3356 			/*
3357 			 * Update the physical map
3358 			 */
3359 			pmap_copy(new_map->pmap, old_map->pmap,
3360 			    new_entry->start,
3361 			    (old_entry->end - old_entry->start),
3362 			    old_entry->start);
3363 			break;
3364 
3365 		case VM_INHERIT_COPY:
3366 			/*
3367 			 * Clone the entry and link into the map.
3368 			 */
3369 			new_entry = vm_map_entry_create(new_map);
3370 			*new_entry = *old_entry;
3371 			/*
3372 			 * Copied entry is COW over the old object.
3373 			 */
3374 			new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
3375 			    MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_VN_WRITECNT);
3376 			new_entry->wiring_thread = NULL;
3377 			new_entry->wired_count = 0;
3378 			new_entry->object.vm_object = NULL;
3379 			new_entry->cred = NULL;
3380 			vm_map_entry_link(new_map, new_map->header.prev,
3381 			    new_entry);
3382 			vmspace_map_entry_forked(vm1, vm2, new_entry);
3383 			vm_map_copy_entry(old_map, new_map, old_entry,
3384 			    new_entry, fork_charge);
3385 			break;
3386 		}
3387 		old_entry = old_entry->next;
3388 	}
3389 	/*
3390 	 * Use inlined vm_map_unlock() to postpone handling the deferred
3391 	 * map entries, which cannot be done until both old_map and
3392 	 * new_map locks are released.
3393 	 */
3394 	sx_xunlock(&old_map->lock);
3395 	sx_xunlock(&new_map->lock);
3396 	vm_map_process_deferred();
3397 
3398 	return (vm2);
3399 }
3400 
3401 int
3402 vm_map_stack(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
3403     vm_prot_t prot, vm_prot_t max, int cow)
3404 {
3405 	vm_size_t growsize, init_ssize;
3406 	rlim_t lmemlim, vmemlim;
3407 	int rv;
3408 
3409 	growsize = sgrowsiz;
3410 	init_ssize = (max_ssize < growsize) ? max_ssize : growsize;
3411 	vm_map_lock(map);
3412 	PROC_LOCK(curproc);
3413 	lmemlim = lim_cur(curproc, RLIMIT_MEMLOCK);
3414 	vmemlim = lim_cur(curproc, RLIMIT_VMEM);
3415 	PROC_UNLOCK(curproc);
3416 	if (!old_mlock && map->flags & MAP_WIREFUTURE) {
3417 		if (ptoa(pmap_wired_count(map->pmap)) + init_ssize > lmemlim) {
3418 			rv = KERN_NO_SPACE;
3419 			goto out;
3420 		}
3421 	}
3422 	/* If we would blow our VMEM resource limit, no go */
3423 	if (map->size + init_ssize > vmemlim) {
3424 		rv = KERN_NO_SPACE;
3425 		goto out;
3426 	}
3427 	rv = vm_map_stack_locked(map, addrbos, max_ssize, growsize, prot,
3428 	    max, cow);
3429 out:
3430 	vm_map_unlock(map);
3431 	return (rv);
3432 }
3433 
3434 static int
3435 vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
3436     vm_size_t growsize, vm_prot_t prot, vm_prot_t max, int cow)
3437 {
3438 	vm_map_entry_t new_entry, prev_entry;
3439 	vm_offset_t bot, top;
3440 	vm_size_t init_ssize;
3441 	int orient, rv;
3442 
3443 	/*
3444 	 * The stack orientation is piggybacked with the cow argument.
3445 	 * Extract it into orient and mask the cow argument so that we
3446 	 * don't pass it around further.
3447 	 * NOTE: We explicitly allow bi-directional stacks.
3448 	 */
3449 	orient = cow & (MAP_STACK_GROWS_DOWN|MAP_STACK_GROWS_UP);
3450 	KASSERT(orient != 0, ("No stack grow direction"));
3451 
3452 	if (addrbos < vm_map_min(map) ||
3453 	    addrbos > vm_map_max(map) ||
3454 	    addrbos + max_ssize < addrbos)
3455 		return (KERN_NO_SPACE);
3456 
3457 	init_ssize = (max_ssize < growsize) ? max_ssize : growsize;
3458 
3459 	/* If addr is already mapped, no go */
3460 	if (vm_map_lookup_entry(map, addrbos, &prev_entry))
3461 		return (KERN_NO_SPACE);
3462 
3463 	/*
3464 	 * If we can't accomodate max_ssize in the current mapping, no go.
3465 	 * However, we need to be aware that subsequent user mappings might
3466 	 * map into the space we have reserved for stack, and currently this
3467 	 * space is not protected.
3468 	 *
3469 	 * Hopefully we will at least detect this condition when we try to
3470 	 * grow the stack.
3471 	 */
3472 	if ((prev_entry->next != &map->header) &&
3473 	    (prev_entry->next->start < addrbos + max_ssize))
3474 		return (KERN_NO_SPACE);
3475 
3476 	/*
3477 	 * We initially map a stack of only init_ssize.  We will grow as
3478 	 * needed later.  Depending on the orientation of the stack (i.e.
3479 	 * the grow direction) we either map at the top of the range, the
3480 	 * bottom of the range or in the middle.
3481 	 *
3482 	 * Note: we would normally expect prot and max to be VM_PROT_ALL,
3483 	 * and cow to be 0.  Possibly we should eliminate these as input
3484 	 * parameters, and just pass these values here in the insert call.
3485 	 */
3486 	if (orient == MAP_STACK_GROWS_DOWN)
3487 		bot = addrbos + max_ssize - init_ssize;
3488 	else if (orient == MAP_STACK_GROWS_UP)
3489 		bot = addrbos;
3490 	else
3491 		bot = round_page(addrbos + max_ssize/2 - init_ssize/2);
3492 	top = bot + init_ssize;
3493 	rv = vm_map_insert(map, NULL, 0, bot, top, prot, max, cow);
3494 
3495 	/* Now set the avail_ssize amount. */
3496 	if (rv == KERN_SUCCESS) {
3497 		new_entry = prev_entry->next;
3498 		if (new_entry->end != top || new_entry->start != bot)
3499 			panic("Bad entry start/end for new stack entry");
3500 
3501 		new_entry->avail_ssize = max_ssize - init_ssize;
3502 		KASSERT((orient & MAP_STACK_GROWS_DOWN) == 0 ||
3503 		    (new_entry->eflags & MAP_ENTRY_GROWS_DOWN) != 0,
3504 		    ("new entry lacks MAP_ENTRY_GROWS_DOWN"));
3505 		KASSERT((orient & MAP_STACK_GROWS_UP) == 0 ||
3506 		    (new_entry->eflags & MAP_ENTRY_GROWS_UP) != 0,
3507 		    ("new entry lacks MAP_ENTRY_GROWS_UP"));
3508 	}
3509 
3510 	return (rv);
3511 }
3512 
3513 static int stack_guard_page = 0;
3514 SYSCTL_INT(_security_bsd, OID_AUTO, stack_guard_page, CTLFLAG_RWTUN,
3515     &stack_guard_page, 0,
3516     "Insert stack guard page ahead of the growable segments.");
3517 
3518 /* Attempts to grow a vm stack entry.  Returns KERN_SUCCESS if the
3519  * desired address is already mapped, or if we successfully grow
3520  * the stack.  Also returns KERN_SUCCESS if addr is outside the
3521  * stack range (this is strange, but preserves compatibility with
3522  * the grow function in vm_machdep.c).
3523  */
3524 int
3525 vm_map_growstack(struct proc *p, vm_offset_t addr)
3526 {
3527 	vm_map_entry_t next_entry, prev_entry;
3528 	vm_map_entry_t new_entry, stack_entry;
3529 	struct vmspace *vm = p->p_vmspace;
3530 	vm_map_t map = &vm->vm_map;
3531 	vm_offset_t end;
3532 	vm_size_t growsize;
3533 	size_t grow_amount, max_grow;
3534 	rlim_t lmemlim, stacklim, vmemlim;
3535 	int is_procstack, rv;
3536 	struct ucred *cred;
3537 #ifdef notyet
3538 	uint64_t limit;
3539 #endif
3540 #ifdef RACCT
3541 	int error;
3542 #endif
3543 
3544 Retry:
3545 	PROC_LOCK(p);
3546 	lmemlim = lim_cur(p, RLIMIT_MEMLOCK);
3547 	stacklim = lim_cur(p, RLIMIT_STACK);
3548 	vmemlim = lim_cur(p, RLIMIT_VMEM);
3549 	PROC_UNLOCK(p);
3550 
3551 	vm_map_lock_read(map);
3552 
3553 	/* If addr is already in the entry range, no need to grow.*/
3554 	if (vm_map_lookup_entry(map, addr, &prev_entry)) {
3555 		vm_map_unlock_read(map);
3556 		return (KERN_SUCCESS);
3557 	}
3558 
3559 	next_entry = prev_entry->next;
3560 	if (!(prev_entry->eflags & MAP_ENTRY_GROWS_UP)) {
3561 		/*
3562 		 * This entry does not grow upwards. Since the address lies
3563 		 * beyond this entry, the next entry (if one exists) has to
3564 		 * be a downward growable entry. The entry list header is
3565 		 * never a growable entry, so it suffices to check the flags.
3566 		 */
3567 		if (!(next_entry->eflags & MAP_ENTRY_GROWS_DOWN)) {
3568 			vm_map_unlock_read(map);
3569 			return (KERN_SUCCESS);
3570 		}
3571 		stack_entry = next_entry;
3572 	} else {
3573 		/*
3574 		 * This entry grows upward. If the next entry does not at
3575 		 * least grow downwards, this is the entry we need to grow.
3576 		 * otherwise we have two possible choices and we have to
3577 		 * select one.
3578 		 */
3579 		if (next_entry->eflags & MAP_ENTRY_GROWS_DOWN) {
3580 			/*
3581 			 * We have two choices; grow the entry closest to
3582 			 * the address to minimize the amount of growth.
3583 			 */
3584 			if (addr - prev_entry->end <= next_entry->start - addr)
3585 				stack_entry = prev_entry;
3586 			else
3587 				stack_entry = next_entry;
3588 		} else
3589 			stack_entry = prev_entry;
3590 	}
3591 
3592 	if (stack_entry == next_entry) {
3593 		KASSERT(stack_entry->eflags & MAP_ENTRY_GROWS_DOWN, ("foo"));
3594 		KASSERT(addr < stack_entry->start, ("foo"));
3595 		end = (prev_entry != &map->header) ? prev_entry->end :
3596 		    stack_entry->start - stack_entry->avail_ssize;
3597 		grow_amount = roundup(stack_entry->start - addr, PAGE_SIZE);
3598 		max_grow = stack_entry->start - end;
3599 	} else {
3600 		KASSERT(stack_entry->eflags & MAP_ENTRY_GROWS_UP, ("foo"));
3601 		KASSERT(addr >= stack_entry->end, ("foo"));
3602 		end = (next_entry != &map->header) ? next_entry->start :
3603 		    stack_entry->end + stack_entry->avail_ssize;
3604 		grow_amount = roundup(addr + 1 - stack_entry->end, PAGE_SIZE);
3605 		max_grow = end - stack_entry->end;
3606 	}
3607 
3608 	if (grow_amount > stack_entry->avail_ssize) {
3609 		vm_map_unlock_read(map);
3610 		return (KERN_NO_SPACE);
3611 	}
3612 
3613 	/*
3614 	 * If there is no longer enough space between the entries nogo, and
3615 	 * adjust the available space.  Note: this  should only happen if the
3616 	 * user has mapped into the stack area after the stack was created,
3617 	 * and is probably an error.
3618 	 *
3619 	 * This also effectively destroys any guard page the user might have
3620 	 * intended by limiting the stack size.
3621 	 */
3622 	if (grow_amount + (stack_guard_page ? PAGE_SIZE : 0) > max_grow) {
3623 		if (vm_map_lock_upgrade(map))
3624 			goto Retry;
3625 
3626 		stack_entry->avail_ssize = max_grow;
3627 
3628 		vm_map_unlock(map);
3629 		return (KERN_NO_SPACE);
3630 	}
3631 
3632 	is_procstack = (addr >= (vm_offset_t)vm->vm_maxsaddr) ? 1 : 0;
3633 
3634 	/*
3635 	 * If this is the main process stack, see if we're over the stack
3636 	 * limit.
3637 	 */
3638 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
3639 		vm_map_unlock_read(map);
3640 		return (KERN_NO_SPACE);
3641 	}
3642 #ifdef RACCT
3643 	PROC_LOCK(p);
3644 	if (is_procstack &&
3645 	    racct_set(p, RACCT_STACK, ctob(vm->vm_ssize) + grow_amount)) {
3646 		PROC_UNLOCK(p);
3647 		vm_map_unlock_read(map);
3648 		return (KERN_NO_SPACE);
3649 	}
3650 	PROC_UNLOCK(p);
3651 #endif
3652 
3653 	/* Round up the grow amount modulo sgrowsiz */
3654 	growsize = sgrowsiz;
3655 	grow_amount = roundup(grow_amount, growsize);
3656 	if (grow_amount > stack_entry->avail_ssize)
3657 		grow_amount = stack_entry->avail_ssize;
3658 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
3659 		grow_amount = trunc_page((vm_size_t)stacklim) -
3660 		    ctob(vm->vm_ssize);
3661 	}
3662 #ifdef notyet
3663 	PROC_LOCK(p);
3664 	limit = racct_get_available(p, RACCT_STACK);
3665 	PROC_UNLOCK(p);
3666 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > limit))
3667 		grow_amount = limit - ctob(vm->vm_ssize);
3668 #endif
3669 	if (!old_mlock && map->flags & MAP_WIREFUTURE) {
3670 		if (ptoa(pmap_wired_count(map->pmap)) + grow_amount > lmemlim) {
3671 			vm_map_unlock_read(map);
3672 			rv = KERN_NO_SPACE;
3673 			goto out;
3674 		}
3675 #ifdef RACCT
3676 		PROC_LOCK(p);
3677 		if (racct_set(p, RACCT_MEMLOCK,
3678 		    ptoa(pmap_wired_count(map->pmap)) + grow_amount)) {
3679 			PROC_UNLOCK(p);
3680 			vm_map_unlock_read(map);
3681 			rv = KERN_NO_SPACE;
3682 			goto out;
3683 		}
3684 		PROC_UNLOCK(p);
3685 #endif
3686 	}
3687 	/* If we would blow our VMEM resource limit, no go */
3688 	if (map->size + grow_amount > vmemlim) {
3689 		vm_map_unlock_read(map);
3690 		rv = KERN_NO_SPACE;
3691 		goto out;
3692 	}
3693 #ifdef RACCT
3694 	PROC_LOCK(p);
3695 	if (racct_set(p, RACCT_VMEM, map->size + grow_amount)) {
3696 		PROC_UNLOCK(p);
3697 		vm_map_unlock_read(map);
3698 		rv = KERN_NO_SPACE;
3699 		goto out;
3700 	}
3701 	PROC_UNLOCK(p);
3702 #endif
3703 
3704 	if (vm_map_lock_upgrade(map))
3705 		goto Retry;
3706 
3707 	if (stack_entry == next_entry) {
3708 		/*
3709 		 * Growing downward.
3710 		 */
3711 		/* Get the preliminary new entry start value */
3712 		addr = stack_entry->start - grow_amount;
3713 
3714 		/*
3715 		 * If this puts us into the previous entry, cut back our
3716 		 * growth to the available space. Also, see the note above.
3717 		 */
3718 		if (addr < end) {
3719 			stack_entry->avail_ssize = max_grow;
3720 			addr = end;
3721 			if (stack_guard_page)
3722 				addr += PAGE_SIZE;
3723 		}
3724 
3725 		rv = vm_map_insert(map, NULL, 0, addr, stack_entry->start,
3726 		    next_entry->protection, next_entry->max_protection,
3727 		    MAP_STACK_GROWS_DOWN);
3728 
3729 		/* Adjust the available stack space by the amount we grew. */
3730 		if (rv == KERN_SUCCESS) {
3731 			new_entry = prev_entry->next;
3732 			KASSERT(new_entry == stack_entry->prev, ("foo"));
3733 			KASSERT(new_entry->end == stack_entry->start, ("foo"));
3734 			KASSERT(new_entry->start == addr, ("foo"));
3735 			KASSERT((new_entry->eflags & MAP_ENTRY_GROWS_DOWN) !=
3736 			    0, ("new entry lacks MAP_ENTRY_GROWS_DOWN"));
3737 			grow_amount = new_entry->end - new_entry->start;
3738 			new_entry->avail_ssize = stack_entry->avail_ssize -
3739 			    grow_amount;
3740 			stack_entry->eflags &= ~MAP_ENTRY_GROWS_DOWN;
3741 		}
3742 	} else {
3743 		/*
3744 		 * Growing upward.
3745 		 */
3746 		addr = stack_entry->end + grow_amount;
3747 
3748 		/*
3749 		 * If this puts us into the next entry, cut back our growth
3750 		 * to the available space. Also, see the note above.
3751 		 */
3752 		if (addr > end) {
3753 			stack_entry->avail_ssize = end - stack_entry->end;
3754 			addr = end;
3755 			if (stack_guard_page)
3756 				addr -= PAGE_SIZE;
3757 		}
3758 
3759 		grow_amount = addr - stack_entry->end;
3760 		cred = stack_entry->cred;
3761 		if (cred == NULL && stack_entry->object.vm_object != NULL)
3762 			cred = stack_entry->object.vm_object->cred;
3763 		if (cred != NULL && !swap_reserve_by_cred(grow_amount, cred))
3764 			rv = KERN_NO_SPACE;
3765 		/* Grow the underlying object if applicable. */
3766 		else if (stack_entry->object.vm_object == NULL ||
3767 			 vm_object_coalesce(stack_entry->object.vm_object,
3768 			 stack_entry->offset,
3769 			 (vm_size_t)(stack_entry->end - stack_entry->start),
3770 			 (vm_size_t)grow_amount, cred != NULL)) {
3771 			map->size += (addr - stack_entry->end);
3772 			/* Update the current entry. */
3773 			stack_entry->end = addr;
3774 			stack_entry->avail_ssize -= grow_amount;
3775 			vm_map_entry_resize_free(map, stack_entry);
3776 			rv = KERN_SUCCESS;
3777 		} else
3778 			rv = KERN_FAILURE;
3779 	}
3780 
3781 	if (rv == KERN_SUCCESS && is_procstack)
3782 		vm->vm_ssize += btoc(grow_amount);
3783 
3784 	vm_map_unlock(map);
3785 
3786 	/*
3787 	 * Heed the MAP_WIREFUTURE flag if it was set for this process.
3788 	 */
3789 	if (rv == KERN_SUCCESS && (map->flags & MAP_WIREFUTURE)) {
3790 		vm_map_wire(map,
3791 		    (stack_entry == next_entry) ? addr : addr - grow_amount,
3792 		    (stack_entry == next_entry) ? stack_entry->start : addr,
3793 		    (p->p_flag & P_SYSTEM)
3794 		    ? VM_MAP_WIRE_SYSTEM|VM_MAP_WIRE_NOHOLES
3795 		    : VM_MAP_WIRE_USER|VM_MAP_WIRE_NOHOLES);
3796 	}
3797 
3798 out:
3799 #ifdef RACCT
3800 	if (rv != KERN_SUCCESS) {
3801 		PROC_LOCK(p);
3802 		error = racct_set(p, RACCT_VMEM, map->size);
3803 		KASSERT(error == 0, ("decreasing RACCT_VMEM failed"));
3804 		if (!old_mlock) {
3805 			error = racct_set(p, RACCT_MEMLOCK,
3806 			    ptoa(pmap_wired_count(map->pmap)));
3807 			KASSERT(error == 0, ("decreasing RACCT_MEMLOCK failed"));
3808 		}
3809 	    	error = racct_set(p, RACCT_STACK, ctob(vm->vm_ssize));
3810 		KASSERT(error == 0, ("decreasing RACCT_STACK failed"));
3811 		PROC_UNLOCK(p);
3812 	}
3813 #endif
3814 
3815 	return (rv);
3816 }
3817 
3818 /*
3819  * Unshare the specified VM space for exec.  If other processes are
3820  * mapped to it, then create a new one.  The new vmspace is null.
3821  */
3822 int
3823 vmspace_exec(struct proc *p, vm_offset_t minuser, vm_offset_t maxuser)
3824 {
3825 	struct vmspace *oldvmspace = p->p_vmspace;
3826 	struct vmspace *newvmspace;
3827 
3828 	KASSERT((curthread->td_pflags & TDP_EXECVMSPC) == 0,
3829 	    ("vmspace_exec recursed"));
3830 	newvmspace = vmspace_alloc(minuser, maxuser, NULL);
3831 	if (newvmspace == NULL)
3832 		return (ENOMEM);
3833 	newvmspace->vm_swrss = oldvmspace->vm_swrss;
3834 	/*
3835 	 * This code is written like this for prototype purposes.  The
3836 	 * goal is to avoid running down the vmspace here, but let the
3837 	 * other process's that are still using the vmspace to finally
3838 	 * run it down.  Even though there is little or no chance of blocking
3839 	 * here, it is a good idea to keep this form for future mods.
3840 	 */
3841 	PROC_VMSPACE_LOCK(p);
3842 	p->p_vmspace = newvmspace;
3843 	PROC_VMSPACE_UNLOCK(p);
3844 	if (p == curthread->td_proc)
3845 		pmap_activate(curthread);
3846 	curthread->td_pflags |= TDP_EXECVMSPC;
3847 	return (0);
3848 }
3849 
3850 /*
3851  * Unshare the specified VM space for forcing COW.  This
3852  * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
3853  */
3854 int
3855 vmspace_unshare(struct proc *p)
3856 {
3857 	struct vmspace *oldvmspace = p->p_vmspace;
3858 	struct vmspace *newvmspace;
3859 	vm_ooffset_t fork_charge;
3860 
3861 	if (oldvmspace->vm_refcnt == 1)
3862 		return (0);
3863 	fork_charge = 0;
3864 	newvmspace = vmspace_fork(oldvmspace, &fork_charge);
3865 	if (newvmspace == NULL)
3866 		return (ENOMEM);
3867 	if (!swap_reserve_by_cred(fork_charge, p->p_ucred)) {
3868 		vmspace_free(newvmspace);
3869 		return (ENOMEM);
3870 	}
3871 	PROC_VMSPACE_LOCK(p);
3872 	p->p_vmspace = newvmspace;
3873 	PROC_VMSPACE_UNLOCK(p);
3874 	if (p == curthread->td_proc)
3875 		pmap_activate(curthread);
3876 	vmspace_free(oldvmspace);
3877 	return (0);
3878 }
3879 
3880 /*
3881  *	vm_map_lookup:
3882  *
3883  *	Finds the VM object, offset, and
3884  *	protection for a given virtual address in the
3885  *	specified map, assuming a page fault of the
3886  *	type specified.
3887  *
3888  *	Leaves the map in question locked for read; return
3889  *	values are guaranteed until a vm_map_lookup_done
3890  *	call is performed.  Note that the map argument
3891  *	is in/out; the returned map must be used in
3892  *	the call to vm_map_lookup_done.
3893  *
3894  *	A handle (out_entry) is returned for use in
3895  *	vm_map_lookup_done, to make that fast.
3896  *
3897  *	If a lookup is requested with "write protection"
3898  *	specified, the map may be changed to perform virtual
3899  *	copying operations, although the data referenced will
3900  *	remain the same.
3901  */
3902 int
3903 vm_map_lookup(vm_map_t *var_map,		/* IN/OUT */
3904 	      vm_offset_t vaddr,
3905 	      vm_prot_t fault_typea,
3906 	      vm_map_entry_t *out_entry,	/* OUT */
3907 	      vm_object_t *object,		/* OUT */
3908 	      vm_pindex_t *pindex,		/* OUT */
3909 	      vm_prot_t *out_prot,		/* OUT */
3910 	      boolean_t *wired)			/* OUT */
3911 {
3912 	vm_map_entry_t entry;
3913 	vm_map_t map = *var_map;
3914 	vm_prot_t prot;
3915 	vm_prot_t fault_type = fault_typea;
3916 	vm_object_t eobject;
3917 	vm_size_t size;
3918 	struct ucred *cred;
3919 
3920 RetryLookup:;
3921 
3922 	vm_map_lock_read(map);
3923 
3924 	/*
3925 	 * Lookup the faulting address.
3926 	 */
3927 	if (!vm_map_lookup_entry(map, vaddr, out_entry)) {
3928 		vm_map_unlock_read(map);
3929 		return (KERN_INVALID_ADDRESS);
3930 	}
3931 
3932 	entry = *out_entry;
3933 
3934 	/*
3935 	 * Handle submaps.
3936 	 */
3937 	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
3938 		vm_map_t old_map = map;
3939 
3940 		*var_map = map = entry->object.sub_map;
3941 		vm_map_unlock_read(old_map);
3942 		goto RetryLookup;
3943 	}
3944 
3945 	/*
3946 	 * Check whether this task is allowed to have this page.
3947 	 */
3948 	prot = entry->protection;
3949 	fault_type &= (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE);
3950 	if ((fault_type & prot) != fault_type || prot == VM_PROT_NONE) {
3951 		vm_map_unlock_read(map);
3952 		return (KERN_PROTECTION_FAILURE);
3953 	}
3954 	if ((entry->eflags & MAP_ENTRY_USER_WIRED) &&
3955 	    (entry->eflags & MAP_ENTRY_COW) &&
3956 	    (fault_type & VM_PROT_WRITE)) {
3957 		vm_map_unlock_read(map);
3958 		return (KERN_PROTECTION_FAILURE);
3959 	}
3960 	if ((fault_typea & VM_PROT_COPY) != 0 &&
3961 	    (entry->max_protection & VM_PROT_WRITE) == 0 &&
3962 	    (entry->eflags & MAP_ENTRY_COW) == 0) {
3963 		vm_map_unlock_read(map);
3964 		return (KERN_PROTECTION_FAILURE);
3965 	}
3966 
3967 	/*
3968 	 * If this page is not pageable, we have to get it for all possible
3969 	 * accesses.
3970 	 */
3971 	*wired = (entry->wired_count != 0);
3972 	if (*wired)
3973 		fault_type = entry->protection;
3974 	size = entry->end - entry->start;
3975 	/*
3976 	 * If the entry was copy-on-write, we either ...
3977 	 */
3978 	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3979 		/*
3980 		 * If we want to write the page, we may as well handle that
3981 		 * now since we've got the map locked.
3982 		 *
3983 		 * If we don't need to write the page, we just demote the
3984 		 * permissions allowed.
3985 		 */
3986 		if ((fault_type & VM_PROT_WRITE) != 0 ||
3987 		    (fault_typea & VM_PROT_COPY) != 0) {
3988 			/*
3989 			 * Make a new object, and place it in the object
3990 			 * chain.  Note that no new references have appeared
3991 			 * -- one just moved from the map to the new
3992 			 * object.
3993 			 */
3994 			if (vm_map_lock_upgrade(map))
3995 				goto RetryLookup;
3996 
3997 			if (entry->cred == NULL) {
3998 				/*
3999 				 * The debugger owner is charged for
4000 				 * the memory.
4001 				 */
4002 				cred = curthread->td_ucred;
4003 				crhold(cred);
4004 				if (!swap_reserve_by_cred(size, cred)) {
4005 					crfree(cred);
4006 					vm_map_unlock(map);
4007 					return (KERN_RESOURCE_SHORTAGE);
4008 				}
4009 				entry->cred = cred;
4010 			}
4011 			vm_object_shadow(&entry->object.vm_object,
4012 			    &entry->offset, size);
4013 			entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
4014 			eobject = entry->object.vm_object;
4015 			if (eobject->cred != NULL) {
4016 				/*
4017 				 * The object was not shadowed.
4018 				 */
4019 				swap_release_by_cred(size, entry->cred);
4020 				crfree(entry->cred);
4021 				entry->cred = NULL;
4022 			} else if (entry->cred != NULL) {
4023 				VM_OBJECT_WLOCK(eobject);
4024 				eobject->cred = entry->cred;
4025 				eobject->charge = size;
4026 				VM_OBJECT_WUNLOCK(eobject);
4027 				entry->cred = NULL;
4028 			}
4029 
4030 			vm_map_lock_downgrade(map);
4031 		} else {
4032 			/*
4033 			 * We're attempting to read a copy-on-write page --
4034 			 * don't allow writes.
4035 			 */
4036 			prot &= ~VM_PROT_WRITE;
4037 		}
4038 	}
4039 
4040 	/*
4041 	 * Create an object if necessary.
4042 	 */
4043 	if (entry->object.vm_object == NULL &&
4044 	    !map->system_map) {
4045 		if (vm_map_lock_upgrade(map))
4046 			goto RetryLookup;
4047 		entry->object.vm_object = vm_object_allocate(OBJT_DEFAULT,
4048 		    atop(size));
4049 		entry->offset = 0;
4050 		if (entry->cred != NULL) {
4051 			VM_OBJECT_WLOCK(entry->object.vm_object);
4052 			entry->object.vm_object->cred = entry->cred;
4053 			entry->object.vm_object->charge = size;
4054 			VM_OBJECT_WUNLOCK(entry->object.vm_object);
4055 			entry->cred = NULL;
4056 		}
4057 		vm_map_lock_downgrade(map);
4058 	}
4059 
4060 	/*
4061 	 * Return the object/offset from this entry.  If the entry was
4062 	 * copy-on-write or empty, it has been fixed up.
4063 	 */
4064 	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4065 	*object = entry->object.vm_object;
4066 
4067 	*out_prot = prot;
4068 	return (KERN_SUCCESS);
4069 }
4070 
4071 /*
4072  *	vm_map_lookup_locked:
4073  *
4074  *	Lookup the faulting address.  A version of vm_map_lookup that returns
4075  *      KERN_FAILURE instead of blocking on map lock or memory allocation.
4076  */
4077 int
4078 vm_map_lookup_locked(vm_map_t *var_map,		/* IN/OUT */
4079 		     vm_offset_t vaddr,
4080 		     vm_prot_t fault_typea,
4081 		     vm_map_entry_t *out_entry,	/* OUT */
4082 		     vm_object_t *object,	/* OUT */
4083 		     vm_pindex_t *pindex,	/* OUT */
4084 		     vm_prot_t *out_prot,	/* OUT */
4085 		     boolean_t *wired)		/* OUT */
4086 {
4087 	vm_map_entry_t entry;
4088 	vm_map_t map = *var_map;
4089 	vm_prot_t prot;
4090 	vm_prot_t fault_type = fault_typea;
4091 
4092 	/*
4093 	 * Lookup the faulting address.
4094 	 */
4095 	if (!vm_map_lookup_entry(map, vaddr, out_entry))
4096 		return (KERN_INVALID_ADDRESS);
4097 
4098 	entry = *out_entry;
4099 
4100 	/*
4101 	 * Fail if the entry refers to a submap.
4102 	 */
4103 	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
4104 		return (KERN_FAILURE);
4105 
4106 	/*
4107 	 * Check whether this task is allowed to have this page.
4108 	 */
4109 	prot = entry->protection;
4110 	fault_type &= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
4111 	if ((fault_type & prot) != fault_type)
4112 		return (KERN_PROTECTION_FAILURE);
4113 	if ((entry->eflags & MAP_ENTRY_USER_WIRED) &&
4114 	    (entry->eflags & MAP_ENTRY_COW) &&
4115 	    (fault_type & VM_PROT_WRITE))
4116 		return (KERN_PROTECTION_FAILURE);
4117 
4118 	/*
4119 	 * If this page is not pageable, we have to get it for all possible
4120 	 * accesses.
4121 	 */
4122 	*wired = (entry->wired_count != 0);
4123 	if (*wired)
4124 		fault_type = entry->protection;
4125 
4126 	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4127 		/*
4128 		 * Fail if the entry was copy-on-write for a write fault.
4129 		 */
4130 		if (fault_type & VM_PROT_WRITE)
4131 			return (KERN_FAILURE);
4132 		/*
4133 		 * We're attempting to read a copy-on-write page --
4134 		 * don't allow writes.
4135 		 */
4136 		prot &= ~VM_PROT_WRITE;
4137 	}
4138 
4139 	/*
4140 	 * Fail if an object should be created.
4141 	 */
4142 	if (entry->object.vm_object == NULL && !map->system_map)
4143 		return (KERN_FAILURE);
4144 
4145 	/*
4146 	 * Return the object/offset from this entry.  If the entry was
4147 	 * copy-on-write or empty, it has been fixed up.
4148 	 */
4149 	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4150 	*object = entry->object.vm_object;
4151 
4152 	*out_prot = prot;
4153 	return (KERN_SUCCESS);
4154 }
4155 
4156 /*
4157  *	vm_map_lookup_done:
4158  *
4159  *	Releases locks acquired by a vm_map_lookup
4160  *	(according to the handle returned by that lookup).
4161  */
4162 void
4163 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry)
4164 {
4165 	/*
4166 	 * Unlock the main-level map
4167 	 */
4168 	vm_map_unlock_read(map);
4169 }
4170 
4171 #include "opt_ddb.h"
4172 #ifdef DDB
4173 #include <sys/kernel.h>
4174 
4175 #include <ddb/ddb.h>
4176 
4177 static void
4178 vm_map_print(vm_map_t map)
4179 {
4180 	vm_map_entry_t entry;
4181 
4182 	db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
4183 	    (void *)map,
4184 	    (void *)map->pmap, map->nentries, map->timestamp);
4185 
4186 	db_indent += 2;
4187 	for (entry = map->header.next; entry != &map->header;
4188 	    entry = entry->next) {
4189 		db_iprintf("map entry %p: start=%p, end=%p\n",
4190 		    (void *)entry, (void *)entry->start, (void *)entry->end);
4191 		{
4192 			static char *inheritance_name[4] =
4193 			{"share", "copy", "none", "donate_copy"};
4194 
4195 			db_iprintf(" prot=%x/%x/%s",
4196 			    entry->protection,
4197 			    entry->max_protection,
4198 			    inheritance_name[(int)(unsigned char)entry->inheritance]);
4199 			if (entry->wired_count != 0)
4200 				db_printf(", wired");
4201 		}
4202 		if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
4203 			db_printf(", share=%p, offset=0x%jx\n",
4204 			    (void *)entry->object.sub_map,
4205 			    (uintmax_t)entry->offset);
4206 			if ((entry->prev == &map->header) ||
4207 			    (entry->prev->object.sub_map !=
4208 				entry->object.sub_map)) {
4209 				db_indent += 2;
4210 				vm_map_print((vm_map_t)entry->object.sub_map);
4211 				db_indent -= 2;
4212 			}
4213 		} else {
4214 			if (entry->cred != NULL)
4215 				db_printf(", ruid %d", entry->cred->cr_ruid);
4216 			db_printf(", object=%p, offset=0x%jx",
4217 			    (void *)entry->object.vm_object,
4218 			    (uintmax_t)entry->offset);
4219 			if (entry->object.vm_object && entry->object.vm_object->cred)
4220 				db_printf(", obj ruid %d charge %jx",
4221 				    entry->object.vm_object->cred->cr_ruid,
4222 				    (uintmax_t)entry->object.vm_object->charge);
4223 			if (entry->eflags & MAP_ENTRY_COW)
4224 				db_printf(", copy (%s)",
4225 				    (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
4226 			db_printf("\n");
4227 
4228 			if ((entry->prev == &map->header) ||
4229 			    (entry->prev->object.vm_object !=
4230 				entry->object.vm_object)) {
4231 				db_indent += 2;
4232 				vm_object_print((db_expr_t)(intptr_t)
4233 						entry->object.vm_object,
4234 						0, 0, (char *)0);
4235 				db_indent -= 2;
4236 			}
4237 		}
4238 	}
4239 	db_indent -= 2;
4240 }
4241 
4242 DB_SHOW_COMMAND(map, map)
4243 {
4244 
4245 	if (!have_addr) {
4246 		db_printf("usage: show map <addr>\n");
4247 		return;
4248 	}
4249 	vm_map_print((vm_map_t)addr);
4250 }
4251 
4252 DB_SHOW_COMMAND(procvm, procvm)
4253 {
4254 	struct proc *p;
4255 
4256 	if (have_addr) {
4257 		p = (struct proc *) addr;
4258 	} else {
4259 		p = curproc;
4260 	}
4261 
4262 	db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
4263 	    (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
4264 	    (void *)vmspace_pmap(p->p_vmspace));
4265 
4266 	vm_map_print((vm_map_t)&p->p_vmspace->vm_map);
4267 }
4268 
4269 #endif /* DDB */
4270