xref: /freebsd/sys/vm/vm_map.c (revision 480093f4440d54b30b3025afeac24b48f2ba7a2e)
1 /*-
2  * SPDX-License-Identifier: (BSD-3-Clause AND MIT-CMU)
3  *
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * The Mach Operating System project at Carnegie-Mellon University.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	from: @(#)vm_map.c	8.3 (Berkeley) 1/12/94
35  *
36  *
37  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38  * All rights reserved.
39  *
40  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
41  *
42  * Permission to use, copy, modify and distribute this software and
43  * its documentation is hereby granted, provided that both the copyright
44  * notice and this permission notice appear in all copies of the
45  * software, derivative works or modified versions, and any portions
46  * thereof, and that both notices appear in supporting documentation.
47  *
48  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
51  *
52  * Carnegie Mellon requests users of this software to return to
53  *
54  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
55  *  School of Computer Science
56  *  Carnegie Mellon University
57  *  Pittsburgh PA 15213-3890
58  *
59  * any improvements or extensions that they make and grant Carnegie the
60  * rights to redistribute these changes.
61  */
62 
63 /*
64  *	Virtual memory mapping module.
65  */
66 
67 #include <sys/cdefs.h>
68 __FBSDID("$FreeBSD$");
69 
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/elf.h>
73 #include <sys/kernel.h>
74 #include <sys/ktr.h>
75 #include <sys/lock.h>
76 #include <sys/mutex.h>
77 #include <sys/proc.h>
78 #include <sys/vmmeter.h>
79 #include <sys/mman.h>
80 #include <sys/vnode.h>
81 #include <sys/racct.h>
82 #include <sys/resourcevar.h>
83 #include <sys/rwlock.h>
84 #include <sys/file.h>
85 #include <sys/sysctl.h>
86 #include <sys/sysent.h>
87 #include <sys/shm.h>
88 
89 #include <vm/vm.h>
90 #include <vm/vm_param.h>
91 #include <vm/pmap.h>
92 #include <vm/vm_map.h>
93 #include <vm/vm_page.h>
94 #include <vm/vm_pageout.h>
95 #include <vm/vm_object.h>
96 #include <vm/vm_pager.h>
97 #include <vm/vm_kern.h>
98 #include <vm/vm_extern.h>
99 #include <vm/vnode_pager.h>
100 #include <vm/swap_pager.h>
101 #include <vm/uma.h>
102 
103 /*
104  *	Virtual memory maps provide for the mapping, protection,
105  *	and sharing of virtual memory objects.  In addition,
106  *	this module provides for an efficient virtual copy of
107  *	memory from one map to another.
108  *
109  *	Synchronization is required prior to most operations.
110  *
111  *	Maps consist of an ordered doubly-linked list of simple
112  *	entries; a self-adjusting binary search tree of these
113  *	entries is used to speed up lookups.
114  *
115  *	Since portions of maps are specified by start/end addresses,
116  *	which may not align with existing map entries, all
117  *	routines merely "clip" entries to these start/end values.
118  *	[That is, an entry is split into two, bordering at a
119  *	start or end value.]  Note that these clippings may not
120  *	always be necessary (as the two resulting entries are then
121  *	not changed); however, the clipping is done for convenience.
122  *
123  *	As mentioned above, virtual copy operations are performed
124  *	by copying VM object references from one map to
125  *	another, and then marking both regions as copy-on-write.
126  */
127 
128 static struct mtx map_sleep_mtx;
129 static uma_zone_t mapentzone;
130 static uma_zone_t kmapentzone;
131 static uma_zone_t mapzone;
132 static uma_zone_t vmspace_zone;
133 static int vmspace_zinit(void *mem, int size, int flags);
134 static int vm_map_zinit(void *mem, int ize, int flags);
135 static void _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min,
136     vm_offset_t max);
137 static void vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map);
138 static void vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry);
139 static void vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry);
140 static int vm_map_growstack(vm_map_t map, vm_offset_t addr,
141     vm_map_entry_t gap_entry);
142 static void vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
143     vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags);
144 #ifdef INVARIANTS
145 static void vm_map_zdtor(void *mem, int size, void *arg);
146 static void vmspace_zdtor(void *mem, int size, void *arg);
147 #endif
148 static int vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos,
149     vm_size_t max_ssize, vm_size_t growsize, vm_prot_t prot, vm_prot_t max,
150     int cow);
151 static void vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
152     vm_offset_t failed_addr);
153 
154 #define	ENTRY_CHARGED(e) ((e)->cred != NULL || \
155     ((e)->object.vm_object != NULL && (e)->object.vm_object->cred != NULL && \
156      !((e)->eflags & MAP_ENTRY_NEEDS_COPY)))
157 
158 /*
159  * PROC_VMSPACE_{UN,}LOCK() can be a noop as long as vmspaces are type
160  * stable.
161  */
162 #define PROC_VMSPACE_LOCK(p) do { } while (0)
163 #define PROC_VMSPACE_UNLOCK(p) do { } while (0)
164 
165 /*
166  *	VM_MAP_RANGE_CHECK:	[ internal use only ]
167  *
168  *	Asserts that the starting and ending region
169  *	addresses fall within the valid range of the map.
170  */
171 #define	VM_MAP_RANGE_CHECK(map, start, end)		\
172 		{					\
173 		if (start < vm_map_min(map))		\
174 			start = vm_map_min(map);	\
175 		if (end > vm_map_max(map))		\
176 			end = vm_map_max(map);		\
177 		if (start > end)			\
178 			start = end;			\
179 		}
180 
181 /*
182  *	vm_map_startup:
183  *
184  *	Initialize the vm_map module.  Must be called before
185  *	any other vm_map routines.
186  *
187  *	Map and entry structures are allocated from the general
188  *	purpose memory pool with some exceptions:
189  *
190  *	- The kernel map and kmem submap are allocated statically.
191  *	- Kernel map entries are allocated out of a static pool.
192  *
193  *	These restrictions are necessary since malloc() uses the
194  *	maps and requires map entries.
195  */
196 
197 void
198 vm_map_startup(void)
199 {
200 	mtx_init(&map_sleep_mtx, "vm map sleep mutex", NULL, MTX_DEF);
201 	mapzone = uma_zcreate("MAP", sizeof(struct vm_map), NULL,
202 #ifdef INVARIANTS
203 	    vm_map_zdtor,
204 #else
205 	    NULL,
206 #endif
207 	    vm_map_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
208 	uma_prealloc(mapzone, MAX_KMAP);
209 	kmapentzone = uma_zcreate("KMAP ENTRY", sizeof(struct vm_map_entry),
210 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
211 	    UMA_ZONE_MTXCLASS | UMA_ZONE_VM);
212 	mapentzone = uma_zcreate("MAP ENTRY", sizeof(struct vm_map_entry),
213 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
214 	vmspace_zone = uma_zcreate("VMSPACE", sizeof(struct vmspace), NULL,
215 #ifdef INVARIANTS
216 	    vmspace_zdtor,
217 #else
218 	    NULL,
219 #endif
220 	    vmspace_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
221 }
222 
223 static int
224 vmspace_zinit(void *mem, int size, int flags)
225 {
226 	struct vmspace *vm;
227 
228 	vm = (struct vmspace *)mem;
229 
230 	vm->vm_map.pmap = NULL;
231 	(void)vm_map_zinit(&vm->vm_map, sizeof(vm->vm_map), flags);
232 	PMAP_LOCK_INIT(vmspace_pmap(vm));
233 	return (0);
234 }
235 
236 static int
237 vm_map_zinit(void *mem, int size, int flags)
238 {
239 	vm_map_t map;
240 
241 	map = (vm_map_t)mem;
242 	memset(map, 0, sizeof(*map));
243 	mtx_init(&map->system_mtx, "vm map (system)", NULL, MTX_DEF | MTX_DUPOK);
244 	sx_init(&map->lock, "vm map (user)");
245 	return (0);
246 }
247 
248 #ifdef INVARIANTS
249 static void
250 vmspace_zdtor(void *mem, int size, void *arg)
251 {
252 	struct vmspace *vm;
253 
254 	vm = (struct vmspace *)mem;
255 
256 	vm_map_zdtor(&vm->vm_map, sizeof(vm->vm_map), arg);
257 }
258 static void
259 vm_map_zdtor(void *mem, int size, void *arg)
260 {
261 	vm_map_t map;
262 
263 	map = (vm_map_t)mem;
264 	KASSERT(map->nentries == 0,
265 	    ("map %p nentries == %d on free.",
266 	    map, map->nentries));
267 	KASSERT(map->size == 0,
268 	    ("map %p size == %lu on free.",
269 	    map, (unsigned long)map->size));
270 }
271 #endif	/* INVARIANTS */
272 
273 /*
274  * Allocate a vmspace structure, including a vm_map and pmap,
275  * and initialize those structures.  The refcnt is set to 1.
276  *
277  * If 'pinit' is NULL then the embedded pmap is initialized via pmap_pinit().
278  */
279 struct vmspace *
280 vmspace_alloc(vm_offset_t min, vm_offset_t max, pmap_pinit_t pinit)
281 {
282 	struct vmspace *vm;
283 
284 	vm = uma_zalloc(vmspace_zone, M_WAITOK);
285 	KASSERT(vm->vm_map.pmap == NULL, ("vm_map.pmap must be NULL"));
286 	if (!pinit(vmspace_pmap(vm))) {
287 		uma_zfree(vmspace_zone, vm);
288 		return (NULL);
289 	}
290 	CTR1(KTR_VM, "vmspace_alloc: %p", vm);
291 	_vm_map_init(&vm->vm_map, vmspace_pmap(vm), min, max);
292 	vm->vm_refcnt = 1;
293 	vm->vm_shm = NULL;
294 	vm->vm_swrss = 0;
295 	vm->vm_tsize = 0;
296 	vm->vm_dsize = 0;
297 	vm->vm_ssize = 0;
298 	vm->vm_taddr = 0;
299 	vm->vm_daddr = 0;
300 	vm->vm_maxsaddr = 0;
301 	return (vm);
302 }
303 
304 #ifdef RACCT
305 static void
306 vmspace_container_reset(struct proc *p)
307 {
308 
309 	PROC_LOCK(p);
310 	racct_set(p, RACCT_DATA, 0);
311 	racct_set(p, RACCT_STACK, 0);
312 	racct_set(p, RACCT_RSS, 0);
313 	racct_set(p, RACCT_MEMLOCK, 0);
314 	racct_set(p, RACCT_VMEM, 0);
315 	PROC_UNLOCK(p);
316 }
317 #endif
318 
319 static inline void
320 vmspace_dofree(struct vmspace *vm)
321 {
322 
323 	CTR1(KTR_VM, "vmspace_free: %p", vm);
324 
325 	/*
326 	 * Make sure any SysV shm is freed, it might not have been in
327 	 * exit1().
328 	 */
329 	shmexit(vm);
330 
331 	/*
332 	 * Lock the map, to wait out all other references to it.
333 	 * Delete all of the mappings and pages they hold, then call
334 	 * the pmap module to reclaim anything left.
335 	 */
336 	(void)vm_map_remove(&vm->vm_map, vm_map_min(&vm->vm_map),
337 	    vm_map_max(&vm->vm_map));
338 
339 	pmap_release(vmspace_pmap(vm));
340 	vm->vm_map.pmap = NULL;
341 	uma_zfree(vmspace_zone, vm);
342 }
343 
344 void
345 vmspace_free(struct vmspace *vm)
346 {
347 
348 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
349 	    "vmspace_free() called");
350 
351 	if (vm->vm_refcnt == 0)
352 		panic("vmspace_free: attempt to free already freed vmspace");
353 
354 	if (atomic_fetchadd_int(&vm->vm_refcnt, -1) == 1)
355 		vmspace_dofree(vm);
356 }
357 
358 void
359 vmspace_exitfree(struct proc *p)
360 {
361 	struct vmspace *vm;
362 
363 	PROC_VMSPACE_LOCK(p);
364 	vm = p->p_vmspace;
365 	p->p_vmspace = NULL;
366 	PROC_VMSPACE_UNLOCK(p);
367 	KASSERT(vm == &vmspace0, ("vmspace_exitfree: wrong vmspace"));
368 	vmspace_free(vm);
369 }
370 
371 void
372 vmspace_exit(struct thread *td)
373 {
374 	int refcnt;
375 	struct vmspace *vm;
376 	struct proc *p;
377 
378 	/*
379 	 * Release user portion of address space.
380 	 * This releases references to vnodes,
381 	 * which could cause I/O if the file has been unlinked.
382 	 * Need to do this early enough that we can still sleep.
383 	 *
384 	 * The last exiting process to reach this point releases as
385 	 * much of the environment as it can. vmspace_dofree() is the
386 	 * slower fallback in case another process had a temporary
387 	 * reference to the vmspace.
388 	 */
389 
390 	p = td->td_proc;
391 	vm = p->p_vmspace;
392 	atomic_add_int(&vmspace0.vm_refcnt, 1);
393 	refcnt = vm->vm_refcnt;
394 	do {
395 		if (refcnt > 1 && p->p_vmspace != &vmspace0) {
396 			/* Switch now since other proc might free vmspace */
397 			PROC_VMSPACE_LOCK(p);
398 			p->p_vmspace = &vmspace0;
399 			PROC_VMSPACE_UNLOCK(p);
400 			pmap_activate(td);
401 		}
402 	} while (!atomic_fcmpset_int(&vm->vm_refcnt, &refcnt, refcnt - 1));
403 	if (refcnt == 1) {
404 		if (p->p_vmspace != vm) {
405 			/* vmspace not yet freed, switch back */
406 			PROC_VMSPACE_LOCK(p);
407 			p->p_vmspace = vm;
408 			PROC_VMSPACE_UNLOCK(p);
409 			pmap_activate(td);
410 		}
411 		pmap_remove_pages(vmspace_pmap(vm));
412 		/* Switch now since this proc will free vmspace */
413 		PROC_VMSPACE_LOCK(p);
414 		p->p_vmspace = &vmspace0;
415 		PROC_VMSPACE_UNLOCK(p);
416 		pmap_activate(td);
417 		vmspace_dofree(vm);
418 	}
419 #ifdef RACCT
420 	if (racct_enable)
421 		vmspace_container_reset(p);
422 #endif
423 }
424 
425 /* Acquire reference to vmspace owned by another process. */
426 
427 struct vmspace *
428 vmspace_acquire_ref(struct proc *p)
429 {
430 	struct vmspace *vm;
431 	int refcnt;
432 
433 	PROC_VMSPACE_LOCK(p);
434 	vm = p->p_vmspace;
435 	if (vm == NULL) {
436 		PROC_VMSPACE_UNLOCK(p);
437 		return (NULL);
438 	}
439 	refcnt = vm->vm_refcnt;
440 	do {
441 		if (refcnt <= 0) { 	/* Avoid 0->1 transition */
442 			PROC_VMSPACE_UNLOCK(p);
443 			return (NULL);
444 		}
445 	} while (!atomic_fcmpset_int(&vm->vm_refcnt, &refcnt, refcnt + 1));
446 	if (vm != p->p_vmspace) {
447 		PROC_VMSPACE_UNLOCK(p);
448 		vmspace_free(vm);
449 		return (NULL);
450 	}
451 	PROC_VMSPACE_UNLOCK(p);
452 	return (vm);
453 }
454 
455 /*
456  * Switch between vmspaces in an AIO kernel process.
457  *
458  * The new vmspace is either the vmspace of a user process obtained
459  * from an active AIO request or the initial vmspace of the AIO kernel
460  * process (when it is idling).  Because user processes will block to
461  * drain any active AIO requests before proceeding in exit() or
462  * execve(), the reference count for vmspaces from AIO requests can
463  * never be 0.  Similarly, AIO kernel processes hold an extra
464  * reference on their initial vmspace for the life of the process.  As
465  * a result, the 'newvm' vmspace always has a non-zero reference
466  * count.  This permits an additional reference on 'newvm' to be
467  * acquired via a simple atomic increment rather than the loop in
468  * vmspace_acquire_ref() above.
469  */
470 void
471 vmspace_switch_aio(struct vmspace *newvm)
472 {
473 	struct vmspace *oldvm;
474 
475 	/* XXX: Need some way to assert that this is an aio daemon. */
476 
477 	KASSERT(newvm->vm_refcnt > 0,
478 	    ("vmspace_switch_aio: newvm unreferenced"));
479 
480 	oldvm = curproc->p_vmspace;
481 	if (oldvm == newvm)
482 		return;
483 
484 	/*
485 	 * Point to the new address space and refer to it.
486 	 */
487 	curproc->p_vmspace = newvm;
488 	atomic_add_int(&newvm->vm_refcnt, 1);
489 
490 	/* Activate the new mapping. */
491 	pmap_activate(curthread);
492 
493 	vmspace_free(oldvm);
494 }
495 
496 void
497 _vm_map_lock(vm_map_t map, const char *file, int line)
498 {
499 
500 	if (map->system_map)
501 		mtx_lock_flags_(&map->system_mtx, 0, file, line);
502 	else
503 		sx_xlock_(&map->lock, file, line);
504 	map->timestamp++;
505 }
506 
507 void
508 vm_map_entry_set_vnode_text(vm_map_entry_t entry, bool add)
509 {
510 	vm_object_t object;
511 	struct vnode *vp;
512 	bool vp_held;
513 
514 	if ((entry->eflags & MAP_ENTRY_VN_EXEC) == 0)
515 		return;
516 	KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
517 	    ("Submap with execs"));
518 	object = entry->object.vm_object;
519 	KASSERT(object != NULL, ("No object for text, entry %p", entry));
520 	if ((object->flags & OBJ_ANON) != 0)
521 		object = object->handle;
522 	else
523 		KASSERT(object->backing_object == NULL,
524 		    ("non-anon object %p shadows", object));
525 	KASSERT(object != NULL, ("No content object for text, entry %p obj %p",
526 	    entry, entry->object.vm_object));
527 
528 	/*
529 	 * Mostly, we do not lock the backing object.  It is
530 	 * referenced by the entry we are processing, so it cannot go
531 	 * away.
532 	 */
533 	vp = NULL;
534 	vp_held = false;
535 	if (object->type == OBJT_DEAD) {
536 		/*
537 		 * For OBJT_DEAD objects, v_writecount was handled in
538 		 * vnode_pager_dealloc().
539 		 */
540 	} else if (object->type == OBJT_VNODE) {
541 		vp = object->handle;
542 	} else if (object->type == OBJT_SWAP) {
543 		KASSERT((object->flags & OBJ_TMPFS_NODE) != 0,
544 		    ("vm_map_entry_set_vnode_text: swap and !TMPFS "
545 		    "entry %p, object %p, add %d", entry, object, add));
546 		/*
547 		 * Tmpfs VREG node, which was reclaimed, has
548 		 * OBJ_TMPFS_NODE flag set, but not OBJ_TMPFS.  In
549 		 * this case there is no v_writecount to adjust.
550 		 */
551 		VM_OBJECT_RLOCK(object);
552 		if ((object->flags & OBJ_TMPFS) != 0) {
553 			vp = object->un_pager.swp.swp_tmpfs;
554 			if (vp != NULL) {
555 				vhold(vp);
556 				vp_held = true;
557 			}
558 		}
559 		VM_OBJECT_RUNLOCK(object);
560 	} else {
561 		KASSERT(0,
562 		    ("vm_map_entry_set_vnode_text: wrong object type, "
563 		    "entry %p, object %p, add %d", entry, object, add));
564 	}
565 	if (vp != NULL) {
566 		if (add) {
567 			VOP_SET_TEXT_CHECKED(vp);
568 		} else {
569 			vn_lock(vp, LK_SHARED | LK_RETRY);
570 			VOP_UNSET_TEXT_CHECKED(vp);
571 			VOP_UNLOCK(vp);
572 		}
573 		if (vp_held)
574 			vdrop(vp);
575 	}
576 }
577 
578 /*
579  * Use a different name for this vm_map_entry field when it's use
580  * is not consistent with its use as part of an ordered search tree.
581  */
582 #define defer_next right
583 
584 static void
585 vm_map_process_deferred(void)
586 {
587 	struct thread *td;
588 	vm_map_entry_t entry, next;
589 	vm_object_t object;
590 
591 	td = curthread;
592 	entry = td->td_map_def_user;
593 	td->td_map_def_user = NULL;
594 	while (entry != NULL) {
595 		next = entry->defer_next;
596 		MPASS((entry->eflags & (MAP_ENTRY_WRITECNT |
597 		    MAP_ENTRY_VN_EXEC)) != (MAP_ENTRY_WRITECNT |
598 		    MAP_ENTRY_VN_EXEC));
599 		if ((entry->eflags & MAP_ENTRY_WRITECNT) != 0) {
600 			/*
601 			 * Decrement the object's writemappings and
602 			 * possibly the vnode's v_writecount.
603 			 */
604 			KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
605 			    ("Submap with writecount"));
606 			object = entry->object.vm_object;
607 			KASSERT(object != NULL, ("No object for writecount"));
608 			vm_pager_release_writecount(object, entry->start,
609 			    entry->end);
610 		}
611 		vm_map_entry_set_vnode_text(entry, false);
612 		vm_map_entry_deallocate(entry, FALSE);
613 		entry = next;
614 	}
615 }
616 
617 #ifdef INVARIANTS
618 static void
619 _vm_map_assert_locked(vm_map_t map, const char *file, int line)
620 {
621 
622 	if (map->system_map)
623 		mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
624 	else
625 		sx_assert_(&map->lock, SA_XLOCKED, file, line);
626 }
627 
628 #define	VM_MAP_ASSERT_LOCKED(map) \
629     _vm_map_assert_locked(map, LOCK_FILE, LOCK_LINE)
630 
631 enum { VMMAP_CHECK_NONE, VMMAP_CHECK_UNLOCK, VMMAP_CHECK_ALL };
632 #ifdef DIAGNOSTIC
633 static int enable_vmmap_check = VMMAP_CHECK_UNLOCK;
634 #else
635 static int enable_vmmap_check = VMMAP_CHECK_NONE;
636 #endif
637 SYSCTL_INT(_debug, OID_AUTO, vmmap_check, CTLFLAG_RWTUN,
638     &enable_vmmap_check, 0, "Enable vm map consistency checking");
639 
640 static void _vm_map_assert_consistent(vm_map_t map, int check);
641 
642 #define VM_MAP_ASSERT_CONSISTENT(map) \
643     _vm_map_assert_consistent(map, VMMAP_CHECK_ALL)
644 #ifdef DIAGNOSTIC
645 #define VM_MAP_UNLOCK_CONSISTENT(map) do {				\
646 	if (map->nupdates > map->nentries) {				\
647 		_vm_map_assert_consistent(map, VMMAP_CHECK_UNLOCK);	\
648 		map->nupdates = 0;					\
649 	}								\
650 } while (0)
651 #else
652 #define VM_MAP_UNLOCK_CONSISTENT(map)
653 #endif
654 #else
655 #define	VM_MAP_ASSERT_LOCKED(map)
656 #define VM_MAP_ASSERT_CONSISTENT(map)
657 #define VM_MAP_UNLOCK_CONSISTENT(map)
658 #endif /* INVARIANTS */
659 
660 void
661 _vm_map_unlock(vm_map_t map, const char *file, int line)
662 {
663 
664 	VM_MAP_UNLOCK_CONSISTENT(map);
665 	if (map->system_map)
666 		mtx_unlock_flags_(&map->system_mtx, 0, file, line);
667 	else {
668 		sx_xunlock_(&map->lock, file, line);
669 		vm_map_process_deferred();
670 	}
671 }
672 
673 void
674 _vm_map_lock_read(vm_map_t map, const char *file, int line)
675 {
676 
677 	if (map->system_map)
678 		mtx_lock_flags_(&map->system_mtx, 0, file, line);
679 	else
680 		sx_slock_(&map->lock, file, line);
681 }
682 
683 void
684 _vm_map_unlock_read(vm_map_t map, const char *file, int line)
685 {
686 
687 	if (map->system_map)
688 		mtx_unlock_flags_(&map->system_mtx, 0, file, line);
689 	else {
690 		sx_sunlock_(&map->lock, file, line);
691 		vm_map_process_deferred();
692 	}
693 }
694 
695 int
696 _vm_map_trylock(vm_map_t map, const char *file, int line)
697 {
698 	int error;
699 
700 	error = map->system_map ?
701 	    !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
702 	    !sx_try_xlock_(&map->lock, file, line);
703 	if (error == 0)
704 		map->timestamp++;
705 	return (error == 0);
706 }
707 
708 int
709 _vm_map_trylock_read(vm_map_t map, const char *file, int line)
710 {
711 	int error;
712 
713 	error = map->system_map ?
714 	    !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
715 	    !sx_try_slock_(&map->lock, file, line);
716 	return (error == 0);
717 }
718 
719 /*
720  *	_vm_map_lock_upgrade:	[ internal use only ]
721  *
722  *	Tries to upgrade a read (shared) lock on the specified map to a write
723  *	(exclusive) lock.  Returns the value "0" if the upgrade succeeds and a
724  *	non-zero value if the upgrade fails.  If the upgrade fails, the map is
725  *	returned without a read or write lock held.
726  *
727  *	Requires that the map be read locked.
728  */
729 int
730 _vm_map_lock_upgrade(vm_map_t map, const char *file, int line)
731 {
732 	unsigned int last_timestamp;
733 
734 	if (map->system_map) {
735 		mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
736 	} else {
737 		if (!sx_try_upgrade_(&map->lock, file, line)) {
738 			last_timestamp = map->timestamp;
739 			sx_sunlock_(&map->lock, file, line);
740 			vm_map_process_deferred();
741 			/*
742 			 * If the map's timestamp does not change while the
743 			 * map is unlocked, then the upgrade succeeds.
744 			 */
745 			sx_xlock_(&map->lock, file, line);
746 			if (last_timestamp != map->timestamp) {
747 				sx_xunlock_(&map->lock, file, line);
748 				return (1);
749 			}
750 		}
751 	}
752 	map->timestamp++;
753 	return (0);
754 }
755 
756 void
757 _vm_map_lock_downgrade(vm_map_t map, const char *file, int line)
758 {
759 
760 	if (map->system_map) {
761 		mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
762 	} else {
763 		VM_MAP_UNLOCK_CONSISTENT(map);
764 		sx_downgrade_(&map->lock, file, line);
765 	}
766 }
767 
768 /*
769  *	vm_map_locked:
770  *
771  *	Returns a non-zero value if the caller holds a write (exclusive) lock
772  *	on the specified map and the value "0" otherwise.
773  */
774 int
775 vm_map_locked(vm_map_t map)
776 {
777 
778 	if (map->system_map)
779 		return (mtx_owned(&map->system_mtx));
780 	else
781 		return (sx_xlocked(&map->lock));
782 }
783 
784 /*
785  *	_vm_map_unlock_and_wait:
786  *
787  *	Atomically releases the lock on the specified map and puts the calling
788  *	thread to sleep.  The calling thread will remain asleep until either
789  *	vm_map_wakeup() is performed on the map or the specified timeout is
790  *	exceeded.
791  *
792  *	WARNING!  This function does not perform deferred deallocations of
793  *	objects and map	entries.  Therefore, the calling thread is expected to
794  *	reacquire the map lock after reawakening and later perform an ordinary
795  *	unlock operation, such as vm_map_unlock(), before completing its
796  *	operation on the map.
797  */
798 int
799 _vm_map_unlock_and_wait(vm_map_t map, int timo, const char *file, int line)
800 {
801 
802 	VM_MAP_UNLOCK_CONSISTENT(map);
803 	mtx_lock(&map_sleep_mtx);
804 	if (map->system_map)
805 		mtx_unlock_flags_(&map->system_mtx, 0, file, line);
806 	else
807 		sx_xunlock_(&map->lock, file, line);
808 	return (msleep(&map->root, &map_sleep_mtx, PDROP | PVM, "vmmaps",
809 	    timo));
810 }
811 
812 /*
813  *	vm_map_wakeup:
814  *
815  *	Awaken any threads that have slept on the map using
816  *	vm_map_unlock_and_wait().
817  */
818 void
819 vm_map_wakeup(vm_map_t map)
820 {
821 
822 	/*
823 	 * Acquire and release map_sleep_mtx to prevent a wakeup()
824 	 * from being performed (and lost) between the map unlock
825 	 * and the msleep() in _vm_map_unlock_and_wait().
826 	 */
827 	mtx_lock(&map_sleep_mtx);
828 	mtx_unlock(&map_sleep_mtx);
829 	wakeup(&map->root);
830 }
831 
832 void
833 vm_map_busy(vm_map_t map)
834 {
835 
836 	VM_MAP_ASSERT_LOCKED(map);
837 	map->busy++;
838 }
839 
840 void
841 vm_map_unbusy(vm_map_t map)
842 {
843 
844 	VM_MAP_ASSERT_LOCKED(map);
845 	KASSERT(map->busy, ("vm_map_unbusy: not busy"));
846 	if (--map->busy == 0 && (map->flags & MAP_BUSY_WAKEUP)) {
847 		vm_map_modflags(map, 0, MAP_BUSY_WAKEUP);
848 		wakeup(&map->busy);
849 	}
850 }
851 
852 void
853 vm_map_wait_busy(vm_map_t map)
854 {
855 
856 	VM_MAP_ASSERT_LOCKED(map);
857 	while (map->busy) {
858 		vm_map_modflags(map, MAP_BUSY_WAKEUP, 0);
859 		if (map->system_map)
860 			msleep(&map->busy, &map->system_mtx, 0, "mbusy", 0);
861 		else
862 			sx_sleep(&map->busy, &map->lock, 0, "mbusy", 0);
863 	}
864 	map->timestamp++;
865 }
866 
867 long
868 vmspace_resident_count(struct vmspace *vmspace)
869 {
870 	return pmap_resident_count(vmspace_pmap(vmspace));
871 }
872 
873 /*
874  *	vm_map_create:
875  *
876  *	Creates and returns a new empty VM map with
877  *	the given physical map structure, and having
878  *	the given lower and upper address bounds.
879  */
880 vm_map_t
881 vm_map_create(pmap_t pmap, vm_offset_t min, vm_offset_t max)
882 {
883 	vm_map_t result;
884 
885 	result = uma_zalloc(mapzone, M_WAITOK);
886 	CTR1(KTR_VM, "vm_map_create: %p", result);
887 	_vm_map_init(result, pmap, min, max);
888 	return (result);
889 }
890 
891 /*
892  * Initialize an existing vm_map structure
893  * such as that in the vmspace structure.
894  */
895 static void
896 _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
897 {
898 
899 	map->header.eflags = MAP_ENTRY_HEADER;
900 	map->needs_wakeup = FALSE;
901 	map->system_map = 0;
902 	map->pmap = pmap;
903 	map->header.end = min;
904 	map->header.start = max;
905 	map->flags = 0;
906 	map->header.left = map->header.right = &map->header;
907 	map->root = NULL;
908 	map->timestamp = 0;
909 	map->busy = 0;
910 	map->anon_loc = 0;
911 #ifdef DIAGNOSTIC
912 	map->nupdates = 0;
913 #endif
914 }
915 
916 void
917 vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
918 {
919 
920 	_vm_map_init(map, pmap, min, max);
921 	mtx_init(&map->system_mtx, "system map", NULL, MTX_DEF | MTX_DUPOK);
922 	sx_init(&map->lock, "user map");
923 }
924 
925 /*
926  *	vm_map_entry_dispose:	[ internal use only ]
927  *
928  *	Inverse of vm_map_entry_create.
929  */
930 static void
931 vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry)
932 {
933 	uma_zfree(map->system_map ? kmapentzone : mapentzone, entry);
934 }
935 
936 /*
937  *	vm_map_entry_create:	[ internal use only ]
938  *
939  *	Allocates a VM map entry for insertion.
940  *	No entry fields are filled in.
941  */
942 static vm_map_entry_t
943 vm_map_entry_create(vm_map_t map)
944 {
945 	vm_map_entry_t new_entry;
946 
947 	if (map->system_map)
948 		new_entry = uma_zalloc(kmapentzone, M_NOWAIT);
949 	else
950 		new_entry = uma_zalloc(mapentzone, M_WAITOK);
951 	if (new_entry == NULL)
952 		panic("vm_map_entry_create: kernel resources exhausted");
953 	return (new_entry);
954 }
955 
956 /*
957  *	vm_map_entry_set_behavior:
958  *
959  *	Set the expected access behavior, either normal, random, or
960  *	sequential.
961  */
962 static inline void
963 vm_map_entry_set_behavior(vm_map_entry_t entry, u_char behavior)
964 {
965 	entry->eflags = (entry->eflags & ~MAP_ENTRY_BEHAV_MASK) |
966 	    (behavior & MAP_ENTRY_BEHAV_MASK);
967 }
968 
969 /*
970  *	vm_map_entry_max_free_{left,right}:
971  *
972  *	Compute the size of the largest free gap between two entries,
973  *	one the root of a tree and the other the ancestor of that root
974  *	that is the least or greatest ancestor found on the search path.
975  */
976 static inline vm_size_t
977 vm_map_entry_max_free_left(vm_map_entry_t root, vm_map_entry_t left_ancestor)
978 {
979 
980 	return (root->left != left_ancestor ?
981 	    root->left->max_free : root->start - left_ancestor->end);
982 }
983 
984 static inline vm_size_t
985 vm_map_entry_max_free_right(vm_map_entry_t root, vm_map_entry_t right_ancestor)
986 {
987 
988 	return (root->right != right_ancestor ?
989 	    root->right->max_free : right_ancestor->start - root->end);
990 }
991 
992 /*
993  *	vm_map_entry_{pred,succ}:
994  *
995  *	Find the {predecessor, successor} of the entry by taking one step
996  *	in the appropriate direction and backtracking as much as necessary.
997  *	vm_map_entry_succ is defined in vm_map.h.
998  */
999 static inline vm_map_entry_t
1000 vm_map_entry_pred(vm_map_entry_t entry)
1001 {
1002 	vm_map_entry_t prior;
1003 
1004 	prior = entry->left;
1005 	if (prior->right->start < entry->start) {
1006 		do
1007 			prior = prior->right;
1008 		while (prior->right != entry);
1009 	}
1010 	return (prior);
1011 }
1012 
1013 static inline vm_size_t
1014 vm_size_max(vm_size_t a, vm_size_t b)
1015 {
1016 
1017 	return (a > b ? a : b);
1018 }
1019 
1020 #define SPLAY_LEFT_STEP(root, y, llist, rlist, test) do {		\
1021 	vm_map_entry_t z;						\
1022 	vm_size_t max_free;						\
1023 									\
1024 	/*								\
1025 	 * Infer root->right->max_free == root->max_free when		\
1026 	 * y->max_free < root->max_free || root->max_free == 0.		\
1027 	 * Otherwise, look right to find it.				\
1028 	 */								\
1029 	y = root->left;							\
1030 	max_free = root->max_free;					\
1031 	KASSERT(max_free == vm_size_max(				\
1032 	    vm_map_entry_max_free_left(root, llist),			\
1033 	    vm_map_entry_max_free_right(root, rlist)),			\
1034 	    ("%s: max_free invariant fails", __func__));		\
1035 	if (max_free - 1 < vm_map_entry_max_free_left(root, llist))	\
1036 		max_free = vm_map_entry_max_free_right(root, rlist);	\
1037 	if (y != llist && (test)) {					\
1038 		/* Rotate right and make y root. */			\
1039 		z = y->right;						\
1040 		if (z != root) {					\
1041 			root->left = z;					\
1042 			y->right = root;				\
1043 			if (max_free < y->max_free)			\
1044 			    root->max_free = max_free =			\
1045 			    vm_size_max(max_free, z->max_free);		\
1046 		} else if (max_free < y->max_free)			\
1047 			root->max_free = max_free =			\
1048 			    vm_size_max(max_free, root->start - y->end);\
1049 		root = y;						\
1050 		y = root->left;						\
1051 	}								\
1052 	/* Copy right->max_free.  Put root on rlist. */			\
1053 	root->max_free = max_free;					\
1054 	KASSERT(max_free == vm_map_entry_max_free_right(root, rlist),	\
1055 	    ("%s: max_free not copied from right", __func__));		\
1056 	root->left = rlist;						\
1057 	rlist = root;							\
1058 	root = y != llist ? y : NULL;					\
1059 } while (0)
1060 
1061 #define SPLAY_RIGHT_STEP(root, y, llist, rlist, test) do {		\
1062 	vm_map_entry_t z;						\
1063 	vm_size_t max_free;						\
1064 									\
1065 	/*								\
1066 	 * Infer root->left->max_free == root->max_free when		\
1067 	 * y->max_free < root->max_free || root->max_free == 0.		\
1068 	 * Otherwise, look left to find it.				\
1069 	 */								\
1070 	y = root->right;						\
1071 	max_free = root->max_free;					\
1072 	KASSERT(max_free == vm_size_max(				\
1073 	    vm_map_entry_max_free_left(root, llist),			\
1074 	    vm_map_entry_max_free_right(root, rlist)),			\
1075 	    ("%s: max_free invariant fails", __func__));		\
1076 	if (max_free - 1 < vm_map_entry_max_free_right(root, rlist))	\
1077 		max_free = vm_map_entry_max_free_left(root, llist);	\
1078 	if (y != rlist && (test)) {					\
1079 		/* Rotate left and make y root. */			\
1080 		z = y->left;						\
1081 		if (z != root) {					\
1082 			root->right = z;				\
1083 			y->left = root;					\
1084 			if (max_free < y->max_free)			\
1085 			    root->max_free = max_free =			\
1086 			    vm_size_max(max_free, z->max_free);		\
1087 		} else if (max_free < y->max_free)			\
1088 			root->max_free = max_free =			\
1089 			    vm_size_max(max_free, y->start - root->end);\
1090 		root = y;						\
1091 		y = root->right;					\
1092 	}								\
1093 	/* Copy left->max_free.  Put root on llist. */			\
1094 	root->max_free = max_free;					\
1095 	KASSERT(max_free == vm_map_entry_max_free_left(root, llist),	\
1096 	    ("%s: max_free not copied from left", __func__));		\
1097 	root->right = llist;						\
1098 	llist = root;							\
1099 	root = y != rlist ? y : NULL;					\
1100 } while (0)
1101 
1102 /*
1103  * Walk down the tree until we find addr or a gap where addr would go, breaking
1104  * off left and right subtrees of nodes less than, or greater than addr.  Treat
1105  * subtrees with root->max_free < length as empty trees.  llist and rlist are
1106  * the two sides in reverse order (bottom-up), with llist linked by the right
1107  * pointer and rlist linked by the left pointer in the vm_map_entry, and both
1108  * lists terminated by &map->header.  This function, and the subsequent call to
1109  * vm_map_splay_merge_{left,right,pred,succ}, rely on the start and end address
1110  * values in &map->header.
1111  */
1112 static __always_inline vm_map_entry_t
1113 vm_map_splay_split(vm_map_t map, vm_offset_t addr, vm_size_t length,
1114     vm_map_entry_t *llist, vm_map_entry_t *rlist)
1115 {
1116 	vm_map_entry_t left, right, root, y;
1117 
1118 	left = right = &map->header;
1119 	root = map->root;
1120 	while (root != NULL && root->max_free >= length) {
1121 		KASSERT(left->end <= root->start &&
1122 		    root->end <= right->start,
1123 		    ("%s: root not within tree bounds", __func__));
1124 		if (addr < root->start) {
1125 			SPLAY_LEFT_STEP(root, y, left, right,
1126 			    y->max_free >= length && addr < y->start);
1127 		} else if (addr >= root->end) {
1128 			SPLAY_RIGHT_STEP(root, y, left, right,
1129 			    y->max_free >= length && addr >= y->end);
1130 		} else
1131 			break;
1132 	}
1133 	*llist = left;
1134 	*rlist = right;
1135 	return (root);
1136 }
1137 
1138 static __always_inline void
1139 vm_map_splay_findnext(vm_map_entry_t root, vm_map_entry_t *rlist)
1140 {
1141 	vm_map_entry_t hi, right, y;
1142 
1143 	right = *rlist;
1144 	hi = root->right == right ? NULL : root->right;
1145 	if (hi == NULL)
1146 		return;
1147 	do
1148 		SPLAY_LEFT_STEP(hi, y, root, right, true);
1149 	while (hi != NULL);
1150 	*rlist = right;
1151 }
1152 
1153 static __always_inline void
1154 vm_map_splay_findprev(vm_map_entry_t root, vm_map_entry_t *llist)
1155 {
1156 	vm_map_entry_t left, lo, y;
1157 
1158 	left = *llist;
1159 	lo = root->left == left ? NULL : root->left;
1160 	if (lo == NULL)
1161 		return;
1162 	do
1163 		SPLAY_RIGHT_STEP(lo, y, left, root, true);
1164 	while (lo != NULL);
1165 	*llist = left;
1166 }
1167 
1168 static inline void
1169 vm_map_entry_swap(vm_map_entry_t *a, vm_map_entry_t *b)
1170 {
1171 	vm_map_entry_t tmp;
1172 
1173 	tmp = *b;
1174 	*b = *a;
1175 	*a = tmp;
1176 }
1177 
1178 /*
1179  * Walk back up the two spines, flip the pointers and set max_free.  The
1180  * subtrees of the root go at the bottom of llist and rlist.
1181  */
1182 static vm_size_t
1183 vm_map_splay_merge_left_walk(vm_map_entry_t header, vm_map_entry_t root,
1184     vm_map_entry_t tail, vm_size_t max_free, vm_map_entry_t llist)
1185 {
1186 	do {
1187 		/*
1188 		 * The max_free values of the children of llist are in
1189 		 * llist->max_free and max_free.  Update with the
1190 		 * max value.
1191 		 */
1192 		llist->max_free = max_free =
1193 		    vm_size_max(llist->max_free, max_free);
1194 		vm_map_entry_swap(&llist->right, &tail);
1195 		vm_map_entry_swap(&tail, &llist);
1196 	} while (llist != header);
1197 	root->left = tail;
1198 	return (max_free);
1199 }
1200 
1201 /*
1202  * When llist is known to be the predecessor of root.
1203  */
1204 static inline vm_size_t
1205 vm_map_splay_merge_pred(vm_map_entry_t header, vm_map_entry_t root,
1206     vm_map_entry_t llist)
1207 {
1208 	vm_size_t max_free;
1209 
1210 	max_free = root->start - llist->end;
1211 	if (llist != header) {
1212 		max_free = vm_map_splay_merge_left_walk(header, root,
1213 		    root, max_free, llist);
1214 	} else {
1215 		root->left = header;
1216 		header->right = root;
1217 	}
1218 	return (max_free);
1219 }
1220 
1221 /*
1222  * When llist may or may not be the predecessor of root.
1223  */
1224 static inline vm_size_t
1225 vm_map_splay_merge_left(vm_map_entry_t header, vm_map_entry_t root,
1226     vm_map_entry_t llist)
1227 {
1228 	vm_size_t max_free;
1229 
1230 	max_free = vm_map_entry_max_free_left(root, llist);
1231 	if (llist != header) {
1232 		max_free = vm_map_splay_merge_left_walk(header, root,
1233 		    root->left == llist ? root : root->left,
1234 		    max_free, llist);
1235 	}
1236 	return (max_free);
1237 }
1238 
1239 static vm_size_t
1240 vm_map_splay_merge_right_walk(vm_map_entry_t header, vm_map_entry_t root,
1241     vm_map_entry_t tail, vm_size_t max_free, vm_map_entry_t rlist)
1242 {
1243 	do {
1244 		/*
1245 		 * The max_free values of the children of rlist are in
1246 		 * rlist->max_free and max_free.  Update with the
1247 		 * max value.
1248 		 */
1249 		rlist->max_free = max_free =
1250 		    vm_size_max(rlist->max_free, max_free);
1251 		vm_map_entry_swap(&rlist->left, &tail);
1252 		vm_map_entry_swap(&tail, &rlist);
1253 	} while (rlist != header);
1254 	root->right = tail;
1255 	return (max_free);
1256 }
1257 
1258 /*
1259  * When rlist is known to be the succecessor of root.
1260  */
1261 static inline vm_size_t
1262 vm_map_splay_merge_succ(vm_map_entry_t header, vm_map_entry_t root,
1263     vm_map_entry_t rlist)
1264 {
1265 	vm_size_t max_free;
1266 
1267 	max_free = rlist->start - root->end;
1268 	if (rlist != header) {
1269 		max_free = vm_map_splay_merge_right_walk(header, root,
1270 		    root, max_free, rlist);
1271 	} else {
1272 		root->right = header;
1273 		header->left = root;
1274 	}
1275 	return (max_free);
1276 }
1277 
1278 /*
1279  * When rlist may or may not be the succecessor of root.
1280  */
1281 static inline vm_size_t
1282 vm_map_splay_merge_right(vm_map_entry_t header, vm_map_entry_t root,
1283     vm_map_entry_t rlist)
1284 {
1285 	vm_size_t max_free;
1286 
1287 	max_free = vm_map_entry_max_free_right(root, rlist);
1288 	if (rlist != header) {
1289 		max_free = vm_map_splay_merge_right_walk(header, root,
1290 		    root->right == rlist ? root : root->right,
1291 		    max_free, rlist);
1292 	}
1293 	return (max_free);
1294 }
1295 
1296 /*
1297  *	vm_map_splay:
1298  *
1299  *	The Sleator and Tarjan top-down splay algorithm with the
1300  *	following variation.  Max_free must be computed bottom-up, so
1301  *	on the downward pass, maintain the left and right spines in
1302  *	reverse order.  Then, make a second pass up each side to fix
1303  *	the pointers and compute max_free.  The time bound is O(log n)
1304  *	amortized.
1305  *
1306  *	The tree is threaded, which means that there are no null pointers.
1307  *	When a node has no left child, its left pointer points to its
1308  *	predecessor, which the last ancestor on the search path from the root
1309  *	where the search branched right.  Likewise, when a node has no right
1310  *	child, its right pointer points to its successor.  The map header node
1311  *	is the predecessor of the first map entry, and the successor of the
1312  *	last.
1313  *
1314  *	The new root is the vm_map_entry containing "addr", or else an
1315  *	adjacent entry (lower if possible) if addr is not in the tree.
1316  *
1317  *	The map must be locked, and leaves it so.
1318  *
1319  *	Returns: the new root.
1320  */
1321 static vm_map_entry_t
1322 vm_map_splay(vm_map_t map, vm_offset_t addr)
1323 {
1324 	vm_map_entry_t header, llist, rlist, root;
1325 	vm_size_t max_free_left, max_free_right;
1326 
1327 	header = &map->header;
1328 	root = vm_map_splay_split(map, addr, 0, &llist, &rlist);
1329 	if (root != NULL) {
1330 		max_free_left = vm_map_splay_merge_left(header, root, llist);
1331 		max_free_right = vm_map_splay_merge_right(header, root, rlist);
1332 	} else if (llist != header) {
1333 		/*
1334 		 * Recover the greatest node in the left
1335 		 * subtree and make it the root.
1336 		 */
1337 		root = llist;
1338 		llist = root->right;
1339 		max_free_left = vm_map_splay_merge_left(header, root, llist);
1340 		max_free_right = vm_map_splay_merge_succ(header, root, rlist);
1341 	} else if (rlist != header) {
1342 		/*
1343 		 * Recover the least node in the right
1344 		 * subtree and make it the root.
1345 		 */
1346 		root = rlist;
1347 		rlist = root->left;
1348 		max_free_left = vm_map_splay_merge_pred(header, root, llist);
1349 		max_free_right = vm_map_splay_merge_right(header, root, rlist);
1350 	} else {
1351 		/* There is no root. */
1352 		return (NULL);
1353 	}
1354 	root->max_free = vm_size_max(max_free_left, max_free_right);
1355 	map->root = root;
1356 	VM_MAP_ASSERT_CONSISTENT(map);
1357 	return (root);
1358 }
1359 
1360 /*
1361  *	vm_map_entry_{un,}link:
1362  *
1363  *	Insert/remove entries from maps.  On linking, if new entry clips
1364  *	existing entry, trim existing entry to avoid overlap, and manage
1365  *	offsets.  On unlinking, merge disappearing entry with neighbor, if
1366  *	called for, and manage offsets.  Callers should not modify fields in
1367  *	entries already mapped.
1368  */
1369 static void
1370 vm_map_entry_link(vm_map_t map, vm_map_entry_t entry)
1371 {
1372 	vm_map_entry_t header, llist, rlist, root;
1373 	vm_size_t max_free_left, max_free_right;
1374 
1375 	CTR3(KTR_VM,
1376 	    "vm_map_entry_link: map %p, nentries %d, entry %p", map,
1377 	    map->nentries, entry);
1378 	VM_MAP_ASSERT_LOCKED(map);
1379 	map->nentries++;
1380 	header = &map->header;
1381 	root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
1382 	if (root == NULL) {
1383 		/*
1384 		 * The new entry does not overlap any existing entry in the
1385 		 * map, so it becomes the new root of the map tree.
1386 		 */
1387 		max_free_left = vm_map_splay_merge_pred(header, entry, llist);
1388 		max_free_right = vm_map_splay_merge_succ(header, entry, rlist);
1389 	} else if (entry->start == root->start) {
1390 		/*
1391 		 * The new entry is a clone of root, with only the end field
1392 		 * changed.  The root entry will be shrunk to abut the new
1393 		 * entry, and will be the right child of the new root entry in
1394 		 * the modified map.
1395 		 */
1396 		KASSERT(entry->end < root->end,
1397 		    ("%s: clip_start not within entry", __func__));
1398 		vm_map_splay_findprev(root, &llist);
1399 		root->offset += entry->end - root->start;
1400 		root->start = entry->end;
1401 		max_free_left = vm_map_splay_merge_pred(header, entry, llist);
1402 		max_free_right = root->max_free = vm_size_max(
1403 		    vm_map_splay_merge_pred(entry, root, entry),
1404 		    vm_map_splay_merge_right(header, root, rlist));
1405 	} else {
1406 		/*
1407 		 * The new entry is a clone of root, with only the start field
1408 		 * changed.  The root entry will be shrunk to abut the new
1409 		 * entry, and will be the left child of the new root entry in
1410 		 * the modified map.
1411 		 */
1412 		KASSERT(entry->end == root->end,
1413 		    ("%s: clip_start not within entry", __func__));
1414 		vm_map_splay_findnext(root, &rlist);
1415 		entry->offset += entry->start - root->start;
1416 		root->end = entry->start;
1417 		max_free_left = root->max_free = vm_size_max(
1418 		    vm_map_splay_merge_left(header, root, llist),
1419 		    vm_map_splay_merge_succ(entry, root, entry));
1420 		max_free_right = vm_map_splay_merge_succ(header, entry, rlist);
1421 	}
1422 	entry->max_free = vm_size_max(max_free_left, max_free_right);
1423 	map->root = entry;
1424 	VM_MAP_ASSERT_CONSISTENT(map);
1425 }
1426 
1427 enum unlink_merge_type {
1428 	UNLINK_MERGE_NONE,
1429 	UNLINK_MERGE_NEXT
1430 };
1431 
1432 static void
1433 vm_map_entry_unlink(vm_map_t map, vm_map_entry_t entry,
1434     enum unlink_merge_type op)
1435 {
1436 	vm_map_entry_t header, llist, rlist, root;
1437 	vm_size_t max_free_left, max_free_right;
1438 
1439 	VM_MAP_ASSERT_LOCKED(map);
1440 	header = &map->header;
1441 	root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
1442 	KASSERT(root != NULL,
1443 	    ("vm_map_entry_unlink: unlink object not mapped"));
1444 
1445 	vm_map_splay_findprev(root, &llist);
1446 	vm_map_splay_findnext(root, &rlist);
1447 	if (op == UNLINK_MERGE_NEXT) {
1448 		rlist->start = root->start;
1449 		rlist->offset = root->offset;
1450 	}
1451 	if (llist != header) {
1452 		root = llist;
1453 		llist = root->right;
1454 		max_free_left = vm_map_splay_merge_left(header, root, llist);
1455 		max_free_right = vm_map_splay_merge_succ(header, root, rlist);
1456 	} else if (rlist != header) {
1457 		root = rlist;
1458 		rlist = root->left;
1459 		max_free_left = vm_map_splay_merge_pred(header, root, llist);
1460 		max_free_right = vm_map_splay_merge_right(header, root, rlist);
1461 	} else {
1462 		header->left = header->right = header;
1463 		root = NULL;
1464 	}
1465 	if (root != NULL)
1466 		root->max_free = vm_size_max(max_free_left, max_free_right);
1467 	map->root = root;
1468 	VM_MAP_ASSERT_CONSISTENT(map);
1469 	map->nentries--;
1470 	CTR3(KTR_VM, "vm_map_entry_unlink: map %p, nentries %d, entry %p", map,
1471 	    map->nentries, entry);
1472 }
1473 
1474 /*
1475  *	vm_map_entry_resize:
1476  *
1477  *	Resize a vm_map_entry, recompute the amount of free space that
1478  *	follows it and propagate that value up the tree.
1479  *
1480  *	The map must be locked, and leaves it so.
1481  */
1482 static void
1483 vm_map_entry_resize(vm_map_t map, vm_map_entry_t entry, vm_size_t grow_amount)
1484 {
1485 	vm_map_entry_t header, llist, rlist, root;
1486 
1487 	VM_MAP_ASSERT_LOCKED(map);
1488 	header = &map->header;
1489 	root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
1490 	KASSERT(root != NULL, ("%s: resize object not mapped", __func__));
1491 	vm_map_splay_findnext(root, &rlist);
1492 	entry->end += grow_amount;
1493 	root->max_free = vm_size_max(
1494 	    vm_map_splay_merge_left(header, root, llist),
1495 	    vm_map_splay_merge_succ(header, root, rlist));
1496 	map->root = root;
1497 	VM_MAP_ASSERT_CONSISTENT(map);
1498 	CTR4(KTR_VM, "%s: map %p, nentries %d, entry %p",
1499 	    __func__, map, map->nentries, entry);
1500 }
1501 
1502 /*
1503  *	vm_map_lookup_entry:	[ internal use only ]
1504  *
1505  *	Finds the map entry containing (or
1506  *	immediately preceding) the specified address
1507  *	in the given map; the entry is returned
1508  *	in the "entry" parameter.  The boolean
1509  *	result indicates whether the address is
1510  *	actually contained in the map.
1511  */
1512 boolean_t
1513 vm_map_lookup_entry(
1514 	vm_map_t map,
1515 	vm_offset_t address,
1516 	vm_map_entry_t *entry)	/* OUT */
1517 {
1518 	vm_map_entry_t cur, header, lbound, ubound;
1519 	boolean_t locked;
1520 
1521 	/*
1522 	 * If the map is empty, then the map entry immediately preceding
1523 	 * "address" is the map's header.
1524 	 */
1525 	header = &map->header;
1526 	cur = map->root;
1527 	if (cur == NULL) {
1528 		*entry = header;
1529 		return (FALSE);
1530 	}
1531 	if (address >= cur->start && cur->end > address) {
1532 		*entry = cur;
1533 		return (TRUE);
1534 	}
1535 	if ((locked = vm_map_locked(map)) ||
1536 	    sx_try_upgrade(&map->lock)) {
1537 		/*
1538 		 * Splay requires a write lock on the map.  However, it only
1539 		 * restructures the binary search tree; it does not otherwise
1540 		 * change the map.  Thus, the map's timestamp need not change
1541 		 * on a temporary upgrade.
1542 		 */
1543 		cur = vm_map_splay(map, address);
1544 		if (!locked) {
1545 			VM_MAP_UNLOCK_CONSISTENT(map);
1546 			sx_downgrade(&map->lock);
1547 		}
1548 
1549 		/*
1550 		 * If "address" is contained within a map entry, the new root
1551 		 * is that map entry.  Otherwise, the new root is a map entry
1552 		 * immediately before or after "address".
1553 		 */
1554 		if (address < cur->start) {
1555 			*entry = header;
1556 			return (FALSE);
1557 		}
1558 		*entry = cur;
1559 		return (address < cur->end);
1560 	}
1561 	/*
1562 	 * Since the map is only locked for read access, perform a
1563 	 * standard binary search tree lookup for "address".
1564 	 */
1565 	lbound = ubound = header;
1566 	for (;;) {
1567 		if (address < cur->start) {
1568 			ubound = cur;
1569 			cur = cur->left;
1570 			if (cur == lbound)
1571 				break;
1572 		} else if (cur->end <= address) {
1573 			lbound = cur;
1574 			cur = cur->right;
1575 			if (cur == ubound)
1576 				break;
1577 		} else {
1578 			*entry = cur;
1579 			return (TRUE);
1580 		}
1581 	}
1582 	*entry = lbound;
1583 	return (FALSE);
1584 }
1585 
1586 /*
1587  *	vm_map_insert:
1588  *
1589  *	Inserts the given whole VM object into the target
1590  *	map at the specified address range.  The object's
1591  *	size should match that of the address range.
1592  *
1593  *	Requires that the map be locked, and leaves it so.
1594  *
1595  *	If object is non-NULL, ref count must be bumped by caller
1596  *	prior to making call to account for the new entry.
1597  */
1598 int
1599 vm_map_insert(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1600     vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max, int cow)
1601 {
1602 	vm_map_entry_t new_entry, next_entry, prev_entry;
1603 	struct ucred *cred;
1604 	vm_eflags_t protoeflags;
1605 	vm_inherit_t inheritance;
1606 
1607 	VM_MAP_ASSERT_LOCKED(map);
1608 	KASSERT(object != kernel_object ||
1609 	    (cow & MAP_COPY_ON_WRITE) == 0,
1610 	    ("vm_map_insert: kernel object and COW"));
1611 	KASSERT(object == NULL || (cow & MAP_NOFAULT) == 0,
1612 	    ("vm_map_insert: paradoxical MAP_NOFAULT request"));
1613 	KASSERT((prot & ~max) == 0,
1614 	    ("prot %#x is not subset of max_prot %#x", prot, max));
1615 
1616 	/*
1617 	 * Check that the start and end points are not bogus.
1618 	 */
1619 	if (start < vm_map_min(map) || end > vm_map_max(map) ||
1620 	    start >= end)
1621 		return (KERN_INVALID_ADDRESS);
1622 
1623 	/*
1624 	 * Find the entry prior to the proposed starting address; if it's part
1625 	 * of an existing entry, this range is bogus.
1626 	 */
1627 	if (vm_map_lookup_entry(map, start, &prev_entry))
1628 		return (KERN_NO_SPACE);
1629 
1630 	/*
1631 	 * Assert that the next entry doesn't overlap the end point.
1632 	 */
1633 	next_entry = vm_map_entry_succ(prev_entry);
1634 	if (next_entry->start < end)
1635 		return (KERN_NO_SPACE);
1636 
1637 	if ((cow & MAP_CREATE_GUARD) != 0 && (object != NULL ||
1638 	    max != VM_PROT_NONE))
1639 		return (KERN_INVALID_ARGUMENT);
1640 
1641 	protoeflags = 0;
1642 	if (cow & MAP_COPY_ON_WRITE)
1643 		protoeflags |= MAP_ENTRY_COW | MAP_ENTRY_NEEDS_COPY;
1644 	if (cow & MAP_NOFAULT)
1645 		protoeflags |= MAP_ENTRY_NOFAULT;
1646 	if (cow & MAP_DISABLE_SYNCER)
1647 		protoeflags |= MAP_ENTRY_NOSYNC;
1648 	if (cow & MAP_DISABLE_COREDUMP)
1649 		protoeflags |= MAP_ENTRY_NOCOREDUMP;
1650 	if (cow & MAP_STACK_GROWS_DOWN)
1651 		protoeflags |= MAP_ENTRY_GROWS_DOWN;
1652 	if (cow & MAP_STACK_GROWS_UP)
1653 		protoeflags |= MAP_ENTRY_GROWS_UP;
1654 	if (cow & MAP_WRITECOUNT)
1655 		protoeflags |= MAP_ENTRY_WRITECNT;
1656 	if (cow & MAP_VN_EXEC)
1657 		protoeflags |= MAP_ENTRY_VN_EXEC;
1658 	if ((cow & MAP_CREATE_GUARD) != 0)
1659 		protoeflags |= MAP_ENTRY_GUARD;
1660 	if ((cow & MAP_CREATE_STACK_GAP_DN) != 0)
1661 		protoeflags |= MAP_ENTRY_STACK_GAP_DN;
1662 	if ((cow & MAP_CREATE_STACK_GAP_UP) != 0)
1663 		protoeflags |= MAP_ENTRY_STACK_GAP_UP;
1664 	if (cow & MAP_INHERIT_SHARE)
1665 		inheritance = VM_INHERIT_SHARE;
1666 	else
1667 		inheritance = VM_INHERIT_DEFAULT;
1668 
1669 	cred = NULL;
1670 	if ((cow & (MAP_ACC_NO_CHARGE | MAP_NOFAULT | MAP_CREATE_GUARD)) != 0)
1671 		goto charged;
1672 	if ((cow & MAP_ACC_CHARGED) || ((prot & VM_PROT_WRITE) &&
1673 	    ((protoeflags & MAP_ENTRY_NEEDS_COPY) || object == NULL))) {
1674 		if (!(cow & MAP_ACC_CHARGED) && !swap_reserve(end - start))
1675 			return (KERN_RESOURCE_SHORTAGE);
1676 		KASSERT(object == NULL ||
1677 		    (protoeflags & MAP_ENTRY_NEEDS_COPY) != 0 ||
1678 		    object->cred == NULL,
1679 		    ("overcommit: vm_map_insert o %p", object));
1680 		cred = curthread->td_ucred;
1681 	}
1682 
1683 charged:
1684 	/* Expand the kernel pmap, if necessary. */
1685 	if (map == kernel_map && end > kernel_vm_end)
1686 		pmap_growkernel(end);
1687 	if (object != NULL) {
1688 		/*
1689 		 * OBJ_ONEMAPPING must be cleared unless this mapping
1690 		 * is trivially proven to be the only mapping for any
1691 		 * of the object's pages.  (Object granularity
1692 		 * reference counting is insufficient to recognize
1693 		 * aliases with precision.)
1694 		 */
1695 		if ((object->flags & OBJ_ANON) != 0) {
1696 			VM_OBJECT_WLOCK(object);
1697 			if (object->ref_count > 1 || object->shadow_count != 0)
1698 				vm_object_clear_flag(object, OBJ_ONEMAPPING);
1699 			VM_OBJECT_WUNLOCK(object);
1700 		}
1701 	} else if ((prev_entry->eflags & ~MAP_ENTRY_USER_WIRED) ==
1702 	    protoeflags &&
1703 	    (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP |
1704 	    MAP_VN_EXEC)) == 0 &&
1705 	    prev_entry->end == start && (prev_entry->cred == cred ||
1706 	    (prev_entry->object.vm_object != NULL &&
1707 	    prev_entry->object.vm_object->cred == cred)) &&
1708 	    vm_object_coalesce(prev_entry->object.vm_object,
1709 	    prev_entry->offset,
1710 	    (vm_size_t)(prev_entry->end - prev_entry->start),
1711 	    (vm_size_t)(end - prev_entry->end), cred != NULL &&
1712 	    (protoeflags & MAP_ENTRY_NEEDS_COPY) == 0)) {
1713 		/*
1714 		 * We were able to extend the object.  Determine if we
1715 		 * can extend the previous map entry to include the
1716 		 * new range as well.
1717 		 */
1718 		if (prev_entry->inheritance == inheritance &&
1719 		    prev_entry->protection == prot &&
1720 		    prev_entry->max_protection == max &&
1721 		    prev_entry->wired_count == 0) {
1722 			KASSERT((prev_entry->eflags & MAP_ENTRY_USER_WIRED) ==
1723 			    0, ("prev_entry %p has incoherent wiring",
1724 			    prev_entry));
1725 			if ((prev_entry->eflags & MAP_ENTRY_GUARD) == 0)
1726 				map->size += end - prev_entry->end;
1727 			vm_map_entry_resize(map, prev_entry,
1728 			    end - prev_entry->end);
1729 			vm_map_try_merge_entries(map, prev_entry, next_entry);
1730 			return (KERN_SUCCESS);
1731 		}
1732 
1733 		/*
1734 		 * If we can extend the object but cannot extend the
1735 		 * map entry, we have to create a new map entry.  We
1736 		 * must bump the ref count on the extended object to
1737 		 * account for it.  object may be NULL.
1738 		 */
1739 		object = prev_entry->object.vm_object;
1740 		offset = prev_entry->offset +
1741 		    (prev_entry->end - prev_entry->start);
1742 		vm_object_reference(object);
1743 		if (cred != NULL && object != NULL && object->cred != NULL &&
1744 		    !(prev_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
1745 			/* Object already accounts for this uid. */
1746 			cred = NULL;
1747 		}
1748 	}
1749 	if (cred != NULL)
1750 		crhold(cred);
1751 
1752 	/*
1753 	 * Create a new entry
1754 	 */
1755 	new_entry = vm_map_entry_create(map);
1756 	new_entry->start = start;
1757 	new_entry->end = end;
1758 	new_entry->cred = NULL;
1759 
1760 	new_entry->eflags = protoeflags;
1761 	new_entry->object.vm_object = object;
1762 	new_entry->offset = offset;
1763 
1764 	new_entry->inheritance = inheritance;
1765 	new_entry->protection = prot;
1766 	new_entry->max_protection = max;
1767 	new_entry->wired_count = 0;
1768 	new_entry->wiring_thread = NULL;
1769 	new_entry->read_ahead = VM_FAULT_READ_AHEAD_INIT;
1770 	new_entry->next_read = start;
1771 
1772 	KASSERT(cred == NULL || !ENTRY_CHARGED(new_entry),
1773 	    ("overcommit: vm_map_insert leaks vm_map %p", new_entry));
1774 	new_entry->cred = cred;
1775 
1776 	/*
1777 	 * Insert the new entry into the list
1778 	 */
1779 	vm_map_entry_link(map, new_entry);
1780 	if ((new_entry->eflags & MAP_ENTRY_GUARD) == 0)
1781 		map->size += new_entry->end - new_entry->start;
1782 
1783 	/*
1784 	 * Try to coalesce the new entry with both the previous and next
1785 	 * entries in the list.  Previously, we only attempted to coalesce
1786 	 * with the previous entry when object is NULL.  Here, we handle the
1787 	 * other cases, which are less common.
1788 	 */
1789 	vm_map_try_merge_entries(map, prev_entry, new_entry);
1790 	vm_map_try_merge_entries(map, new_entry, next_entry);
1791 
1792 	if ((cow & (MAP_PREFAULT | MAP_PREFAULT_PARTIAL)) != 0) {
1793 		vm_map_pmap_enter(map, start, prot, object, OFF_TO_IDX(offset),
1794 		    end - start, cow & MAP_PREFAULT_PARTIAL);
1795 	}
1796 
1797 	return (KERN_SUCCESS);
1798 }
1799 
1800 /*
1801  *	vm_map_findspace:
1802  *
1803  *	Find the first fit (lowest VM address) for "length" free bytes
1804  *	beginning at address >= start in the given map.
1805  *
1806  *	In a vm_map_entry, "max_free" is the maximum amount of
1807  *	contiguous free space between an entry in its subtree and a
1808  *	neighbor of that entry.  This allows finding a free region in
1809  *	one path down the tree, so O(log n) amortized with splay
1810  *	trees.
1811  *
1812  *	The map must be locked, and leaves it so.
1813  *
1814  *	Returns: starting address if sufficient space,
1815  *		 vm_map_max(map)-length+1 if insufficient space.
1816  */
1817 vm_offset_t
1818 vm_map_findspace(vm_map_t map, vm_offset_t start, vm_size_t length)
1819 {
1820 	vm_map_entry_t header, llist, rlist, root, y;
1821 	vm_size_t left_length, max_free_left, max_free_right;
1822 	vm_offset_t gap_end;
1823 
1824 	/*
1825 	 * Request must fit within min/max VM address and must avoid
1826 	 * address wrap.
1827 	 */
1828 	start = MAX(start, vm_map_min(map));
1829 	if (start >= vm_map_max(map) || length > vm_map_max(map) - start)
1830 		return (vm_map_max(map) - length + 1);
1831 
1832 	/* Empty tree means wide open address space. */
1833 	if (map->root == NULL)
1834 		return (start);
1835 
1836 	/*
1837 	 * After splay_split, if start is within an entry, push it to the start
1838 	 * of the following gap.  If rlist is at the end of the gap containing
1839 	 * start, save the end of that gap in gap_end to see if the gap is big
1840 	 * enough; otherwise set gap_end to start skip gap-checking and move
1841 	 * directly to a search of the right subtree.
1842 	 */
1843 	header = &map->header;
1844 	root = vm_map_splay_split(map, start, length, &llist, &rlist);
1845 	gap_end = rlist->start;
1846 	if (root != NULL) {
1847 		start = root->end;
1848 		if (root->right != rlist)
1849 			gap_end = start;
1850 		max_free_left = vm_map_splay_merge_left(header, root, llist);
1851 		max_free_right = vm_map_splay_merge_right(header, root, rlist);
1852 	} else if (rlist != header) {
1853 		root = rlist;
1854 		rlist = root->left;
1855 		max_free_left = vm_map_splay_merge_pred(header, root, llist);
1856 		max_free_right = vm_map_splay_merge_right(header, root, rlist);
1857 	} else {
1858 		root = llist;
1859 		llist = root->right;
1860 		max_free_left = vm_map_splay_merge_left(header, root, llist);
1861 		max_free_right = vm_map_splay_merge_succ(header, root, rlist);
1862 	}
1863 	root->max_free = vm_size_max(max_free_left, max_free_right);
1864 	map->root = root;
1865 	VM_MAP_ASSERT_CONSISTENT(map);
1866 	if (length <= gap_end - start)
1867 		return (start);
1868 
1869 	/* With max_free, can immediately tell if no solution. */
1870 	if (root->right == header || length > root->right->max_free)
1871 		return (vm_map_max(map) - length + 1);
1872 
1873 	/*
1874 	 * Splay for the least large-enough gap in the right subtree.
1875 	 */
1876 	llist = rlist = header;
1877 	for (left_length = 0;;
1878 	    left_length = vm_map_entry_max_free_left(root, llist)) {
1879 		if (length <= left_length)
1880 			SPLAY_LEFT_STEP(root, y, llist, rlist,
1881 			    length <= vm_map_entry_max_free_left(y, llist));
1882 		else
1883 			SPLAY_RIGHT_STEP(root, y, llist, rlist,
1884 			    length > vm_map_entry_max_free_left(y, root));
1885 		if (root == NULL)
1886 			break;
1887 	}
1888 	root = llist;
1889 	llist = root->right;
1890 	max_free_left = vm_map_splay_merge_left(header, root, llist);
1891 	if (rlist == header) {
1892 		root->max_free = vm_size_max(max_free_left,
1893 		    vm_map_splay_merge_succ(header, root, rlist));
1894 	} else {
1895 		y = rlist;
1896 		rlist = y->left;
1897 		y->max_free = vm_size_max(
1898 		    vm_map_splay_merge_pred(root, y, root),
1899 		    vm_map_splay_merge_right(header, y, rlist));
1900 		root->max_free = vm_size_max(max_free_left, y->max_free);
1901 	}
1902 	map->root = root;
1903 	VM_MAP_ASSERT_CONSISTENT(map);
1904 	return (root->end);
1905 }
1906 
1907 int
1908 vm_map_fixed(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1909     vm_offset_t start, vm_size_t length, vm_prot_t prot,
1910     vm_prot_t max, int cow)
1911 {
1912 	vm_offset_t end;
1913 	int result;
1914 
1915 	end = start + length;
1916 	KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
1917 	    object == NULL,
1918 	    ("vm_map_fixed: non-NULL backing object for stack"));
1919 	vm_map_lock(map);
1920 	VM_MAP_RANGE_CHECK(map, start, end);
1921 	if ((cow & MAP_CHECK_EXCL) == 0)
1922 		vm_map_delete(map, start, end);
1923 	if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
1924 		result = vm_map_stack_locked(map, start, length, sgrowsiz,
1925 		    prot, max, cow);
1926 	} else {
1927 		result = vm_map_insert(map, object, offset, start, end,
1928 		    prot, max, cow);
1929 	}
1930 	vm_map_unlock(map);
1931 	return (result);
1932 }
1933 
1934 static const int aslr_pages_rnd_64[2] = {0x1000, 0x10};
1935 static const int aslr_pages_rnd_32[2] = {0x100, 0x4};
1936 
1937 static int cluster_anon = 1;
1938 SYSCTL_INT(_vm, OID_AUTO, cluster_anon, CTLFLAG_RW,
1939     &cluster_anon, 0,
1940     "Cluster anonymous mappings: 0 = no, 1 = yes if no hint, 2 = always");
1941 
1942 static bool
1943 clustering_anon_allowed(vm_offset_t addr)
1944 {
1945 
1946 	switch (cluster_anon) {
1947 	case 0:
1948 		return (false);
1949 	case 1:
1950 		return (addr == 0);
1951 	case 2:
1952 	default:
1953 		return (true);
1954 	}
1955 }
1956 
1957 static long aslr_restarts;
1958 SYSCTL_LONG(_vm, OID_AUTO, aslr_restarts, CTLFLAG_RD,
1959     &aslr_restarts, 0,
1960     "Number of aslr failures");
1961 
1962 #define	MAP_32BIT_MAX_ADDR	((vm_offset_t)1 << 31)
1963 
1964 /*
1965  * Searches for the specified amount of free space in the given map with the
1966  * specified alignment.  Performs an address-ordered, first-fit search from
1967  * the given address "*addr", with an optional upper bound "max_addr".  If the
1968  * parameter "alignment" is zero, then the alignment is computed from the
1969  * given (object, offset) pair so as to enable the greatest possible use of
1970  * superpage mappings.  Returns KERN_SUCCESS and the address of the free space
1971  * in "*addr" if successful.  Otherwise, returns KERN_NO_SPACE.
1972  *
1973  * The map must be locked.  Initially, there must be at least "length" bytes
1974  * of free space at the given address.
1975  */
1976 static int
1977 vm_map_alignspace(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1978     vm_offset_t *addr, vm_size_t length, vm_offset_t max_addr,
1979     vm_offset_t alignment)
1980 {
1981 	vm_offset_t aligned_addr, free_addr;
1982 
1983 	VM_MAP_ASSERT_LOCKED(map);
1984 	free_addr = *addr;
1985 	KASSERT(free_addr == vm_map_findspace(map, free_addr, length),
1986 	    ("caller failed to provide space %#jx at address %p",
1987 	     (uintmax_t)length, (void *)free_addr));
1988 	for (;;) {
1989 		/*
1990 		 * At the start of every iteration, the free space at address
1991 		 * "*addr" is at least "length" bytes.
1992 		 */
1993 		if (alignment == 0)
1994 			pmap_align_superpage(object, offset, addr, length);
1995 		else if ((*addr & (alignment - 1)) != 0) {
1996 			*addr &= ~(alignment - 1);
1997 			*addr += alignment;
1998 		}
1999 		aligned_addr = *addr;
2000 		if (aligned_addr == free_addr) {
2001 			/*
2002 			 * Alignment did not change "*addr", so "*addr" must
2003 			 * still provide sufficient free space.
2004 			 */
2005 			return (KERN_SUCCESS);
2006 		}
2007 
2008 		/*
2009 		 * Test for address wrap on "*addr".  A wrapped "*addr" could
2010 		 * be a valid address, in which case vm_map_findspace() cannot
2011 		 * be relied upon to fail.
2012 		 */
2013 		if (aligned_addr < free_addr)
2014 			return (KERN_NO_SPACE);
2015 		*addr = vm_map_findspace(map, aligned_addr, length);
2016 		if (*addr + length > vm_map_max(map) ||
2017 		    (max_addr != 0 && *addr + length > max_addr))
2018 			return (KERN_NO_SPACE);
2019 		free_addr = *addr;
2020 		if (free_addr == aligned_addr) {
2021 			/*
2022 			 * If a successful call to vm_map_findspace() did not
2023 			 * change "*addr", then "*addr" must still be aligned
2024 			 * and provide sufficient free space.
2025 			 */
2026 			return (KERN_SUCCESS);
2027 		}
2028 	}
2029 }
2030 
2031 /*
2032  *	vm_map_find finds an unallocated region in the target address
2033  *	map with the given length.  The search is defined to be
2034  *	first-fit from the specified address; the region found is
2035  *	returned in the same parameter.
2036  *
2037  *	If object is non-NULL, ref count must be bumped by caller
2038  *	prior to making call to account for the new entry.
2039  */
2040 int
2041 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
2042 	    vm_offset_t *addr,	/* IN/OUT */
2043 	    vm_size_t length, vm_offset_t max_addr, int find_space,
2044 	    vm_prot_t prot, vm_prot_t max, int cow)
2045 {
2046 	vm_offset_t alignment, curr_min_addr, min_addr;
2047 	int gap, pidx, rv, try;
2048 	bool cluster, en_aslr, update_anon;
2049 
2050 	KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
2051 	    object == NULL,
2052 	    ("vm_map_find: non-NULL backing object for stack"));
2053 	MPASS((cow & MAP_REMAP) == 0 || (find_space == VMFS_NO_SPACE &&
2054 	    (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0));
2055 	if (find_space == VMFS_OPTIMAL_SPACE && (object == NULL ||
2056 	    (object->flags & OBJ_COLORED) == 0))
2057 		find_space = VMFS_ANY_SPACE;
2058 	if (find_space >> 8 != 0) {
2059 		KASSERT((find_space & 0xff) == 0, ("bad VMFS flags"));
2060 		alignment = (vm_offset_t)1 << (find_space >> 8);
2061 	} else
2062 		alignment = 0;
2063 	en_aslr = (map->flags & MAP_ASLR) != 0;
2064 	update_anon = cluster = clustering_anon_allowed(*addr) &&
2065 	    (map->flags & MAP_IS_SUB_MAP) == 0 && max_addr == 0 &&
2066 	    find_space != VMFS_NO_SPACE && object == NULL &&
2067 	    (cow & (MAP_INHERIT_SHARE | MAP_STACK_GROWS_UP |
2068 	    MAP_STACK_GROWS_DOWN)) == 0 && prot != PROT_NONE;
2069 	curr_min_addr = min_addr = *addr;
2070 	if (en_aslr && min_addr == 0 && !cluster &&
2071 	    find_space != VMFS_NO_SPACE &&
2072 	    (map->flags & MAP_ASLR_IGNSTART) != 0)
2073 		curr_min_addr = min_addr = vm_map_min(map);
2074 	try = 0;
2075 	vm_map_lock(map);
2076 	if (cluster) {
2077 		curr_min_addr = map->anon_loc;
2078 		if (curr_min_addr == 0)
2079 			cluster = false;
2080 	}
2081 	if (find_space != VMFS_NO_SPACE) {
2082 		KASSERT(find_space == VMFS_ANY_SPACE ||
2083 		    find_space == VMFS_OPTIMAL_SPACE ||
2084 		    find_space == VMFS_SUPER_SPACE ||
2085 		    alignment != 0, ("unexpected VMFS flag"));
2086 again:
2087 		/*
2088 		 * When creating an anonymous mapping, try clustering
2089 		 * with an existing anonymous mapping first.
2090 		 *
2091 		 * We make up to two attempts to find address space
2092 		 * for a given find_space value. The first attempt may
2093 		 * apply randomization or may cluster with an existing
2094 		 * anonymous mapping. If this first attempt fails,
2095 		 * perform a first-fit search of the available address
2096 		 * space.
2097 		 *
2098 		 * If all tries failed, and find_space is
2099 		 * VMFS_OPTIMAL_SPACE, fallback to VMFS_ANY_SPACE.
2100 		 * Again enable clustering and randomization.
2101 		 */
2102 		try++;
2103 		MPASS(try <= 2);
2104 
2105 		if (try == 2) {
2106 			/*
2107 			 * Second try: we failed either to find a
2108 			 * suitable region for randomizing the
2109 			 * allocation, or to cluster with an existing
2110 			 * mapping.  Retry with free run.
2111 			 */
2112 			curr_min_addr = (map->flags & MAP_ASLR_IGNSTART) != 0 ?
2113 			    vm_map_min(map) : min_addr;
2114 			atomic_add_long(&aslr_restarts, 1);
2115 		}
2116 
2117 		if (try == 1 && en_aslr && !cluster) {
2118 			/*
2119 			 * Find space for allocation, including
2120 			 * gap needed for later randomization.
2121 			 */
2122 			pidx = MAXPAGESIZES > 1 && pagesizes[1] != 0 &&
2123 			    (find_space == VMFS_SUPER_SPACE || find_space ==
2124 			    VMFS_OPTIMAL_SPACE) ? 1 : 0;
2125 			gap = vm_map_max(map) > MAP_32BIT_MAX_ADDR &&
2126 			    (max_addr == 0 || max_addr > MAP_32BIT_MAX_ADDR) ?
2127 			    aslr_pages_rnd_64[pidx] : aslr_pages_rnd_32[pidx];
2128 			*addr = vm_map_findspace(map, curr_min_addr,
2129 			    length + gap * pagesizes[pidx]);
2130 			if (*addr + length + gap * pagesizes[pidx] >
2131 			    vm_map_max(map))
2132 				goto again;
2133 			/* And randomize the start address. */
2134 			*addr += (arc4random() % gap) * pagesizes[pidx];
2135 			if (max_addr != 0 && *addr + length > max_addr)
2136 				goto again;
2137 		} else {
2138 			*addr = vm_map_findspace(map, curr_min_addr, length);
2139 			if (*addr + length > vm_map_max(map) ||
2140 			    (max_addr != 0 && *addr + length > max_addr)) {
2141 				if (cluster) {
2142 					cluster = false;
2143 					MPASS(try == 1);
2144 					goto again;
2145 				}
2146 				rv = KERN_NO_SPACE;
2147 				goto done;
2148 			}
2149 		}
2150 
2151 		if (find_space != VMFS_ANY_SPACE &&
2152 		    (rv = vm_map_alignspace(map, object, offset, addr, length,
2153 		    max_addr, alignment)) != KERN_SUCCESS) {
2154 			if (find_space == VMFS_OPTIMAL_SPACE) {
2155 				find_space = VMFS_ANY_SPACE;
2156 				curr_min_addr = min_addr;
2157 				cluster = update_anon;
2158 				try = 0;
2159 				goto again;
2160 			}
2161 			goto done;
2162 		}
2163 	} else if ((cow & MAP_REMAP) != 0) {
2164 		if (*addr < vm_map_min(map) ||
2165 		    *addr + length > vm_map_max(map) ||
2166 		    *addr + length <= length) {
2167 			rv = KERN_INVALID_ADDRESS;
2168 			goto done;
2169 		}
2170 		vm_map_delete(map, *addr, *addr + length);
2171 	}
2172 	if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
2173 		rv = vm_map_stack_locked(map, *addr, length, sgrowsiz, prot,
2174 		    max, cow);
2175 	} else {
2176 		rv = vm_map_insert(map, object, offset, *addr, *addr + length,
2177 		    prot, max, cow);
2178 	}
2179 	if (rv == KERN_SUCCESS && update_anon)
2180 		map->anon_loc = *addr + length;
2181 done:
2182 	vm_map_unlock(map);
2183 	return (rv);
2184 }
2185 
2186 /*
2187  *	vm_map_find_min() is a variant of vm_map_find() that takes an
2188  *	additional parameter (min_addr) and treats the given address
2189  *	(*addr) differently.  Specifically, it treats *addr as a hint
2190  *	and not as the minimum address where the mapping is created.
2191  *
2192  *	This function works in two phases.  First, it tries to
2193  *	allocate above the hint.  If that fails and the hint is
2194  *	greater than min_addr, it performs a second pass, replacing
2195  *	the hint with min_addr as the minimum address for the
2196  *	allocation.
2197  */
2198 int
2199 vm_map_find_min(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
2200     vm_offset_t *addr, vm_size_t length, vm_offset_t min_addr,
2201     vm_offset_t max_addr, int find_space, vm_prot_t prot, vm_prot_t max,
2202     int cow)
2203 {
2204 	vm_offset_t hint;
2205 	int rv;
2206 
2207 	hint = *addr;
2208 	for (;;) {
2209 		rv = vm_map_find(map, object, offset, addr, length, max_addr,
2210 		    find_space, prot, max, cow);
2211 		if (rv == KERN_SUCCESS || min_addr >= hint)
2212 			return (rv);
2213 		*addr = hint = min_addr;
2214 	}
2215 }
2216 
2217 /*
2218  * A map entry with any of the following flags set must not be merged with
2219  * another entry.
2220  */
2221 #define	MAP_ENTRY_NOMERGE_MASK	(MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP | \
2222 	    MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_IS_SUB_MAP | MAP_ENTRY_VN_EXEC)
2223 
2224 static bool
2225 vm_map_mergeable_neighbors(vm_map_entry_t prev, vm_map_entry_t entry)
2226 {
2227 
2228 	KASSERT((prev->eflags & MAP_ENTRY_NOMERGE_MASK) == 0 ||
2229 	    (entry->eflags & MAP_ENTRY_NOMERGE_MASK) == 0,
2230 	    ("vm_map_mergeable_neighbors: neither %p nor %p are mergeable",
2231 	    prev, entry));
2232 	return (prev->end == entry->start &&
2233 	    prev->object.vm_object == entry->object.vm_object &&
2234 	    (prev->object.vm_object == NULL ||
2235 	    prev->offset + (prev->end - prev->start) == entry->offset) &&
2236 	    prev->eflags == entry->eflags &&
2237 	    prev->protection == entry->protection &&
2238 	    prev->max_protection == entry->max_protection &&
2239 	    prev->inheritance == entry->inheritance &&
2240 	    prev->wired_count == entry->wired_count &&
2241 	    prev->cred == entry->cred);
2242 }
2243 
2244 static void
2245 vm_map_merged_neighbor_dispose(vm_map_t map, vm_map_entry_t entry)
2246 {
2247 
2248 	/*
2249 	 * If the backing object is a vnode object, vm_object_deallocate()
2250 	 * calls vrele().  However, vrele() does not lock the vnode because
2251 	 * the vnode has additional references.  Thus, the map lock can be
2252 	 * kept without causing a lock-order reversal with the vnode lock.
2253 	 *
2254 	 * Since we count the number of virtual page mappings in
2255 	 * object->un_pager.vnp.writemappings, the writemappings value
2256 	 * should not be adjusted when the entry is disposed of.
2257 	 */
2258 	if (entry->object.vm_object != NULL)
2259 		vm_object_deallocate(entry->object.vm_object);
2260 	if (entry->cred != NULL)
2261 		crfree(entry->cred);
2262 	vm_map_entry_dispose(map, entry);
2263 }
2264 
2265 /*
2266  *	vm_map_try_merge_entries:
2267  *
2268  *	Compare the given map entry to its predecessor, and merge its precessor
2269  *	into it if possible.  The entry remains valid, and may be extended.
2270  *	The predecessor may be deleted.
2271  *
2272  *	The map must be locked.
2273  */
2274 void
2275 vm_map_try_merge_entries(vm_map_t map, vm_map_entry_t prev_entry,
2276     vm_map_entry_t entry)
2277 {
2278 
2279 	VM_MAP_ASSERT_LOCKED(map);
2280 	if ((entry->eflags & MAP_ENTRY_NOMERGE_MASK) == 0 &&
2281 	    vm_map_mergeable_neighbors(prev_entry, entry)) {
2282 		vm_map_entry_unlink(map, prev_entry, UNLINK_MERGE_NEXT);
2283 		vm_map_merged_neighbor_dispose(map, prev_entry);
2284 	}
2285 }
2286 
2287 /*
2288  *	vm_map_entry_back:
2289  *
2290  *	Allocate an object to back a map entry.
2291  */
2292 static inline void
2293 vm_map_entry_back(vm_map_entry_t entry)
2294 {
2295 	vm_object_t object;
2296 
2297 	KASSERT(entry->object.vm_object == NULL,
2298 	    ("map entry %p has backing object", entry));
2299 	KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
2300 	    ("map entry %p is a submap", entry));
2301 	object = vm_object_allocate_anon(atop(entry->end - entry->start), NULL,
2302 	    entry->cred, entry->end - entry->start);
2303 	entry->object.vm_object = object;
2304 	entry->offset = 0;
2305 	entry->cred = NULL;
2306 }
2307 
2308 /*
2309  *	vm_map_entry_charge_object
2310  *
2311  *	If there is no object backing this entry, create one.  Otherwise, if
2312  *	the entry has cred, give it to the backing object.
2313  */
2314 static inline void
2315 vm_map_entry_charge_object(vm_map_t map, vm_map_entry_t entry)
2316 {
2317 
2318 	VM_MAP_ASSERT_LOCKED(map);
2319 	KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
2320 	    ("map entry %p is a submap", entry));
2321 	if (entry->object.vm_object == NULL && !map->system_map &&
2322 	    (entry->eflags & MAP_ENTRY_GUARD) == 0)
2323 		vm_map_entry_back(entry);
2324 	else if (entry->object.vm_object != NULL &&
2325 	    ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
2326 	    entry->cred != NULL) {
2327 		VM_OBJECT_WLOCK(entry->object.vm_object);
2328 		KASSERT(entry->object.vm_object->cred == NULL,
2329 		    ("OVERCOMMIT: %s: both cred e %p", __func__, entry));
2330 		entry->object.vm_object->cred = entry->cred;
2331 		entry->object.vm_object->charge = entry->end - entry->start;
2332 		VM_OBJECT_WUNLOCK(entry->object.vm_object);
2333 		entry->cred = NULL;
2334 	}
2335 }
2336 
2337 /*
2338  *	vm_map_entry_clone
2339  *
2340  *	Create a duplicate map entry for clipping.
2341  */
2342 static vm_map_entry_t
2343 vm_map_entry_clone(vm_map_t map, vm_map_entry_t entry)
2344 {
2345 	vm_map_entry_t new_entry;
2346 
2347 	VM_MAP_ASSERT_LOCKED(map);
2348 
2349 	/*
2350 	 * Create a backing object now, if none exists, so that more individual
2351 	 * objects won't be created after the map entry is split.
2352 	 */
2353 	vm_map_entry_charge_object(map, entry);
2354 
2355 	/* Clone the entry. */
2356 	new_entry = vm_map_entry_create(map);
2357 	*new_entry = *entry;
2358 	if (new_entry->cred != NULL)
2359 		crhold(entry->cred);
2360 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
2361 		vm_object_reference(new_entry->object.vm_object);
2362 		vm_map_entry_set_vnode_text(new_entry, true);
2363 		/*
2364 		 * The object->un_pager.vnp.writemappings for the object of
2365 		 * MAP_ENTRY_WRITECNT type entry shall be kept as is here.  The
2366 		 * virtual pages are re-distributed among the clipped entries,
2367 		 * so the sum is left the same.
2368 		 */
2369 	}
2370 	return (new_entry);
2371 }
2372 
2373 /*
2374  *	vm_map_clip_start:	[ internal use only ]
2375  *
2376  *	Asserts that the given entry begins at or after
2377  *	the specified address; if necessary,
2378  *	it splits the entry into two.
2379  */
2380 #define vm_map_clip_start(map, entry, startaddr) \
2381 { \
2382 	if (startaddr > entry->start) \
2383 		_vm_map_clip_start(map, entry, startaddr); \
2384 }
2385 
2386 /*
2387  *	This routine is called only when it is known that
2388  *	the entry must be split.
2389  */
2390 static void
2391 _vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t start)
2392 {
2393 	vm_map_entry_t new_entry;
2394 
2395 	VM_MAP_ASSERT_LOCKED(map);
2396 	KASSERT(entry->end > start && entry->start < start,
2397 	    ("_vm_map_clip_start: invalid clip of entry %p", entry));
2398 
2399 	new_entry = vm_map_entry_clone(map, entry);
2400 
2401 	/*
2402 	 * Split off the front portion.  Insert the new entry BEFORE this one,
2403 	 * so that this entry has the specified starting address.
2404 	 */
2405 	new_entry->end = start;
2406 	vm_map_entry_link(map, new_entry);
2407 }
2408 
2409 /*
2410  *	vm_map_clip_end:	[ internal use only ]
2411  *
2412  *	Asserts that the given entry ends at or before
2413  *	the specified address; if necessary,
2414  *	it splits the entry into two.
2415  */
2416 #define vm_map_clip_end(map, entry, endaddr) \
2417 { \
2418 	if ((endaddr) < (entry->end)) \
2419 		_vm_map_clip_end((map), (entry), (endaddr)); \
2420 }
2421 
2422 /*
2423  *	This routine is called only when it is known that
2424  *	the entry must be split.
2425  */
2426 static void
2427 _vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t end)
2428 {
2429 	vm_map_entry_t new_entry;
2430 
2431 	VM_MAP_ASSERT_LOCKED(map);
2432 	KASSERT(entry->start < end && entry->end > end,
2433 	    ("_vm_map_clip_end: invalid clip of entry %p", entry));
2434 
2435 	new_entry = vm_map_entry_clone(map, entry);
2436 
2437 	/*
2438 	 * Split off the back portion.  Insert the new entry AFTER this one,
2439 	 * so that this entry has the specified ending address.
2440 	 */
2441 	new_entry->start = end;
2442 	vm_map_entry_link(map, new_entry);
2443 }
2444 
2445 /*
2446  *	vm_map_submap:		[ kernel use only ]
2447  *
2448  *	Mark the given range as handled by a subordinate map.
2449  *
2450  *	This range must have been created with vm_map_find,
2451  *	and no other operations may have been performed on this
2452  *	range prior to calling vm_map_submap.
2453  *
2454  *	Only a limited number of operations can be performed
2455  *	within this rage after calling vm_map_submap:
2456  *		vm_fault
2457  *	[Don't try vm_map_copy!]
2458  *
2459  *	To remove a submapping, one must first remove the
2460  *	range from the superior map, and then destroy the
2461  *	submap (if desired).  [Better yet, don't try it.]
2462  */
2463 int
2464 vm_map_submap(
2465 	vm_map_t map,
2466 	vm_offset_t start,
2467 	vm_offset_t end,
2468 	vm_map_t submap)
2469 {
2470 	vm_map_entry_t entry;
2471 	int result;
2472 
2473 	result = KERN_INVALID_ARGUMENT;
2474 
2475 	vm_map_lock(submap);
2476 	submap->flags |= MAP_IS_SUB_MAP;
2477 	vm_map_unlock(submap);
2478 
2479 	vm_map_lock(map);
2480 
2481 	VM_MAP_RANGE_CHECK(map, start, end);
2482 
2483 	if (vm_map_lookup_entry(map, start, &entry)) {
2484 		vm_map_clip_start(map, entry, start);
2485 	} else
2486 		entry = vm_map_entry_succ(entry);
2487 
2488 	vm_map_clip_end(map, entry, end);
2489 
2490 	if ((entry->start == start) && (entry->end == end) &&
2491 	    ((entry->eflags & MAP_ENTRY_COW) == 0) &&
2492 	    (entry->object.vm_object == NULL)) {
2493 		entry->object.sub_map = submap;
2494 		entry->eflags |= MAP_ENTRY_IS_SUB_MAP;
2495 		result = KERN_SUCCESS;
2496 	}
2497 	vm_map_unlock(map);
2498 
2499 	if (result != KERN_SUCCESS) {
2500 		vm_map_lock(submap);
2501 		submap->flags &= ~MAP_IS_SUB_MAP;
2502 		vm_map_unlock(submap);
2503 	}
2504 	return (result);
2505 }
2506 
2507 /*
2508  * The maximum number of pages to map if MAP_PREFAULT_PARTIAL is specified
2509  */
2510 #define	MAX_INIT_PT	96
2511 
2512 /*
2513  *	vm_map_pmap_enter:
2514  *
2515  *	Preload the specified map's pmap with mappings to the specified
2516  *	object's memory-resident pages.  No further physical pages are
2517  *	allocated, and no further virtual pages are retrieved from secondary
2518  *	storage.  If the specified flags include MAP_PREFAULT_PARTIAL, then a
2519  *	limited number of page mappings are created at the low-end of the
2520  *	specified address range.  (For this purpose, a superpage mapping
2521  *	counts as one page mapping.)  Otherwise, all resident pages within
2522  *	the specified address range are mapped.
2523  */
2524 static void
2525 vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
2526     vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags)
2527 {
2528 	vm_offset_t start;
2529 	vm_page_t p, p_start;
2530 	vm_pindex_t mask, psize, threshold, tmpidx;
2531 
2532 	if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0 || object == NULL)
2533 		return;
2534 	if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
2535 		VM_OBJECT_WLOCK(object);
2536 		if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
2537 			pmap_object_init_pt(map->pmap, addr, object, pindex,
2538 			    size);
2539 			VM_OBJECT_WUNLOCK(object);
2540 			return;
2541 		}
2542 		VM_OBJECT_LOCK_DOWNGRADE(object);
2543 	} else
2544 		VM_OBJECT_RLOCK(object);
2545 
2546 	psize = atop(size);
2547 	if (psize + pindex > object->size) {
2548 		if (pindex >= object->size) {
2549 			VM_OBJECT_RUNLOCK(object);
2550 			return;
2551 		}
2552 		psize = object->size - pindex;
2553 	}
2554 
2555 	start = 0;
2556 	p_start = NULL;
2557 	threshold = MAX_INIT_PT;
2558 
2559 	p = vm_page_find_least(object, pindex);
2560 	/*
2561 	 * Assert: the variable p is either (1) the page with the
2562 	 * least pindex greater than or equal to the parameter pindex
2563 	 * or (2) NULL.
2564 	 */
2565 	for (;
2566 	     p != NULL && (tmpidx = p->pindex - pindex) < psize;
2567 	     p = TAILQ_NEXT(p, listq)) {
2568 		/*
2569 		 * don't allow an madvise to blow away our really
2570 		 * free pages allocating pv entries.
2571 		 */
2572 		if (((flags & MAP_PREFAULT_MADVISE) != 0 &&
2573 		    vm_page_count_severe()) ||
2574 		    ((flags & MAP_PREFAULT_PARTIAL) != 0 &&
2575 		    tmpidx >= threshold)) {
2576 			psize = tmpidx;
2577 			break;
2578 		}
2579 		if (vm_page_all_valid(p)) {
2580 			if (p_start == NULL) {
2581 				start = addr + ptoa(tmpidx);
2582 				p_start = p;
2583 			}
2584 			/* Jump ahead if a superpage mapping is possible. */
2585 			if (p->psind > 0 && ((addr + ptoa(tmpidx)) &
2586 			    (pagesizes[p->psind] - 1)) == 0) {
2587 				mask = atop(pagesizes[p->psind]) - 1;
2588 				if (tmpidx + mask < psize &&
2589 				    vm_page_ps_test(p, PS_ALL_VALID, NULL)) {
2590 					p += mask;
2591 					threshold += mask;
2592 				}
2593 			}
2594 		} else if (p_start != NULL) {
2595 			pmap_enter_object(map->pmap, start, addr +
2596 			    ptoa(tmpidx), p_start, prot);
2597 			p_start = NULL;
2598 		}
2599 	}
2600 	if (p_start != NULL)
2601 		pmap_enter_object(map->pmap, start, addr + ptoa(psize),
2602 		    p_start, prot);
2603 	VM_OBJECT_RUNLOCK(object);
2604 }
2605 
2606 /*
2607  *	vm_map_protect:
2608  *
2609  *	Sets the protection of the specified address
2610  *	region in the target map.  If "set_max" is
2611  *	specified, the maximum protection is to be set;
2612  *	otherwise, only the current protection is affected.
2613  */
2614 int
2615 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
2616 	       vm_prot_t new_prot, boolean_t set_max)
2617 {
2618 	vm_map_entry_t entry, first_entry, in_tran, prev_entry;
2619 	vm_object_t obj;
2620 	struct ucred *cred;
2621 	vm_prot_t old_prot;
2622 	int rv;
2623 
2624 	if (start == end)
2625 		return (KERN_SUCCESS);
2626 
2627 again:
2628 	in_tran = NULL;
2629 	vm_map_lock(map);
2630 
2631 	/*
2632 	 * Ensure that we are not concurrently wiring pages.  vm_map_wire() may
2633 	 * need to fault pages into the map and will drop the map lock while
2634 	 * doing so, and the VM object may end up in an inconsistent state if we
2635 	 * update the protection on the map entry in between faults.
2636 	 */
2637 	vm_map_wait_busy(map);
2638 
2639 	VM_MAP_RANGE_CHECK(map, start, end);
2640 
2641 	if (!vm_map_lookup_entry(map, start, &first_entry))
2642 		first_entry = vm_map_entry_succ(first_entry);
2643 
2644 	/*
2645 	 * Make a first pass to check for protection violations.
2646 	 */
2647 	for (entry = first_entry; entry->start < end;
2648 	    entry = vm_map_entry_succ(entry)) {
2649 		if ((entry->eflags & MAP_ENTRY_GUARD) != 0)
2650 			continue;
2651 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0) {
2652 			vm_map_unlock(map);
2653 			return (KERN_INVALID_ARGUMENT);
2654 		}
2655 		if ((new_prot & entry->max_protection) != new_prot) {
2656 			vm_map_unlock(map);
2657 			return (KERN_PROTECTION_FAILURE);
2658 		}
2659 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0)
2660 			in_tran = entry;
2661 	}
2662 
2663 	/*
2664 	 * Postpone the operation until all in-transition map entries have
2665 	 * stabilized.  An in-transition entry might already have its pages
2666 	 * wired and wired_count incremented, but not yet have its
2667 	 * MAP_ENTRY_USER_WIRED flag set.  In which case, we would fail to call
2668 	 * vm_fault_copy_entry() in the final loop below.
2669 	 */
2670 	if (in_tran != NULL) {
2671 		in_tran->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2672 		vm_map_unlock_and_wait(map, 0);
2673 		goto again;
2674 	}
2675 
2676 	/*
2677 	 * Before changing the protections, try to reserve swap space for any
2678 	 * private (i.e., copy-on-write) mappings that are transitioning from
2679 	 * read-only to read/write access.  If a reservation fails, break out
2680 	 * of this loop early and let the next loop simplify the entries, since
2681 	 * some may now be mergeable.
2682 	 */
2683 	rv = KERN_SUCCESS;
2684 	vm_map_clip_start(map, first_entry, start);
2685 	for (entry = first_entry; entry->start < end;
2686 	    entry = vm_map_entry_succ(entry)) {
2687 		vm_map_clip_end(map, entry, end);
2688 
2689 		if (set_max ||
2690 		    ((new_prot & ~entry->protection) & VM_PROT_WRITE) == 0 ||
2691 		    ENTRY_CHARGED(entry) ||
2692 		    (entry->eflags & MAP_ENTRY_GUARD) != 0) {
2693 			continue;
2694 		}
2695 
2696 		cred = curthread->td_ucred;
2697 		obj = entry->object.vm_object;
2698 
2699 		if (obj == NULL ||
2700 		    (entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0) {
2701 			if (!swap_reserve(entry->end - entry->start)) {
2702 				rv = KERN_RESOURCE_SHORTAGE;
2703 				end = entry->end;
2704 				break;
2705 			}
2706 			crhold(cred);
2707 			entry->cred = cred;
2708 			continue;
2709 		}
2710 
2711 		if (obj->type != OBJT_DEFAULT && obj->type != OBJT_SWAP)
2712 			continue;
2713 		VM_OBJECT_WLOCK(obj);
2714 		if (obj->type != OBJT_DEFAULT && obj->type != OBJT_SWAP) {
2715 			VM_OBJECT_WUNLOCK(obj);
2716 			continue;
2717 		}
2718 
2719 		/*
2720 		 * Charge for the whole object allocation now, since
2721 		 * we cannot distinguish between non-charged and
2722 		 * charged clipped mapping of the same object later.
2723 		 */
2724 		KASSERT(obj->charge == 0,
2725 		    ("vm_map_protect: object %p overcharged (entry %p)",
2726 		    obj, entry));
2727 		if (!swap_reserve(ptoa(obj->size))) {
2728 			VM_OBJECT_WUNLOCK(obj);
2729 			rv = KERN_RESOURCE_SHORTAGE;
2730 			end = entry->end;
2731 			break;
2732 		}
2733 
2734 		crhold(cred);
2735 		obj->cred = cred;
2736 		obj->charge = ptoa(obj->size);
2737 		VM_OBJECT_WUNLOCK(obj);
2738 	}
2739 
2740 	/*
2741 	 * If enough swap space was available, go back and fix up protections.
2742 	 * Otherwise, just simplify entries, since some may have been modified.
2743 	 * [Note that clipping is not necessary the second time.]
2744 	 */
2745 	for (prev_entry = vm_map_entry_pred(first_entry), entry = first_entry;
2746 	    entry->start < end;
2747 	    vm_map_try_merge_entries(map, prev_entry, entry),
2748 	    prev_entry = entry, entry = vm_map_entry_succ(entry)) {
2749 		if (rv != KERN_SUCCESS ||
2750 		    (entry->eflags & MAP_ENTRY_GUARD) != 0)
2751 			continue;
2752 
2753 		old_prot = entry->protection;
2754 
2755 		if (set_max)
2756 			entry->protection =
2757 			    (entry->max_protection = new_prot) &
2758 			    old_prot;
2759 		else
2760 			entry->protection = new_prot;
2761 
2762 		/*
2763 		 * For user wired map entries, the normal lazy evaluation of
2764 		 * write access upgrades through soft page faults is
2765 		 * undesirable.  Instead, immediately copy any pages that are
2766 		 * copy-on-write and enable write access in the physical map.
2767 		 */
2768 		if ((entry->eflags & MAP_ENTRY_USER_WIRED) != 0 &&
2769 		    (entry->protection & VM_PROT_WRITE) != 0 &&
2770 		    (old_prot & VM_PROT_WRITE) == 0)
2771 			vm_fault_copy_entry(map, map, entry, entry, NULL);
2772 
2773 		/*
2774 		 * When restricting access, update the physical map.  Worry
2775 		 * about copy-on-write here.
2776 		 */
2777 		if ((old_prot & ~entry->protection) != 0) {
2778 #define MASK(entry)	(((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
2779 							VM_PROT_ALL)
2780 			pmap_protect(map->pmap, entry->start,
2781 			    entry->end,
2782 			    entry->protection & MASK(entry));
2783 #undef	MASK
2784 		}
2785 	}
2786 	vm_map_try_merge_entries(map, prev_entry, entry);
2787 	vm_map_unlock(map);
2788 	return (rv);
2789 }
2790 
2791 /*
2792  *	vm_map_madvise:
2793  *
2794  *	This routine traverses a processes map handling the madvise
2795  *	system call.  Advisories are classified as either those effecting
2796  *	the vm_map_entry structure, or those effecting the underlying
2797  *	objects.
2798  */
2799 int
2800 vm_map_madvise(
2801 	vm_map_t map,
2802 	vm_offset_t start,
2803 	vm_offset_t end,
2804 	int behav)
2805 {
2806 	vm_map_entry_t entry, prev_entry;
2807 	bool modify_map;
2808 
2809 	/*
2810 	 * Some madvise calls directly modify the vm_map_entry, in which case
2811 	 * we need to use an exclusive lock on the map and we need to perform
2812 	 * various clipping operations.  Otherwise we only need a read-lock
2813 	 * on the map.
2814 	 */
2815 	switch(behav) {
2816 	case MADV_NORMAL:
2817 	case MADV_SEQUENTIAL:
2818 	case MADV_RANDOM:
2819 	case MADV_NOSYNC:
2820 	case MADV_AUTOSYNC:
2821 	case MADV_NOCORE:
2822 	case MADV_CORE:
2823 		if (start == end)
2824 			return (0);
2825 		modify_map = true;
2826 		vm_map_lock(map);
2827 		break;
2828 	case MADV_WILLNEED:
2829 	case MADV_DONTNEED:
2830 	case MADV_FREE:
2831 		if (start == end)
2832 			return (0);
2833 		modify_map = false;
2834 		vm_map_lock_read(map);
2835 		break;
2836 	default:
2837 		return (EINVAL);
2838 	}
2839 
2840 	/*
2841 	 * Locate starting entry and clip if necessary.
2842 	 */
2843 	VM_MAP_RANGE_CHECK(map, start, end);
2844 
2845 	if (vm_map_lookup_entry(map, start, &entry)) {
2846 		if (modify_map)
2847 			vm_map_clip_start(map, entry, start);
2848 		prev_entry = vm_map_entry_pred(entry);
2849 	} else {
2850 		prev_entry = entry;
2851 		entry = vm_map_entry_succ(entry);
2852 	}
2853 
2854 	if (modify_map) {
2855 		/*
2856 		 * madvise behaviors that are implemented in the vm_map_entry.
2857 		 *
2858 		 * We clip the vm_map_entry so that behavioral changes are
2859 		 * limited to the specified address range.
2860 		 */
2861 		for (; entry->start < end;
2862 		     prev_entry = entry, entry = vm_map_entry_succ(entry)) {
2863 			if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2864 				continue;
2865 
2866 			vm_map_clip_end(map, entry, end);
2867 
2868 			switch (behav) {
2869 			case MADV_NORMAL:
2870 				vm_map_entry_set_behavior(entry,
2871 				    MAP_ENTRY_BEHAV_NORMAL);
2872 				break;
2873 			case MADV_SEQUENTIAL:
2874 				vm_map_entry_set_behavior(entry,
2875 				    MAP_ENTRY_BEHAV_SEQUENTIAL);
2876 				break;
2877 			case MADV_RANDOM:
2878 				vm_map_entry_set_behavior(entry,
2879 				    MAP_ENTRY_BEHAV_RANDOM);
2880 				break;
2881 			case MADV_NOSYNC:
2882 				entry->eflags |= MAP_ENTRY_NOSYNC;
2883 				break;
2884 			case MADV_AUTOSYNC:
2885 				entry->eflags &= ~MAP_ENTRY_NOSYNC;
2886 				break;
2887 			case MADV_NOCORE:
2888 				entry->eflags |= MAP_ENTRY_NOCOREDUMP;
2889 				break;
2890 			case MADV_CORE:
2891 				entry->eflags &= ~MAP_ENTRY_NOCOREDUMP;
2892 				break;
2893 			default:
2894 				break;
2895 			}
2896 			vm_map_try_merge_entries(map, prev_entry, entry);
2897 		}
2898 		vm_map_try_merge_entries(map, prev_entry, entry);
2899 		vm_map_unlock(map);
2900 	} else {
2901 		vm_pindex_t pstart, pend;
2902 
2903 		/*
2904 		 * madvise behaviors that are implemented in the underlying
2905 		 * vm_object.
2906 		 *
2907 		 * Since we don't clip the vm_map_entry, we have to clip
2908 		 * the vm_object pindex and count.
2909 		 */
2910 		for (; entry->start < end;
2911 		    entry = vm_map_entry_succ(entry)) {
2912 			vm_offset_t useEnd, useStart;
2913 
2914 			if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2915 				continue;
2916 
2917 			/*
2918 			 * MADV_FREE would otherwise rewind time to
2919 			 * the creation of the shadow object.  Because
2920 			 * we hold the VM map read-locked, neither the
2921 			 * entry's object nor the presence of a
2922 			 * backing object can change.
2923 			 */
2924 			if (behav == MADV_FREE &&
2925 			    entry->object.vm_object != NULL &&
2926 			    entry->object.vm_object->backing_object != NULL)
2927 				continue;
2928 
2929 			pstart = OFF_TO_IDX(entry->offset);
2930 			pend = pstart + atop(entry->end - entry->start);
2931 			useStart = entry->start;
2932 			useEnd = entry->end;
2933 
2934 			if (entry->start < start) {
2935 				pstart += atop(start - entry->start);
2936 				useStart = start;
2937 			}
2938 			if (entry->end > end) {
2939 				pend -= atop(entry->end - end);
2940 				useEnd = end;
2941 			}
2942 
2943 			if (pstart >= pend)
2944 				continue;
2945 
2946 			/*
2947 			 * Perform the pmap_advise() before clearing
2948 			 * PGA_REFERENCED in vm_page_advise().  Otherwise, a
2949 			 * concurrent pmap operation, such as pmap_remove(),
2950 			 * could clear a reference in the pmap and set
2951 			 * PGA_REFERENCED on the page before the pmap_advise()
2952 			 * had completed.  Consequently, the page would appear
2953 			 * referenced based upon an old reference that
2954 			 * occurred before this pmap_advise() ran.
2955 			 */
2956 			if (behav == MADV_DONTNEED || behav == MADV_FREE)
2957 				pmap_advise(map->pmap, useStart, useEnd,
2958 				    behav);
2959 
2960 			vm_object_madvise(entry->object.vm_object, pstart,
2961 			    pend, behav);
2962 
2963 			/*
2964 			 * Pre-populate paging structures in the
2965 			 * WILLNEED case.  For wired entries, the
2966 			 * paging structures are already populated.
2967 			 */
2968 			if (behav == MADV_WILLNEED &&
2969 			    entry->wired_count == 0) {
2970 				vm_map_pmap_enter(map,
2971 				    useStart,
2972 				    entry->protection,
2973 				    entry->object.vm_object,
2974 				    pstart,
2975 				    ptoa(pend - pstart),
2976 				    MAP_PREFAULT_MADVISE
2977 				);
2978 			}
2979 		}
2980 		vm_map_unlock_read(map);
2981 	}
2982 	return (0);
2983 }
2984 
2985 
2986 /*
2987  *	vm_map_inherit:
2988  *
2989  *	Sets the inheritance of the specified address
2990  *	range in the target map.  Inheritance
2991  *	affects how the map will be shared with
2992  *	child maps at the time of vmspace_fork.
2993  */
2994 int
2995 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
2996 	       vm_inherit_t new_inheritance)
2997 {
2998 	vm_map_entry_t entry, prev_entry;
2999 
3000 	switch (new_inheritance) {
3001 	case VM_INHERIT_NONE:
3002 	case VM_INHERIT_COPY:
3003 	case VM_INHERIT_SHARE:
3004 	case VM_INHERIT_ZERO:
3005 		break;
3006 	default:
3007 		return (KERN_INVALID_ARGUMENT);
3008 	}
3009 	if (start == end)
3010 		return (KERN_SUCCESS);
3011 	vm_map_lock(map);
3012 	VM_MAP_RANGE_CHECK(map, start, end);
3013 	if (vm_map_lookup_entry(map, start, &prev_entry)) {
3014 		entry = prev_entry;
3015 		vm_map_clip_start(map, entry, start);
3016 		prev_entry = vm_map_entry_pred(entry);
3017 	} else
3018 		entry = vm_map_entry_succ(prev_entry);
3019 	for (; entry->start < end;
3020 	    prev_entry = entry, entry = vm_map_entry_succ(entry)) {
3021 		vm_map_clip_end(map, entry, end);
3022 		if ((entry->eflags & MAP_ENTRY_GUARD) == 0 ||
3023 		    new_inheritance != VM_INHERIT_ZERO)
3024 			entry->inheritance = new_inheritance;
3025 		vm_map_try_merge_entries(map, prev_entry, entry);
3026 	}
3027 	vm_map_try_merge_entries(map, prev_entry, entry);
3028 	vm_map_unlock(map);
3029 	return (KERN_SUCCESS);
3030 }
3031 
3032 /*
3033  *	vm_map_entry_in_transition:
3034  *
3035  *	Release the map lock, and sleep until the entry is no longer in
3036  *	transition.  Awake and acquire the map lock.  If the map changed while
3037  *	another held the lock, lookup a possibly-changed entry at or after the
3038  *	'start' position of the old entry.
3039  */
3040 static vm_map_entry_t
3041 vm_map_entry_in_transition(vm_map_t map, vm_offset_t in_start,
3042     vm_offset_t *io_end, bool holes_ok, vm_map_entry_t in_entry)
3043 {
3044 	vm_map_entry_t entry;
3045 	vm_offset_t start;
3046 	u_int last_timestamp;
3047 
3048 	VM_MAP_ASSERT_LOCKED(map);
3049 	KASSERT((in_entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3050 	    ("not in-tranition map entry %p", in_entry));
3051 	/*
3052 	 * We have not yet clipped the entry.
3053 	 */
3054 	start = MAX(in_start, in_entry->start);
3055 	in_entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
3056 	last_timestamp = map->timestamp;
3057 	if (vm_map_unlock_and_wait(map, 0)) {
3058 		/*
3059 		 * Allow interruption of user wiring/unwiring?
3060 		 */
3061 	}
3062 	vm_map_lock(map);
3063 	if (last_timestamp + 1 == map->timestamp)
3064 		return (in_entry);
3065 
3066 	/*
3067 	 * Look again for the entry because the map was modified while it was
3068 	 * unlocked.  Specifically, the entry may have been clipped, merged, or
3069 	 * deleted.
3070 	 */
3071 	if (!vm_map_lookup_entry(map, start, &entry)) {
3072 		if (!holes_ok) {
3073 			*io_end = start;
3074 			return (NULL);
3075 		}
3076 		entry = vm_map_entry_succ(entry);
3077 	}
3078 	return (entry);
3079 }
3080 
3081 /*
3082  *	vm_map_unwire:
3083  *
3084  *	Implements both kernel and user unwiring.
3085  */
3086 int
3087 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t end,
3088     int flags)
3089 {
3090 	vm_map_entry_t entry, first_entry, next_entry, prev_entry;
3091 	int rv;
3092 	bool holes_ok, need_wakeup, user_unwire;
3093 
3094 	if (start == end)
3095 		return (KERN_SUCCESS);
3096 	holes_ok = (flags & VM_MAP_WIRE_HOLESOK) != 0;
3097 	user_unwire = (flags & VM_MAP_WIRE_USER) != 0;
3098 	vm_map_lock(map);
3099 	VM_MAP_RANGE_CHECK(map, start, end);
3100 	if (!vm_map_lookup_entry(map, start, &first_entry)) {
3101 		if (holes_ok)
3102 			first_entry = vm_map_entry_succ(first_entry);
3103 		else {
3104 			vm_map_unlock(map);
3105 			return (KERN_INVALID_ADDRESS);
3106 		}
3107 	}
3108 	rv = KERN_SUCCESS;
3109 	for (entry = first_entry; entry->start < end; entry = next_entry) {
3110 		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
3111 			/*
3112 			 * We have not yet clipped the entry.
3113 			 */
3114 			next_entry = vm_map_entry_in_transition(map, start,
3115 			    &end, holes_ok, entry);
3116 			if (next_entry == NULL) {
3117 				if (entry == first_entry) {
3118 					vm_map_unlock(map);
3119 					return (KERN_INVALID_ADDRESS);
3120 				}
3121 				rv = KERN_INVALID_ADDRESS;
3122 				break;
3123 			}
3124 			first_entry = (entry == first_entry) ?
3125 			    next_entry : NULL;
3126 			continue;
3127 		}
3128 		vm_map_clip_start(map, entry, start);
3129 		vm_map_clip_end(map, entry, end);
3130 		/*
3131 		 * Mark the entry in case the map lock is released.  (See
3132 		 * above.)
3133 		 */
3134 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
3135 		    entry->wiring_thread == NULL,
3136 		    ("owned map entry %p", entry));
3137 		entry->eflags |= MAP_ENTRY_IN_TRANSITION;
3138 		entry->wiring_thread = curthread;
3139 		next_entry = vm_map_entry_succ(entry);
3140 		/*
3141 		 * Check the map for holes in the specified region.
3142 		 * If holes_ok, skip this check.
3143 		 */
3144 		if (!holes_ok &&
3145 		    entry->end < end && next_entry->start > entry->end) {
3146 			end = entry->end;
3147 			rv = KERN_INVALID_ADDRESS;
3148 			break;
3149 		}
3150 		/*
3151 		 * If system unwiring, require that the entry is system wired.
3152 		 */
3153 		if (!user_unwire &&
3154 		    vm_map_entry_system_wired_count(entry) == 0) {
3155 			end = entry->end;
3156 			rv = KERN_INVALID_ARGUMENT;
3157 			break;
3158 		}
3159 	}
3160 	need_wakeup = false;
3161 	if (first_entry == NULL &&
3162 	    !vm_map_lookup_entry(map, start, &first_entry)) {
3163 		KASSERT(holes_ok, ("vm_map_unwire: lookup failed"));
3164 		prev_entry = first_entry;
3165 		entry = vm_map_entry_succ(first_entry);
3166 	} else {
3167 		prev_entry = vm_map_entry_pred(first_entry);
3168 		entry = first_entry;
3169 	}
3170 	for (; entry->start < end;
3171 	    prev_entry = entry, entry = vm_map_entry_succ(entry)) {
3172 		/*
3173 		 * If holes_ok was specified, an empty
3174 		 * space in the unwired region could have been mapped
3175 		 * while the map lock was dropped for draining
3176 		 * MAP_ENTRY_IN_TRANSITION.  Moreover, another thread
3177 		 * could be simultaneously wiring this new mapping
3178 		 * entry.  Detect these cases and skip any entries
3179 		 * marked as in transition by us.
3180 		 */
3181 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
3182 		    entry->wiring_thread != curthread) {
3183 			KASSERT(holes_ok,
3184 			    ("vm_map_unwire: !HOLESOK and new/changed entry"));
3185 			continue;
3186 		}
3187 
3188 		if (rv == KERN_SUCCESS && (!user_unwire ||
3189 		    (entry->eflags & MAP_ENTRY_USER_WIRED))) {
3190 			if (entry->wired_count == 1)
3191 				vm_map_entry_unwire(map, entry);
3192 			else
3193 				entry->wired_count--;
3194 			if (user_unwire)
3195 				entry->eflags &= ~MAP_ENTRY_USER_WIRED;
3196 		}
3197 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3198 		    ("vm_map_unwire: in-transition flag missing %p", entry));
3199 		KASSERT(entry->wiring_thread == curthread,
3200 		    ("vm_map_unwire: alien wire %p", entry));
3201 		entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
3202 		entry->wiring_thread = NULL;
3203 		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
3204 			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
3205 			need_wakeup = true;
3206 		}
3207 		vm_map_try_merge_entries(map, prev_entry, entry);
3208 	}
3209 	vm_map_try_merge_entries(map, prev_entry, entry);
3210 	vm_map_unlock(map);
3211 	if (need_wakeup)
3212 		vm_map_wakeup(map);
3213 	return (rv);
3214 }
3215 
3216 static void
3217 vm_map_wire_user_count_sub(u_long npages)
3218 {
3219 
3220 	atomic_subtract_long(&vm_user_wire_count, npages);
3221 }
3222 
3223 static bool
3224 vm_map_wire_user_count_add(u_long npages)
3225 {
3226 	u_long wired;
3227 
3228 	wired = vm_user_wire_count;
3229 	do {
3230 		if (npages + wired > vm_page_max_user_wired)
3231 			return (false);
3232 	} while (!atomic_fcmpset_long(&vm_user_wire_count, &wired,
3233 	    npages + wired));
3234 
3235 	return (true);
3236 }
3237 
3238 /*
3239  *	vm_map_wire_entry_failure:
3240  *
3241  *	Handle a wiring failure on the given entry.
3242  *
3243  *	The map should be locked.
3244  */
3245 static void
3246 vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
3247     vm_offset_t failed_addr)
3248 {
3249 
3250 	VM_MAP_ASSERT_LOCKED(map);
3251 	KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 &&
3252 	    entry->wired_count == 1,
3253 	    ("vm_map_wire_entry_failure: entry %p isn't being wired", entry));
3254 	KASSERT(failed_addr < entry->end,
3255 	    ("vm_map_wire_entry_failure: entry %p was fully wired", entry));
3256 
3257 	/*
3258 	 * If any pages at the start of this entry were successfully wired,
3259 	 * then unwire them.
3260 	 */
3261 	if (failed_addr > entry->start) {
3262 		pmap_unwire(map->pmap, entry->start, failed_addr);
3263 		vm_object_unwire(entry->object.vm_object, entry->offset,
3264 		    failed_addr - entry->start, PQ_ACTIVE);
3265 	}
3266 
3267 	/*
3268 	 * Assign an out-of-range value to represent the failure to wire this
3269 	 * entry.
3270 	 */
3271 	entry->wired_count = -1;
3272 }
3273 
3274 int
3275 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t end, int flags)
3276 {
3277 	int rv;
3278 
3279 	vm_map_lock(map);
3280 	rv = vm_map_wire_locked(map, start, end, flags);
3281 	vm_map_unlock(map);
3282 	return (rv);
3283 }
3284 
3285 
3286 /*
3287  *	vm_map_wire_locked:
3288  *
3289  *	Implements both kernel and user wiring.  Returns with the map locked,
3290  *	the map lock may be dropped.
3291  */
3292 int
3293 vm_map_wire_locked(vm_map_t map, vm_offset_t start, vm_offset_t end, int flags)
3294 {
3295 	vm_map_entry_t entry, first_entry, next_entry, prev_entry;
3296 	vm_offset_t faddr, saved_end, saved_start;
3297 	u_long npages;
3298 	u_int last_timestamp;
3299 	int rv;
3300 	bool holes_ok, need_wakeup, user_wire;
3301 	vm_prot_t prot;
3302 
3303 	VM_MAP_ASSERT_LOCKED(map);
3304 
3305 	if (start == end)
3306 		return (KERN_SUCCESS);
3307 	prot = 0;
3308 	if (flags & VM_MAP_WIRE_WRITE)
3309 		prot |= VM_PROT_WRITE;
3310 	holes_ok = (flags & VM_MAP_WIRE_HOLESOK) != 0;
3311 	user_wire = (flags & VM_MAP_WIRE_USER) != 0;
3312 	VM_MAP_RANGE_CHECK(map, start, end);
3313 	if (!vm_map_lookup_entry(map, start, &first_entry)) {
3314 		if (holes_ok)
3315 			first_entry = vm_map_entry_succ(first_entry);
3316 		else
3317 			return (KERN_INVALID_ADDRESS);
3318 	}
3319 	for (entry = first_entry; entry->start < end; entry = next_entry) {
3320 		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
3321 			/*
3322 			 * We have not yet clipped the entry.
3323 			 */
3324 			next_entry = vm_map_entry_in_transition(map, start,
3325 			    &end, holes_ok, entry);
3326 			if (next_entry == NULL) {
3327 				if (entry == first_entry)
3328 					return (KERN_INVALID_ADDRESS);
3329 				rv = KERN_INVALID_ADDRESS;
3330 				goto done;
3331 			}
3332 			first_entry = (entry == first_entry) ?
3333 			    next_entry : NULL;
3334 			continue;
3335 		}
3336 		vm_map_clip_start(map, entry, start);
3337 		vm_map_clip_end(map, entry, end);
3338 		/*
3339 		 * Mark the entry in case the map lock is released.  (See
3340 		 * above.)
3341 		 */
3342 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
3343 		    entry->wiring_thread == NULL,
3344 		    ("owned map entry %p", entry));
3345 		entry->eflags |= MAP_ENTRY_IN_TRANSITION;
3346 		entry->wiring_thread = curthread;
3347 		if ((entry->protection & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0
3348 		    || (entry->protection & prot) != prot) {
3349 			entry->eflags |= MAP_ENTRY_WIRE_SKIPPED;
3350 			if (!holes_ok) {
3351 				end = entry->end;
3352 				rv = KERN_INVALID_ADDRESS;
3353 				goto done;
3354 			}
3355 		} else if (entry->wired_count == 0) {
3356 			entry->wired_count++;
3357 
3358 			npages = atop(entry->end - entry->start);
3359 			if (user_wire && !vm_map_wire_user_count_add(npages)) {
3360 				vm_map_wire_entry_failure(map, entry,
3361 				    entry->start);
3362 				end = entry->end;
3363 				rv = KERN_RESOURCE_SHORTAGE;
3364 				goto done;
3365 			}
3366 
3367 			/*
3368 			 * Release the map lock, relying on the in-transition
3369 			 * mark.  Mark the map busy for fork.
3370 			 */
3371 			saved_start = entry->start;
3372 			saved_end = entry->end;
3373 			last_timestamp = map->timestamp;
3374 			vm_map_busy(map);
3375 			vm_map_unlock(map);
3376 
3377 			faddr = saved_start;
3378 			do {
3379 				/*
3380 				 * Simulate a fault to get the page and enter
3381 				 * it into the physical map.
3382 				 */
3383 				if ((rv = vm_fault(map, faddr,
3384 				    VM_PROT_NONE, VM_FAULT_WIRE, NULL)) !=
3385 				    KERN_SUCCESS)
3386 					break;
3387 			} while ((faddr += PAGE_SIZE) < saved_end);
3388 			vm_map_lock(map);
3389 			vm_map_unbusy(map);
3390 			if (last_timestamp + 1 != map->timestamp) {
3391 				/*
3392 				 * Look again for the entry because the map was
3393 				 * modified while it was unlocked.  The entry
3394 				 * may have been clipped, but NOT merged or
3395 				 * deleted.
3396 				 */
3397 				if (!vm_map_lookup_entry(map, saved_start,
3398 				    &next_entry))
3399 					KASSERT(false,
3400 					    ("vm_map_wire: lookup failed"));
3401 				first_entry = (entry == first_entry) ?
3402 				    next_entry : NULL;
3403 				for (entry = next_entry; entry->end < saved_end;
3404 				    entry = vm_map_entry_succ(entry)) {
3405 					/*
3406 					 * In case of failure, handle entries
3407 					 * that were not fully wired here;
3408 					 * fully wired entries are handled
3409 					 * later.
3410 					 */
3411 					if (rv != KERN_SUCCESS &&
3412 					    faddr < entry->end)
3413 						vm_map_wire_entry_failure(map,
3414 						    entry, faddr);
3415 				}
3416 			}
3417 			if (rv != KERN_SUCCESS) {
3418 				vm_map_wire_entry_failure(map, entry, faddr);
3419 				if (user_wire)
3420 					vm_map_wire_user_count_sub(npages);
3421 				end = entry->end;
3422 				goto done;
3423 			}
3424 		} else if (!user_wire ||
3425 			   (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
3426 			entry->wired_count++;
3427 		}
3428 		/*
3429 		 * Check the map for holes in the specified region.
3430 		 * If holes_ok was specified, skip this check.
3431 		 */
3432 		next_entry = vm_map_entry_succ(entry);
3433 		if (!holes_ok &&
3434 		    entry->end < end && next_entry->start > entry->end) {
3435 			end = entry->end;
3436 			rv = KERN_INVALID_ADDRESS;
3437 			goto done;
3438 		}
3439 	}
3440 	rv = KERN_SUCCESS;
3441 done:
3442 	need_wakeup = false;
3443 	if (first_entry == NULL &&
3444 	    !vm_map_lookup_entry(map, start, &first_entry)) {
3445 		KASSERT(holes_ok, ("vm_map_wire: lookup failed"));
3446 		prev_entry = first_entry;
3447 		entry = vm_map_entry_succ(first_entry);
3448 	} else {
3449 		prev_entry = vm_map_entry_pred(first_entry);
3450 		entry = first_entry;
3451 	}
3452 	for (; entry->start < end;
3453 	    prev_entry = entry, entry = vm_map_entry_succ(entry)) {
3454 		/*
3455 		 * If holes_ok was specified, an empty
3456 		 * space in the unwired region could have been mapped
3457 		 * while the map lock was dropped for faulting in the
3458 		 * pages or draining MAP_ENTRY_IN_TRANSITION.
3459 		 * Moreover, another thread could be simultaneously
3460 		 * wiring this new mapping entry.  Detect these cases
3461 		 * and skip any entries marked as in transition not by us.
3462 		 */
3463 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
3464 		    entry->wiring_thread != curthread) {
3465 			KASSERT(holes_ok,
3466 			    ("vm_map_wire: !HOLESOK and new/changed entry"));
3467 			continue;
3468 		}
3469 
3470 		if ((entry->eflags & MAP_ENTRY_WIRE_SKIPPED) != 0) {
3471 			/* do nothing */
3472 		} else if (rv == KERN_SUCCESS) {
3473 			if (user_wire)
3474 				entry->eflags |= MAP_ENTRY_USER_WIRED;
3475 		} else if (entry->wired_count == -1) {
3476 			/*
3477 			 * Wiring failed on this entry.  Thus, unwiring is
3478 			 * unnecessary.
3479 			 */
3480 			entry->wired_count = 0;
3481 		} else if (!user_wire ||
3482 		    (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
3483 			/*
3484 			 * Undo the wiring.  Wiring succeeded on this entry
3485 			 * but failed on a later entry.
3486 			 */
3487 			if (entry->wired_count == 1) {
3488 				vm_map_entry_unwire(map, entry);
3489 				if (user_wire)
3490 					vm_map_wire_user_count_sub(
3491 					    atop(entry->end - entry->start));
3492 			} else
3493 				entry->wired_count--;
3494 		}
3495 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3496 		    ("vm_map_wire: in-transition flag missing %p", entry));
3497 		KASSERT(entry->wiring_thread == curthread,
3498 		    ("vm_map_wire: alien wire %p", entry));
3499 		entry->eflags &= ~(MAP_ENTRY_IN_TRANSITION |
3500 		    MAP_ENTRY_WIRE_SKIPPED);
3501 		entry->wiring_thread = NULL;
3502 		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
3503 			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
3504 			need_wakeup = true;
3505 		}
3506 		vm_map_try_merge_entries(map, prev_entry, entry);
3507 	}
3508 	vm_map_try_merge_entries(map, prev_entry, entry);
3509 	if (need_wakeup)
3510 		vm_map_wakeup(map);
3511 	return (rv);
3512 }
3513 
3514 /*
3515  * vm_map_sync
3516  *
3517  * Push any dirty cached pages in the address range to their pager.
3518  * If syncio is TRUE, dirty pages are written synchronously.
3519  * If invalidate is TRUE, any cached pages are freed as well.
3520  *
3521  * If the size of the region from start to end is zero, we are
3522  * supposed to flush all modified pages within the region containing
3523  * start.  Unfortunately, a region can be split or coalesced with
3524  * neighboring regions, making it difficult to determine what the
3525  * original region was.  Therefore, we approximate this requirement by
3526  * flushing the current region containing start.
3527  *
3528  * Returns an error if any part of the specified range is not mapped.
3529  */
3530 int
3531 vm_map_sync(
3532 	vm_map_t map,
3533 	vm_offset_t start,
3534 	vm_offset_t end,
3535 	boolean_t syncio,
3536 	boolean_t invalidate)
3537 {
3538 	vm_map_entry_t entry, first_entry, next_entry;
3539 	vm_size_t size;
3540 	vm_object_t object;
3541 	vm_ooffset_t offset;
3542 	unsigned int last_timestamp;
3543 	boolean_t failed;
3544 
3545 	vm_map_lock_read(map);
3546 	VM_MAP_RANGE_CHECK(map, start, end);
3547 	if (!vm_map_lookup_entry(map, start, &first_entry)) {
3548 		vm_map_unlock_read(map);
3549 		return (KERN_INVALID_ADDRESS);
3550 	} else if (start == end) {
3551 		start = first_entry->start;
3552 		end = first_entry->end;
3553 	}
3554 	/*
3555 	 * Make a first pass to check for user-wired memory and holes.
3556 	 */
3557 	for (entry = first_entry; entry->start < end; entry = next_entry) {
3558 		if (invalidate &&
3559 		    (entry->eflags & MAP_ENTRY_USER_WIRED) != 0) {
3560 			vm_map_unlock_read(map);
3561 			return (KERN_INVALID_ARGUMENT);
3562 		}
3563 		next_entry = vm_map_entry_succ(entry);
3564 		if (end > entry->end &&
3565 		    entry->end != next_entry->start) {
3566 			vm_map_unlock_read(map);
3567 			return (KERN_INVALID_ADDRESS);
3568 		}
3569 	}
3570 
3571 	if (invalidate)
3572 		pmap_remove(map->pmap, start, end);
3573 	failed = FALSE;
3574 
3575 	/*
3576 	 * Make a second pass, cleaning/uncaching pages from the indicated
3577 	 * objects as we go.
3578 	 */
3579 	for (entry = first_entry; entry->start < end;) {
3580 		offset = entry->offset + (start - entry->start);
3581 		size = (end <= entry->end ? end : entry->end) - start;
3582 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0) {
3583 			vm_map_t smap;
3584 			vm_map_entry_t tentry;
3585 			vm_size_t tsize;
3586 
3587 			smap = entry->object.sub_map;
3588 			vm_map_lock_read(smap);
3589 			(void) vm_map_lookup_entry(smap, offset, &tentry);
3590 			tsize = tentry->end - offset;
3591 			if (tsize < size)
3592 				size = tsize;
3593 			object = tentry->object.vm_object;
3594 			offset = tentry->offset + (offset - tentry->start);
3595 			vm_map_unlock_read(smap);
3596 		} else {
3597 			object = entry->object.vm_object;
3598 		}
3599 		vm_object_reference(object);
3600 		last_timestamp = map->timestamp;
3601 		vm_map_unlock_read(map);
3602 		if (!vm_object_sync(object, offset, size, syncio, invalidate))
3603 			failed = TRUE;
3604 		start += size;
3605 		vm_object_deallocate(object);
3606 		vm_map_lock_read(map);
3607 		if (last_timestamp == map->timestamp ||
3608 		    !vm_map_lookup_entry(map, start, &entry))
3609 			entry = vm_map_entry_succ(entry);
3610 	}
3611 
3612 	vm_map_unlock_read(map);
3613 	return (failed ? KERN_FAILURE : KERN_SUCCESS);
3614 }
3615 
3616 /*
3617  *	vm_map_entry_unwire:	[ internal use only ]
3618  *
3619  *	Make the region specified by this entry pageable.
3620  *
3621  *	The map in question should be locked.
3622  *	[This is the reason for this routine's existence.]
3623  */
3624 static void
3625 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
3626 {
3627 	vm_size_t size;
3628 
3629 	VM_MAP_ASSERT_LOCKED(map);
3630 	KASSERT(entry->wired_count > 0,
3631 	    ("vm_map_entry_unwire: entry %p isn't wired", entry));
3632 
3633 	size = entry->end - entry->start;
3634 	if ((entry->eflags & MAP_ENTRY_USER_WIRED) != 0)
3635 		vm_map_wire_user_count_sub(atop(size));
3636 	pmap_unwire(map->pmap, entry->start, entry->end);
3637 	vm_object_unwire(entry->object.vm_object, entry->offset, size,
3638 	    PQ_ACTIVE);
3639 	entry->wired_count = 0;
3640 }
3641 
3642 static void
3643 vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map)
3644 {
3645 
3646 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0)
3647 		vm_object_deallocate(entry->object.vm_object);
3648 	uma_zfree(system_map ? kmapentzone : mapentzone, entry);
3649 }
3650 
3651 /*
3652  *	vm_map_entry_delete:	[ internal use only ]
3653  *
3654  *	Deallocate the given entry from the target map.
3655  */
3656 static void
3657 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry)
3658 {
3659 	vm_object_t object;
3660 	vm_pindex_t offidxstart, offidxend, count, size1;
3661 	vm_size_t size;
3662 
3663 	vm_map_entry_unlink(map, entry, UNLINK_MERGE_NONE);
3664 	object = entry->object.vm_object;
3665 
3666 	if ((entry->eflags & MAP_ENTRY_GUARD) != 0) {
3667 		MPASS(entry->cred == NULL);
3668 		MPASS((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0);
3669 		MPASS(object == NULL);
3670 		vm_map_entry_deallocate(entry, map->system_map);
3671 		return;
3672 	}
3673 
3674 	size = entry->end - entry->start;
3675 	map->size -= size;
3676 
3677 	if (entry->cred != NULL) {
3678 		swap_release_by_cred(size, entry->cred);
3679 		crfree(entry->cred);
3680 	}
3681 
3682 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0 || object == NULL) {
3683 		entry->object.vm_object = NULL;
3684 	} else if ((object->flags & OBJ_ANON) != 0 ||
3685 	    object == kernel_object) {
3686 		KASSERT(entry->cred == NULL || object->cred == NULL ||
3687 		    (entry->eflags & MAP_ENTRY_NEEDS_COPY),
3688 		    ("OVERCOMMIT vm_map_entry_delete: both cred %p", entry));
3689 		count = atop(size);
3690 		offidxstart = OFF_TO_IDX(entry->offset);
3691 		offidxend = offidxstart + count;
3692 		VM_OBJECT_WLOCK(object);
3693 		if (object->ref_count != 1 &&
3694 		    ((object->flags & OBJ_ONEMAPPING) != 0 ||
3695 		    object == kernel_object)) {
3696 			vm_object_collapse(object);
3697 
3698 			/*
3699 			 * The option OBJPR_NOTMAPPED can be passed here
3700 			 * because vm_map_delete() already performed
3701 			 * pmap_remove() on the only mapping to this range
3702 			 * of pages.
3703 			 */
3704 			vm_object_page_remove(object, offidxstart, offidxend,
3705 			    OBJPR_NOTMAPPED);
3706 			if (object->type == OBJT_SWAP)
3707 				swap_pager_freespace(object, offidxstart,
3708 				    count);
3709 			if (offidxend >= object->size &&
3710 			    offidxstart < object->size) {
3711 				size1 = object->size;
3712 				object->size = offidxstart;
3713 				if (object->cred != NULL) {
3714 					size1 -= object->size;
3715 					KASSERT(object->charge >= ptoa(size1),
3716 					    ("object %p charge < 0", object));
3717 					swap_release_by_cred(ptoa(size1),
3718 					    object->cred);
3719 					object->charge -= ptoa(size1);
3720 				}
3721 			}
3722 		}
3723 		VM_OBJECT_WUNLOCK(object);
3724 	}
3725 	if (map->system_map)
3726 		vm_map_entry_deallocate(entry, TRUE);
3727 	else {
3728 		entry->defer_next = curthread->td_map_def_user;
3729 		curthread->td_map_def_user = entry;
3730 	}
3731 }
3732 
3733 /*
3734  *	vm_map_delete:	[ internal use only ]
3735  *
3736  *	Deallocates the given address range from the target
3737  *	map.
3738  */
3739 int
3740 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
3741 {
3742 	vm_map_entry_t entry;
3743 	vm_map_entry_t first_entry;
3744 
3745 	VM_MAP_ASSERT_LOCKED(map);
3746 	if (start == end)
3747 		return (KERN_SUCCESS);
3748 
3749 	/*
3750 	 * Find the start of the region, and clip it
3751 	 */
3752 	if (!vm_map_lookup_entry(map, start, &first_entry))
3753 		entry = vm_map_entry_succ(first_entry);
3754 	else {
3755 		entry = first_entry;
3756 		vm_map_clip_start(map, entry, start);
3757 	}
3758 
3759 	/*
3760 	 * Step through all entries in this region
3761 	 */
3762 	while (entry->start < end) {
3763 		vm_map_entry_t next;
3764 
3765 		/*
3766 		 * Wait for wiring or unwiring of an entry to complete.
3767 		 * Also wait for any system wirings to disappear on
3768 		 * user maps.
3769 		 */
3770 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 ||
3771 		    (vm_map_pmap(map) != kernel_pmap &&
3772 		    vm_map_entry_system_wired_count(entry) != 0)) {
3773 			unsigned int last_timestamp;
3774 			vm_offset_t saved_start;
3775 			vm_map_entry_t tmp_entry;
3776 
3777 			saved_start = entry->start;
3778 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
3779 			last_timestamp = map->timestamp;
3780 			(void) vm_map_unlock_and_wait(map, 0);
3781 			vm_map_lock(map);
3782 			if (last_timestamp + 1 != map->timestamp) {
3783 				/*
3784 				 * Look again for the entry because the map was
3785 				 * modified while it was unlocked.
3786 				 * Specifically, the entry may have been
3787 				 * clipped, merged, or deleted.
3788 				 */
3789 				if (!vm_map_lookup_entry(map, saved_start,
3790 							 &tmp_entry))
3791 					entry = vm_map_entry_succ(tmp_entry);
3792 				else {
3793 					entry = tmp_entry;
3794 					vm_map_clip_start(map, entry,
3795 							  saved_start);
3796 				}
3797 			}
3798 			continue;
3799 		}
3800 		vm_map_clip_end(map, entry, end);
3801 
3802 		next = vm_map_entry_succ(entry);
3803 
3804 		/*
3805 		 * Unwire before removing addresses from the pmap; otherwise,
3806 		 * unwiring will put the entries back in the pmap.
3807 		 */
3808 		if (entry->wired_count != 0)
3809 			vm_map_entry_unwire(map, entry);
3810 
3811 		/*
3812 		 * Remove mappings for the pages, but only if the
3813 		 * mappings could exist.  For instance, it does not
3814 		 * make sense to call pmap_remove() for guard entries.
3815 		 */
3816 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0 ||
3817 		    entry->object.vm_object != NULL)
3818 			pmap_remove(map->pmap, entry->start, entry->end);
3819 
3820 		if (entry->end == map->anon_loc)
3821 			map->anon_loc = entry->start;
3822 
3823 		/*
3824 		 * Delete the entry only after removing all pmap
3825 		 * entries pointing to its pages.  (Otherwise, its
3826 		 * page frames may be reallocated, and any modify bits
3827 		 * will be set in the wrong object!)
3828 		 */
3829 		vm_map_entry_delete(map, entry);
3830 		entry = next;
3831 	}
3832 	return (KERN_SUCCESS);
3833 }
3834 
3835 /*
3836  *	vm_map_remove:
3837  *
3838  *	Remove the given address range from the target map.
3839  *	This is the exported form of vm_map_delete.
3840  */
3841 int
3842 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
3843 {
3844 	int result;
3845 
3846 	vm_map_lock(map);
3847 	VM_MAP_RANGE_CHECK(map, start, end);
3848 	result = vm_map_delete(map, start, end);
3849 	vm_map_unlock(map);
3850 	return (result);
3851 }
3852 
3853 /*
3854  *	vm_map_check_protection:
3855  *
3856  *	Assert that the target map allows the specified privilege on the
3857  *	entire address region given.  The entire region must be allocated.
3858  *
3859  *	WARNING!  This code does not and should not check whether the
3860  *	contents of the region is accessible.  For example a smaller file
3861  *	might be mapped into a larger address space.
3862  *
3863  *	NOTE!  This code is also called by munmap().
3864  *
3865  *	The map must be locked.  A read lock is sufficient.
3866  */
3867 boolean_t
3868 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
3869 			vm_prot_t protection)
3870 {
3871 	vm_map_entry_t entry;
3872 	vm_map_entry_t tmp_entry;
3873 
3874 	if (!vm_map_lookup_entry(map, start, &tmp_entry))
3875 		return (FALSE);
3876 	entry = tmp_entry;
3877 
3878 	while (start < end) {
3879 		/*
3880 		 * No holes allowed!
3881 		 */
3882 		if (start < entry->start)
3883 			return (FALSE);
3884 		/*
3885 		 * Check protection associated with entry.
3886 		 */
3887 		if ((entry->protection & protection) != protection)
3888 			return (FALSE);
3889 		/* go to next entry */
3890 		start = entry->end;
3891 		entry = vm_map_entry_succ(entry);
3892 	}
3893 	return (TRUE);
3894 }
3895 
3896 
3897 /*
3898  *
3899  *	vm_map_copy_swap_object:
3900  *
3901  *	Copies a swap-backed object from an existing map entry to a
3902  *	new one.  Carries forward the swap charge.  May change the
3903  *	src object on return.
3904  */
3905 static void
3906 vm_map_copy_swap_object(vm_map_entry_t src_entry, vm_map_entry_t dst_entry,
3907     vm_offset_t size, vm_ooffset_t *fork_charge)
3908 {
3909 	vm_object_t src_object;
3910 	struct ucred *cred;
3911 	int charged;
3912 
3913 	src_object = src_entry->object.vm_object;
3914 	charged = ENTRY_CHARGED(src_entry);
3915 	if ((src_object->flags & OBJ_ANON) != 0) {
3916 		VM_OBJECT_WLOCK(src_object);
3917 		vm_object_collapse(src_object);
3918 		if ((src_object->flags & OBJ_ONEMAPPING) != 0) {
3919 			vm_object_split(src_entry);
3920 			src_object = src_entry->object.vm_object;
3921 		}
3922 		vm_object_reference_locked(src_object);
3923 		vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
3924 		VM_OBJECT_WUNLOCK(src_object);
3925 	} else
3926 		vm_object_reference(src_object);
3927 	if (src_entry->cred != NULL &&
3928 	    !(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
3929 		KASSERT(src_object->cred == NULL,
3930 		    ("OVERCOMMIT: vm_map_copy_anon_entry: cred %p",
3931 		     src_object));
3932 		src_object->cred = src_entry->cred;
3933 		src_object->charge = size;
3934 	}
3935 	dst_entry->object.vm_object = src_object;
3936 	if (charged) {
3937 		cred = curthread->td_ucred;
3938 		crhold(cred);
3939 		dst_entry->cred = cred;
3940 		*fork_charge += size;
3941 		if (!(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
3942 			crhold(cred);
3943 			src_entry->cred = cred;
3944 			*fork_charge += size;
3945 		}
3946 	}
3947 }
3948 
3949 /*
3950  *	vm_map_copy_entry:
3951  *
3952  *	Copies the contents of the source entry to the destination
3953  *	entry.  The entries *must* be aligned properly.
3954  */
3955 static void
3956 vm_map_copy_entry(
3957 	vm_map_t src_map,
3958 	vm_map_t dst_map,
3959 	vm_map_entry_t src_entry,
3960 	vm_map_entry_t dst_entry,
3961 	vm_ooffset_t *fork_charge)
3962 {
3963 	vm_object_t src_object;
3964 	vm_map_entry_t fake_entry;
3965 	vm_offset_t size;
3966 
3967 	VM_MAP_ASSERT_LOCKED(dst_map);
3968 
3969 	if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
3970 		return;
3971 
3972 	if (src_entry->wired_count == 0 ||
3973 	    (src_entry->protection & VM_PROT_WRITE) == 0) {
3974 		/*
3975 		 * If the source entry is marked needs_copy, it is already
3976 		 * write-protected.
3977 		 */
3978 		if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0 &&
3979 		    (src_entry->protection & VM_PROT_WRITE) != 0) {
3980 			pmap_protect(src_map->pmap,
3981 			    src_entry->start,
3982 			    src_entry->end,
3983 			    src_entry->protection & ~VM_PROT_WRITE);
3984 		}
3985 
3986 		/*
3987 		 * Make a copy of the object.
3988 		 */
3989 		size = src_entry->end - src_entry->start;
3990 		if ((src_object = src_entry->object.vm_object) != NULL) {
3991 			if (src_object->type == OBJT_DEFAULT ||
3992 			    src_object->type == OBJT_SWAP) {
3993 				vm_map_copy_swap_object(src_entry, dst_entry,
3994 				    size, fork_charge);
3995 				/* May have split/collapsed, reload obj. */
3996 				src_object = src_entry->object.vm_object;
3997 			} else {
3998 				vm_object_reference(src_object);
3999 				dst_entry->object.vm_object = src_object;
4000 			}
4001 			src_entry->eflags |= MAP_ENTRY_COW |
4002 			    MAP_ENTRY_NEEDS_COPY;
4003 			dst_entry->eflags |= MAP_ENTRY_COW |
4004 			    MAP_ENTRY_NEEDS_COPY;
4005 			dst_entry->offset = src_entry->offset;
4006 			if (src_entry->eflags & MAP_ENTRY_WRITECNT) {
4007 				/*
4008 				 * MAP_ENTRY_WRITECNT cannot
4009 				 * indicate write reference from
4010 				 * src_entry, since the entry is
4011 				 * marked as needs copy.  Allocate a
4012 				 * fake entry that is used to
4013 				 * decrement object->un_pager writecount
4014 				 * at the appropriate time.  Attach
4015 				 * fake_entry to the deferred list.
4016 				 */
4017 				fake_entry = vm_map_entry_create(dst_map);
4018 				fake_entry->eflags = MAP_ENTRY_WRITECNT;
4019 				src_entry->eflags &= ~MAP_ENTRY_WRITECNT;
4020 				vm_object_reference(src_object);
4021 				fake_entry->object.vm_object = src_object;
4022 				fake_entry->start = src_entry->start;
4023 				fake_entry->end = src_entry->end;
4024 				fake_entry->defer_next =
4025 				    curthread->td_map_def_user;
4026 				curthread->td_map_def_user = fake_entry;
4027 			}
4028 
4029 			pmap_copy(dst_map->pmap, src_map->pmap,
4030 			    dst_entry->start, dst_entry->end - dst_entry->start,
4031 			    src_entry->start);
4032 		} else {
4033 			dst_entry->object.vm_object = NULL;
4034 			dst_entry->offset = 0;
4035 			if (src_entry->cred != NULL) {
4036 				dst_entry->cred = curthread->td_ucred;
4037 				crhold(dst_entry->cred);
4038 				*fork_charge += size;
4039 			}
4040 		}
4041 	} else {
4042 		/*
4043 		 * We don't want to make writeable wired pages copy-on-write.
4044 		 * Immediately copy these pages into the new map by simulating
4045 		 * page faults.  The new pages are pageable.
4046 		 */
4047 		vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry,
4048 		    fork_charge);
4049 	}
4050 }
4051 
4052 /*
4053  * vmspace_map_entry_forked:
4054  * Update the newly-forked vmspace each time a map entry is inherited
4055  * or copied.  The values for vm_dsize and vm_tsize are approximate
4056  * (and mostly-obsolete ideas in the face of mmap(2) et al.)
4057  */
4058 static void
4059 vmspace_map_entry_forked(const struct vmspace *vm1, struct vmspace *vm2,
4060     vm_map_entry_t entry)
4061 {
4062 	vm_size_t entrysize;
4063 	vm_offset_t newend;
4064 
4065 	if ((entry->eflags & MAP_ENTRY_GUARD) != 0)
4066 		return;
4067 	entrysize = entry->end - entry->start;
4068 	vm2->vm_map.size += entrysize;
4069 	if (entry->eflags & (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP)) {
4070 		vm2->vm_ssize += btoc(entrysize);
4071 	} else if (entry->start >= (vm_offset_t)vm1->vm_daddr &&
4072 	    entry->start < (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize)) {
4073 		newend = MIN(entry->end,
4074 		    (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize));
4075 		vm2->vm_dsize += btoc(newend - entry->start);
4076 	} else if (entry->start >= (vm_offset_t)vm1->vm_taddr &&
4077 	    entry->start < (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize)) {
4078 		newend = MIN(entry->end,
4079 		    (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize));
4080 		vm2->vm_tsize += btoc(newend - entry->start);
4081 	}
4082 }
4083 
4084 /*
4085  * vmspace_fork:
4086  * Create a new process vmspace structure and vm_map
4087  * based on those of an existing process.  The new map
4088  * is based on the old map, according to the inheritance
4089  * values on the regions in that map.
4090  *
4091  * XXX It might be worth coalescing the entries added to the new vmspace.
4092  *
4093  * The source map must not be locked.
4094  */
4095 struct vmspace *
4096 vmspace_fork(struct vmspace *vm1, vm_ooffset_t *fork_charge)
4097 {
4098 	struct vmspace *vm2;
4099 	vm_map_t new_map, old_map;
4100 	vm_map_entry_t new_entry, old_entry;
4101 	vm_object_t object;
4102 	int error, locked;
4103 	vm_inherit_t inh;
4104 
4105 	old_map = &vm1->vm_map;
4106 	/* Copy immutable fields of vm1 to vm2. */
4107 	vm2 = vmspace_alloc(vm_map_min(old_map), vm_map_max(old_map),
4108 	    pmap_pinit);
4109 	if (vm2 == NULL)
4110 		return (NULL);
4111 
4112 	vm2->vm_taddr = vm1->vm_taddr;
4113 	vm2->vm_daddr = vm1->vm_daddr;
4114 	vm2->vm_maxsaddr = vm1->vm_maxsaddr;
4115 	vm_map_lock(old_map);
4116 	if (old_map->busy)
4117 		vm_map_wait_busy(old_map);
4118 	new_map = &vm2->vm_map;
4119 	locked = vm_map_trylock(new_map); /* trylock to silence WITNESS */
4120 	KASSERT(locked, ("vmspace_fork: lock failed"));
4121 
4122 	error = pmap_vmspace_copy(new_map->pmap, old_map->pmap);
4123 	if (error != 0) {
4124 		sx_xunlock(&old_map->lock);
4125 		sx_xunlock(&new_map->lock);
4126 		vm_map_process_deferred();
4127 		vmspace_free(vm2);
4128 		return (NULL);
4129 	}
4130 
4131 	new_map->anon_loc = old_map->anon_loc;
4132 
4133 	VM_MAP_ENTRY_FOREACH(old_entry, old_map) {
4134 		if ((old_entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
4135 			panic("vm_map_fork: encountered a submap");
4136 
4137 		inh = old_entry->inheritance;
4138 		if ((old_entry->eflags & MAP_ENTRY_GUARD) != 0 &&
4139 		    inh != VM_INHERIT_NONE)
4140 			inh = VM_INHERIT_COPY;
4141 
4142 		switch (inh) {
4143 		case VM_INHERIT_NONE:
4144 			break;
4145 
4146 		case VM_INHERIT_SHARE:
4147 			/*
4148 			 * Clone the entry, creating the shared object if
4149 			 * necessary.
4150 			 */
4151 			object = old_entry->object.vm_object;
4152 			if (object == NULL) {
4153 				vm_map_entry_back(old_entry);
4154 				object = old_entry->object.vm_object;
4155 			}
4156 
4157 			/*
4158 			 * Add the reference before calling vm_object_shadow
4159 			 * to insure that a shadow object is created.
4160 			 */
4161 			vm_object_reference(object);
4162 			if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4163 				vm_object_shadow(&old_entry->object.vm_object,
4164 				    &old_entry->offset,
4165 				    old_entry->end - old_entry->start,
4166 				    old_entry->cred,
4167 				    /* Transfer the second reference too. */
4168 				    true);
4169 				old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
4170 				old_entry->cred = NULL;
4171 
4172 				/*
4173 				 * As in vm_map_merged_neighbor_dispose(),
4174 				 * the vnode lock will not be acquired in
4175 				 * this call to vm_object_deallocate().
4176 				 */
4177 				vm_object_deallocate(object);
4178 				object = old_entry->object.vm_object;
4179 			} else {
4180 				VM_OBJECT_WLOCK(object);
4181 				vm_object_clear_flag(object, OBJ_ONEMAPPING);
4182 				if (old_entry->cred != NULL) {
4183 					KASSERT(object->cred == NULL,
4184 					    ("vmspace_fork both cred"));
4185 					object->cred = old_entry->cred;
4186 					object->charge = old_entry->end -
4187 					    old_entry->start;
4188 					old_entry->cred = NULL;
4189 				}
4190 
4191 				/*
4192 				 * Assert the correct state of the vnode
4193 				 * v_writecount while the object is locked, to
4194 				 * not relock it later for the assertion
4195 				 * correctness.
4196 				 */
4197 				if (old_entry->eflags & MAP_ENTRY_WRITECNT &&
4198 				    object->type == OBJT_VNODE) {
4199 					KASSERT(((struct vnode *)object->
4200 					    handle)->v_writecount > 0,
4201 					    ("vmspace_fork: v_writecount %p",
4202 					    object));
4203 					KASSERT(object->un_pager.vnp.
4204 					    writemappings > 0,
4205 					    ("vmspace_fork: vnp.writecount %p",
4206 					    object));
4207 				}
4208 				VM_OBJECT_WUNLOCK(object);
4209 			}
4210 
4211 			/*
4212 			 * Clone the entry, referencing the shared object.
4213 			 */
4214 			new_entry = vm_map_entry_create(new_map);
4215 			*new_entry = *old_entry;
4216 			new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
4217 			    MAP_ENTRY_IN_TRANSITION);
4218 			new_entry->wiring_thread = NULL;
4219 			new_entry->wired_count = 0;
4220 			if (new_entry->eflags & MAP_ENTRY_WRITECNT) {
4221 				vm_pager_update_writecount(object,
4222 				    new_entry->start, new_entry->end);
4223 			}
4224 			vm_map_entry_set_vnode_text(new_entry, true);
4225 
4226 			/*
4227 			 * Insert the entry into the new map -- we know we're
4228 			 * inserting at the end of the new map.
4229 			 */
4230 			vm_map_entry_link(new_map, new_entry);
4231 			vmspace_map_entry_forked(vm1, vm2, new_entry);
4232 
4233 			/*
4234 			 * Update the physical map
4235 			 */
4236 			pmap_copy(new_map->pmap, old_map->pmap,
4237 			    new_entry->start,
4238 			    (old_entry->end - old_entry->start),
4239 			    old_entry->start);
4240 			break;
4241 
4242 		case VM_INHERIT_COPY:
4243 			/*
4244 			 * Clone the entry and link into the map.
4245 			 */
4246 			new_entry = vm_map_entry_create(new_map);
4247 			*new_entry = *old_entry;
4248 			/*
4249 			 * Copied entry is COW over the old object.
4250 			 */
4251 			new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
4252 			    MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_WRITECNT);
4253 			new_entry->wiring_thread = NULL;
4254 			new_entry->wired_count = 0;
4255 			new_entry->object.vm_object = NULL;
4256 			new_entry->cred = NULL;
4257 			vm_map_entry_link(new_map, new_entry);
4258 			vmspace_map_entry_forked(vm1, vm2, new_entry);
4259 			vm_map_copy_entry(old_map, new_map, old_entry,
4260 			    new_entry, fork_charge);
4261 			vm_map_entry_set_vnode_text(new_entry, true);
4262 			break;
4263 
4264 		case VM_INHERIT_ZERO:
4265 			/*
4266 			 * Create a new anonymous mapping entry modelled from
4267 			 * the old one.
4268 			 */
4269 			new_entry = vm_map_entry_create(new_map);
4270 			memset(new_entry, 0, sizeof(*new_entry));
4271 
4272 			new_entry->start = old_entry->start;
4273 			new_entry->end = old_entry->end;
4274 			new_entry->eflags = old_entry->eflags &
4275 			    ~(MAP_ENTRY_USER_WIRED | MAP_ENTRY_IN_TRANSITION |
4276 			    MAP_ENTRY_WRITECNT | MAP_ENTRY_VN_EXEC);
4277 			new_entry->protection = old_entry->protection;
4278 			new_entry->max_protection = old_entry->max_protection;
4279 			new_entry->inheritance = VM_INHERIT_ZERO;
4280 
4281 			vm_map_entry_link(new_map, new_entry);
4282 			vmspace_map_entry_forked(vm1, vm2, new_entry);
4283 
4284 			new_entry->cred = curthread->td_ucred;
4285 			crhold(new_entry->cred);
4286 			*fork_charge += (new_entry->end - new_entry->start);
4287 
4288 			break;
4289 		}
4290 	}
4291 	/*
4292 	 * Use inlined vm_map_unlock() to postpone handling the deferred
4293 	 * map entries, which cannot be done until both old_map and
4294 	 * new_map locks are released.
4295 	 */
4296 	sx_xunlock(&old_map->lock);
4297 	sx_xunlock(&new_map->lock);
4298 	vm_map_process_deferred();
4299 
4300 	return (vm2);
4301 }
4302 
4303 /*
4304  * Create a process's stack for exec_new_vmspace().  This function is never
4305  * asked to wire the newly created stack.
4306  */
4307 int
4308 vm_map_stack(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
4309     vm_prot_t prot, vm_prot_t max, int cow)
4310 {
4311 	vm_size_t growsize, init_ssize;
4312 	rlim_t vmemlim;
4313 	int rv;
4314 
4315 	MPASS((map->flags & MAP_WIREFUTURE) == 0);
4316 	growsize = sgrowsiz;
4317 	init_ssize = (max_ssize < growsize) ? max_ssize : growsize;
4318 	vm_map_lock(map);
4319 	vmemlim = lim_cur(curthread, RLIMIT_VMEM);
4320 	/* If we would blow our VMEM resource limit, no go */
4321 	if (map->size + init_ssize > vmemlim) {
4322 		rv = KERN_NO_SPACE;
4323 		goto out;
4324 	}
4325 	rv = vm_map_stack_locked(map, addrbos, max_ssize, growsize, prot,
4326 	    max, cow);
4327 out:
4328 	vm_map_unlock(map);
4329 	return (rv);
4330 }
4331 
4332 static int stack_guard_page = 1;
4333 SYSCTL_INT(_security_bsd, OID_AUTO, stack_guard_page, CTLFLAG_RWTUN,
4334     &stack_guard_page, 0,
4335     "Specifies the number of guard pages for a stack that grows");
4336 
4337 static int
4338 vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
4339     vm_size_t growsize, vm_prot_t prot, vm_prot_t max, int cow)
4340 {
4341 	vm_map_entry_t new_entry, prev_entry;
4342 	vm_offset_t bot, gap_bot, gap_top, top;
4343 	vm_size_t init_ssize, sgp;
4344 	int orient, rv;
4345 
4346 	/*
4347 	 * The stack orientation is piggybacked with the cow argument.
4348 	 * Extract it into orient and mask the cow argument so that we
4349 	 * don't pass it around further.
4350 	 */
4351 	orient = cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP);
4352 	KASSERT(orient != 0, ("No stack grow direction"));
4353 	KASSERT(orient != (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP),
4354 	    ("bi-dir stack"));
4355 
4356 	if (addrbos < vm_map_min(map) ||
4357 	    addrbos + max_ssize > vm_map_max(map) ||
4358 	    addrbos + max_ssize <= addrbos)
4359 		return (KERN_INVALID_ADDRESS);
4360 	sgp = ((curproc->p_flag2 & P2_STKGAP_DISABLE) != 0 ||
4361 	    (curproc->p_fctl0 & NT_FREEBSD_FCTL_STKGAP_DISABLE) != 0) ? 0 :
4362 	    (vm_size_t)stack_guard_page * PAGE_SIZE;
4363 	if (sgp >= max_ssize)
4364 		return (KERN_INVALID_ARGUMENT);
4365 
4366 	init_ssize = growsize;
4367 	if (max_ssize < init_ssize + sgp)
4368 		init_ssize = max_ssize - sgp;
4369 
4370 	/* If addr is already mapped, no go */
4371 	if (vm_map_lookup_entry(map, addrbos, &prev_entry))
4372 		return (KERN_NO_SPACE);
4373 
4374 	/*
4375 	 * If we can't accommodate max_ssize in the current mapping, no go.
4376 	 */
4377 	if (vm_map_entry_succ(prev_entry)->start < addrbos + max_ssize)
4378 		return (KERN_NO_SPACE);
4379 
4380 	/*
4381 	 * We initially map a stack of only init_ssize.  We will grow as
4382 	 * needed later.  Depending on the orientation of the stack (i.e.
4383 	 * the grow direction) we either map at the top of the range, the
4384 	 * bottom of the range or in the middle.
4385 	 *
4386 	 * Note: we would normally expect prot and max to be VM_PROT_ALL,
4387 	 * and cow to be 0.  Possibly we should eliminate these as input
4388 	 * parameters, and just pass these values here in the insert call.
4389 	 */
4390 	if (orient == MAP_STACK_GROWS_DOWN) {
4391 		bot = addrbos + max_ssize - init_ssize;
4392 		top = bot + init_ssize;
4393 		gap_bot = addrbos;
4394 		gap_top = bot;
4395 	} else /* if (orient == MAP_STACK_GROWS_UP) */ {
4396 		bot = addrbos;
4397 		top = bot + init_ssize;
4398 		gap_bot = top;
4399 		gap_top = addrbos + max_ssize;
4400 	}
4401 	rv = vm_map_insert(map, NULL, 0, bot, top, prot, max, cow);
4402 	if (rv != KERN_SUCCESS)
4403 		return (rv);
4404 	new_entry = vm_map_entry_succ(prev_entry);
4405 	KASSERT(new_entry->end == top || new_entry->start == bot,
4406 	    ("Bad entry start/end for new stack entry"));
4407 	KASSERT((orient & MAP_STACK_GROWS_DOWN) == 0 ||
4408 	    (new_entry->eflags & MAP_ENTRY_GROWS_DOWN) != 0,
4409 	    ("new entry lacks MAP_ENTRY_GROWS_DOWN"));
4410 	KASSERT((orient & MAP_STACK_GROWS_UP) == 0 ||
4411 	    (new_entry->eflags & MAP_ENTRY_GROWS_UP) != 0,
4412 	    ("new entry lacks MAP_ENTRY_GROWS_UP"));
4413 	if (gap_bot == gap_top)
4414 		return (KERN_SUCCESS);
4415 	rv = vm_map_insert(map, NULL, 0, gap_bot, gap_top, VM_PROT_NONE,
4416 	    VM_PROT_NONE, MAP_CREATE_GUARD | (orient == MAP_STACK_GROWS_DOWN ?
4417 	    MAP_CREATE_STACK_GAP_DN : MAP_CREATE_STACK_GAP_UP));
4418 	if (rv == KERN_SUCCESS) {
4419 		/*
4420 		 * Gap can never successfully handle a fault, so
4421 		 * read-ahead logic is never used for it.  Re-use
4422 		 * next_read of the gap entry to store
4423 		 * stack_guard_page for vm_map_growstack().
4424 		 */
4425 		if (orient == MAP_STACK_GROWS_DOWN)
4426 			vm_map_entry_pred(new_entry)->next_read = sgp;
4427 		else
4428 			vm_map_entry_succ(new_entry)->next_read = sgp;
4429 	} else {
4430 		(void)vm_map_delete(map, bot, top);
4431 	}
4432 	return (rv);
4433 }
4434 
4435 /*
4436  * Attempts to grow a vm stack entry.  Returns KERN_SUCCESS if we
4437  * successfully grow the stack.
4438  */
4439 static int
4440 vm_map_growstack(vm_map_t map, vm_offset_t addr, vm_map_entry_t gap_entry)
4441 {
4442 	vm_map_entry_t stack_entry;
4443 	struct proc *p;
4444 	struct vmspace *vm;
4445 	struct ucred *cred;
4446 	vm_offset_t gap_end, gap_start, grow_start;
4447 	vm_size_t grow_amount, guard, max_grow;
4448 	rlim_t lmemlim, stacklim, vmemlim;
4449 	int rv, rv1;
4450 	bool gap_deleted, grow_down, is_procstack;
4451 #ifdef notyet
4452 	uint64_t limit;
4453 #endif
4454 #ifdef RACCT
4455 	int error;
4456 #endif
4457 
4458 	p = curproc;
4459 	vm = p->p_vmspace;
4460 
4461 	/*
4462 	 * Disallow stack growth when the access is performed by a
4463 	 * debugger or AIO daemon.  The reason is that the wrong
4464 	 * resource limits are applied.
4465 	 */
4466 	if (p != initproc && (map != &p->p_vmspace->vm_map ||
4467 	    p->p_textvp == NULL))
4468 		return (KERN_FAILURE);
4469 
4470 	MPASS(!map->system_map);
4471 
4472 	lmemlim = lim_cur(curthread, RLIMIT_MEMLOCK);
4473 	stacklim = lim_cur(curthread, RLIMIT_STACK);
4474 	vmemlim = lim_cur(curthread, RLIMIT_VMEM);
4475 retry:
4476 	/* If addr is not in a hole for a stack grow area, no need to grow. */
4477 	if (gap_entry == NULL && !vm_map_lookup_entry(map, addr, &gap_entry))
4478 		return (KERN_FAILURE);
4479 	if ((gap_entry->eflags & MAP_ENTRY_GUARD) == 0)
4480 		return (KERN_SUCCESS);
4481 	if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_DN) != 0) {
4482 		stack_entry = vm_map_entry_succ(gap_entry);
4483 		if ((stack_entry->eflags & MAP_ENTRY_GROWS_DOWN) == 0 ||
4484 		    stack_entry->start != gap_entry->end)
4485 			return (KERN_FAILURE);
4486 		grow_amount = round_page(stack_entry->start - addr);
4487 		grow_down = true;
4488 	} else if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_UP) != 0) {
4489 		stack_entry = vm_map_entry_pred(gap_entry);
4490 		if ((stack_entry->eflags & MAP_ENTRY_GROWS_UP) == 0 ||
4491 		    stack_entry->end != gap_entry->start)
4492 			return (KERN_FAILURE);
4493 		grow_amount = round_page(addr + 1 - stack_entry->end);
4494 		grow_down = false;
4495 	} else {
4496 		return (KERN_FAILURE);
4497 	}
4498 	guard = ((curproc->p_flag2 & P2_STKGAP_DISABLE) != 0 ||
4499 	    (curproc->p_fctl0 & NT_FREEBSD_FCTL_STKGAP_DISABLE) != 0) ? 0 :
4500 	    gap_entry->next_read;
4501 	max_grow = gap_entry->end - gap_entry->start;
4502 	if (guard > max_grow)
4503 		return (KERN_NO_SPACE);
4504 	max_grow -= guard;
4505 	if (grow_amount > max_grow)
4506 		return (KERN_NO_SPACE);
4507 
4508 	/*
4509 	 * If this is the main process stack, see if we're over the stack
4510 	 * limit.
4511 	 */
4512 	is_procstack = addr >= (vm_offset_t)vm->vm_maxsaddr &&
4513 	    addr < (vm_offset_t)p->p_sysent->sv_usrstack;
4514 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim))
4515 		return (KERN_NO_SPACE);
4516 
4517 #ifdef RACCT
4518 	if (racct_enable) {
4519 		PROC_LOCK(p);
4520 		if (is_procstack && racct_set(p, RACCT_STACK,
4521 		    ctob(vm->vm_ssize) + grow_amount)) {
4522 			PROC_UNLOCK(p);
4523 			return (KERN_NO_SPACE);
4524 		}
4525 		PROC_UNLOCK(p);
4526 	}
4527 #endif
4528 
4529 	grow_amount = roundup(grow_amount, sgrowsiz);
4530 	if (grow_amount > max_grow)
4531 		grow_amount = max_grow;
4532 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
4533 		grow_amount = trunc_page((vm_size_t)stacklim) -
4534 		    ctob(vm->vm_ssize);
4535 	}
4536 
4537 #ifdef notyet
4538 	PROC_LOCK(p);
4539 	limit = racct_get_available(p, RACCT_STACK);
4540 	PROC_UNLOCK(p);
4541 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > limit))
4542 		grow_amount = limit - ctob(vm->vm_ssize);
4543 #endif
4544 
4545 	if (!old_mlock && (map->flags & MAP_WIREFUTURE) != 0) {
4546 		if (ptoa(pmap_wired_count(map->pmap)) + grow_amount > lmemlim) {
4547 			rv = KERN_NO_SPACE;
4548 			goto out;
4549 		}
4550 #ifdef RACCT
4551 		if (racct_enable) {
4552 			PROC_LOCK(p);
4553 			if (racct_set(p, RACCT_MEMLOCK,
4554 			    ptoa(pmap_wired_count(map->pmap)) + grow_amount)) {
4555 				PROC_UNLOCK(p);
4556 				rv = KERN_NO_SPACE;
4557 				goto out;
4558 			}
4559 			PROC_UNLOCK(p);
4560 		}
4561 #endif
4562 	}
4563 
4564 	/* If we would blow our VMEM resource limit, no go */
4565 	if (map->size + grow_amount > vmemlim) {
4566 		rv = KERN_NO_SPACE;
4567 		goto out;
4568 	}
4569 #ifdef RACCT
4570 	if (racct_enable) {
4571 		PROC_LOCK(p);
4572 		if (racct_set(p, RACCT_VMEM, map->size + grow_amount)) {
4573 			PROC_UNLOCK(p);
4574 			rv = KERN_NO_SPACE;
4575 			goto out;
4576 		}
4577 		PROC_UNLOCK(p);
4578 	}
4579 #endif
4580 
4581 	if (vm_map_lock_upgrade(map)) {
4582 		gap_entry = NULL;
4583 		vm_map_lock_read(map);
4584 		goto retry;
4585 	}
4586 
4587 	if (grow_down) {
4588 		grow_start = gap_entry->end - grow_amount;
4589 		if (gap_entry->start + grow_amount == gap_entry->end) {
4590 			gap_start = gap_entry->start;
4591 			gap_end = gap_entry->end;
4592 			vm_map_entry_delete(map, gap_entry);
4593 			gap_deleted = true;
4594 		} else {
4595 			MPASS(gap_entry->start < gap_entry->end - grow_amount);
4596 			vm_map_entry_resize(map, gap_entry, -grow_amount);
4597 			gap_deleted = false;
4598 		}
4599 		rv = vm_map_insert(map, NULL, 0, grow_start,
4600 		    grow_start + grow_amount,
4601 		    stack_entry->protection, stack_entry->max_protection,
4602 		    MAP_STACK_GROWS_DOWN);
4603 		if (rv != KERN_SUCCESS) {
4604 			if (gap_deleted) {
4605 				rv1 = vm_map_insert(map, NULL, 0, gap_start,
4606 				    gap_end, VM_PROT_NONE, VM_PROT_NONE,
4607 				    MAP_CREATE_GUARD | MAP_CREATE_STACK_GAP_DN);
4608 				MPASS(rv1 == KERN_SUCCESS);
4609 			} else
4610 				vm_map_entry_resize(map, gap_entry,
4611 				    grow_amount);
4612 		}
4613 	} else {
4614 		grow_start = stack_entry->end;
4615 		cred = stack_entry->cred;
4616 		if (cred == NULL && stack_entry->object.vm_object != NULL)
4617 			cred = stack_entry->object.vm_object->cred;
4618 		if (cred != NULL && !swap_reserve_by_cred(grow_amount, cred))
4619 			rv = KERN_NO_SPACE;
4620 		/* Grow the underlying object if applicable. */
4621 		else if (stack_entry->object.vm_object == NULL ||
4622 		    vm_object_coalesce(stack_entry->object.vm_object,
4623 		    stack_entry->offset,
4624 		    (vm_size_t)(stack_entry->end - stack_entry->start),
4625 		    grow_amount, cred != NULL)) {
4626 			if (gap_entry->start + grow_amount == gap_entry->end) {
4627 				vm_map_entry_delete(map, gap_entry);
4628 				vm_map_entry_resize(map, stack_entry,
4629 				    grow_amount);
4630 			} else {
4631 				gap_entry->start += grow_amount;
4632 				stack_entry->end += grow_amount;
4633 			}
4634 			map->size += grow_amount;
4635 			rv = KERN_SUCCESS;
4636 		} else
4637 			rv = KERN_FAILURE;
4638 	}
4639 	if (rv == KERN_SUCCESS && is_procstack)
4640 		vm->vm_ssize += btoc(grow_amount);
4641 
4642 	/*
4643 	 * Heed the MAP_WIREFUTURE flag if it was set for this process.
4644 	 */
4645 	if (rv == KERN_SUCCESS && (map->flags & MAP_WIREFUTURE) != 0) {
4646 		rv = vm_map_wire_locked(map, grow_start,
4647 		    grow_start + grow_amount,
4648 		    VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
4649 	}
4650 	vm_map_lock_downgrade(map);
4651 
4652 out:
4653 #ifdef RACCT
4654 	if (racct_enable && rv != KERN_SUCCESS) {
4655 		PROC_LOCK(p);
4656 		error = racct_set(p, RACCT_VMEM, map->size);
4657 		KASSERT(error == 0, ("decreasing RACCT_VMEM failed"));
4658 		if (!old_mlock) {
4659 			error = racct_set(p, RACCT_MEMLOCK,
4660 			    ptoa(pmap_wired_count(map->pmap)));
4661 			KASSERT(error == 0, ("decreasing RACCT_MEMLOCK failed"));
4662 		}
4663 	    	error = racct_set(p, RACCT_STACK, ctob(vm->vm_ssize));
4664 		KASSERT(error == 0, ("decreasing RACCT_STACK failed"));
4665 		PROC_UNLOCK(p);
4666 	}
4667 #endif
4668 
4669 	return (rv);
4670 }
4671 
4672 /*
4673  * Unshare the specified VM space for exec.  If other processes are
4674  * mapped to it, then create a new one.  The new vmspace is null.
4675  */
4676 int
4677 vmspace_exec(struct proc *p, vm_offset_t minuser, vm_offset_t maxuser)
4678 {
4679 	struct vmspace *oldvmspace = p->p_vmspace;
4680 	struct vmspace *newvmspace;
4681 
4682 	KASSERT((curthread->td_pflags & TDP_EXECVMSPC) == 0,
4683 	    ("vmspace_exec recursed"));
4684 	newvmspace = vmspace_alloc(minuser, maxuser, pmap_pinit);
4685 	if (newvmspace == NULL)
4686 		return (ENOMEM);
4687 	newvmspace->vm_swrss = oldvmspace->vm_swrss;
4688 	/*
4689 	 * This code is written like this for prototype purposes.  The
4690 	 * goal is to avoid running down the vmspace here, but let the
4691 	 * other process's that are still using the vmspace to finally
4692 	 * run it down.  Even though there is little or no chance of blocking
4693 	 * here, it is a good idea to keep this form for future mods.
4694 	 */
4695 	PROC_VMSPACE_LOCK(p);
4696 	p->p_vmspace = newvmspace;
4697 	PROC_VMSPACE_UNLOCK(p);
4698 	if (p == curthread->td_proc)
4699 		pmap_activate(curthread);
4700 	curthread->td_pflags |= TDP_EXECVMSPC;
4701 	return (0);
4702 }
4703 
4704 /*
4705  * Unshare the specified VM space for forcing COW.  This
4706  * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
4707  */
4708 int
4709 vmspace_unshare(struct proc *p)
4710 {
4711 	struct vmspace *oldvmspace = p->p_vmspace;
4712 	struct vmspace *newvmspace;
4713 	vm_ooffset_t fork_charge;
4714 
4715 	if (oldvmspace->vm_refcnt == 1)
4716 		return (0);
4717 	fork_charge = 0;
4718 	newvmspace = vmspace_fork(oldvmspace, &fork_charge);
4719 	if (newvmspace == NULL)
4720 		return (ENOMEM);
4721 	if (!swap_reserve_by_cred(fork_charge, p->p_ucred)) {
4722 		vmspace_free(newvmspace);
4723 		return (ENOMEM);
4724 	}
4725 	PROC_VMSPACE_LOCK(p);
4726 	p->p_vmspace = newvmspace;
4727 	PROC_VMSPACE_UNLOCK(p);
4728 	if (p == curthread->td_proc)
4729 		pmap_activate(curthread);
4730 	vmspace_free(oldvmspace);
4731 	return (0);
4732 }
4733 
4734 /*
4735  *	vm_map_lookup:
4736  *
4737  *	Finds the VM object, offset, and
4738  *	protection for a given virtual address in the
4739  *	specified map, assuming a page fault of the
4740  *	type specified.
4741  *
4742  *	Leaves the map in question locked for read; return
4743  *	values are guaranteed until a vm_map_lookup_done
4744  *	call is performed.  Note that the map argument
4745  *	is in/out; the returned map must be used in
4746  *	the call to vm_map_lookup_done.
4747  *
4748  *	A handle (out_entry) is returned for use in
4749  *	vm_map_lookup_done, to make that fast.
4750  *
4751  *	If a lookup is requested with "write protection"
4752  *	specified, the map may be changed to perform virtual
4753  *	copying operations, although the data referenced will
4754  *	remain the same.
4755  */
4756 int
4757 vm_map_lookup(vm_map_t *var_map,		/* IN/OUT */
4758 	      vm_offset_t vaddr,
4759 	      vm_prot_t fault_typea,
4760 	      vm_map_entry_t *out_entry,	/* OUT */
4761 	      vm_object_t *object,		/* OUT */
4762 	      vm_pindex_t *pindex,		/* OUT */
4763 	      vm_prot_t *out_prot,		/* OUT */
4764 	      boolean_t *wired)			/* OUT */
4765 {
4766 	vm_map_entry_t entry;
4767 	vm_map_t map = *var_map;
4768 	vm_prot_t prot;
4769 	vm_prot_t fault_type;
4770 	vm_object_t eobject;
4771 	vm_size_t size;
4772 	struct ucred *cred;
4773 
4774 RetryLookup:
4775 
4776 	vm_map_lock_read(map);
4777 
4778 RetryLookupLocked:
4779 	/*
4780 	 * Lookup the faulting address.
4781 	 */
4782 	if (!vm_map_lookup_entry(map, vaddr, out_entry)) {
4783 		vm_map_unlock_read(map);
4784 		return (KERN_INVALID_ADDRESS);
4785 	}
4786 
4787 	entry = *out_entry;
4788 
4789 	/*
4790 	 * Handle submaps.
4791 	 */
4792 	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
4793 		vm_map_t old_map = map;
4794 
4795 		*var_map = map = entry->object.sub_map;
4796 		vm_map_unlock_read(old_map);
4797 		goto RetryLookup;
4798 	}
4799 
4800 	/*
4801 	 * Check whether this task is allowed to have this page.
4802 	 */
4803 	prot = entry->protection;
4804 	if ((fault_typea & VM_PROT_FAULT_LOOKUP) != 0) {
4805 		fault_typea &= ~VM_PROT_FAULT_LOOKUP;
4806 		if (prot == VM_PROT_NONE && map != kernel_map &&
4807 		    (entry->eflags & MAP_ENTRY_GUARD) != 0 &&
4808 		    (entry->eflags & (MAP_ENTRY_STACK_GAP_DN |
4809 		    MAP_ENTRY_STACK_GAP_UP)) != 0 &&
4810 		    vm_map_growstack(map, vaddr, entry) == KERN_SUCCESS)
4811 			goto RetryLookupLocked;
4812 	}
4813 	fault_type = fault_typea & VM_PROT_ALL;
4814 	if ((fault_type & prot) != fault_type || prot == VM_PROT_NONE) {
4815 		vm_map_unlock_read(map);
4816 		return (KERN_PROTECTION_FAILURE);
4817 	}
4818 	KASSERT((prot & VM_PROT_WRITE) == 0 || (entry->eflags &
4819 	    (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY)) !=
4820 	    (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY),
4821 	    ("entry %p flags %x", entry, entry->eflags));
4822 	if ((fault_typea & VM_PROT_COPY) != 0 &&
4823 	    (entry->max_protection & VM_PROT_WRITE) == 0 &&
4824 	    (entry->eflags & MAP_ENTRY_COW) == 0) {
4825 		vm_map_unlock_read(map);
4826 		return (KERN_PROTECTION_FAILURE);
4827 	}
4828 
4829 	/*
4830 	 * If this page is not pageable, we have to get it for all possible
4831 	 * accesses.
4832 	 */
4833 	*wired = (entry->wired_count != 0);
4834 	if (*wired)
4835 		fault_type = entry->protection;
4836 	size = entry->end - entry->start;
4837 
4838 	/*
4839 	 * If the entry was copy-on-write, we either ...
4840 	 */
4841 	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4842 		/*
4843 		 * If we want to write the page, we may as well handle that
4844 		 * now since we've got the map locked.
4845 		 *
4846 		 * If we don't need to write the page, we just demote the
4847 		 * permissions allowed.
4848 		 */
4849 		if ((fault_type & VM_PROT_WRITE) != 0 ||
4850 		    (fault_typea & VM_PROT_COPY) != 0) {
4851 			/*
4852 			 * Make a new object, and place it in the object
4853 			 * chain.  Note that no new references have appeared
4854 			 * -- one just moved from the map to the new
4855 			 * object.
4856 			 */
4857 			if (vm_map_lock_upgrade(map))
4858 				goto RetryLookup;
4859 
4860 			if (entry->cred == NULL) {
4861 				/*
4862 				 * The debugger owner is charged for
4863 				 * the memory.
4864 				 */
4865 				cred = curthread->td_ucred;
4866 				crhold(cred);
4867 				if (!swap_reserve_by_cred(size, cred)) {
4868 					crfree(cred);
4869 					vm_map_unlock(map);
4870 					return (KERN_RESOURCE_SHORTAGE);
4871 				}
4872 				entry->cred = cred;
4873 			}
4874 			eobject = entry->object.vm_object;
4875 			vm_object_shadow(&entry->object.vm_object,
4876 			    &entry->offset, size, entry->cred, false);
4877 			if (eobject == entry->object.vm_object) {
4878 				/*
4879 				 * The object was not shadowed.
4880 				 */
4881 				swap_release_by_cred(size, entry->cred);
4882 				crfree(entry->cred);
4883 			}
4884 			entry->cred = NULL;
4885 			entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
4886 
4887 			vm_map_lock_downgrade(map);
4888 		} else {
4889 			/*
4890 			 * We're attempting to read a copy-on-write page --
4891 			 * don't allow writes.
4892 			 */
4893 			prot &= ~VM_PROT_WRITE;
4894 		}
4895 	}
4896 
4897 	/*
4898 	 * Create an object if necessary.
4899 	 */
4900 	if (entry->object.vm_object == NULL && !map->system_map) {
4901 		if (vm_map_lock_upgrade(map))
4902 			goto RetryLookup;
4903 		entry->object.vm_object = vm_object_allocate_anon(atop(size),
4904 		    NULL, entry->cred, entry->cred != NULL ? size : 0);
4905 		entry->offset = 0;
4906 		entry->cred = NULL;
4907 		vm_map_lock_downgrade(map);
4908 	}
4909 
4910 	/*
4911 	 * Return the object/offset from this entry.  If the entry was
4912 	 * copy-on-write or empty, it has been fixed up.
4913 	 */
4914 	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4915 	*object = entry->object.vm_object;
4916 
4917 	*out_prot = prot;
4918 	return (KERN_SUCCESS);
4919 }
4920 
4921 /*
4922  *	vm_map_lookup_locked:
4923  *
4924  *	Lookup the faulting address.  A version of vm_map_lookup that returns
4925  *      KERN_FAILURE instead of blocking on map lock or memory allocation.
4926  */
4927 int
4928 vm_map_lookup_locked(vm_map_t *var_map,		/* IN/OUT */
4929 		     vm_offset_t vaddr,
4930 		     vm_prot_t fault_typea,
4931 		     vm_map_entry_t *out_entry,	/* OUT */
4932 		     vm_object_t *object,	/* OUT */
4933 		     vm_pindex_t *pindex,	/* OUT */
4934 		     vm_prot_t *out_prot,	/* OUT */
4935 		     boolean_t *wired)		/* OUT */
4936 {
4937 	vm_map_entry_t entry;
4938 	vm_map_t map = *var_map;
4939 	vm_prot_t prot;
4940 	vm_prot_t fault_type = fault_typea;
4941 
4942 	/*
4943 	 * Lookup the faulting address.
4944 	 */
4945 	if (!vm_map_lookup_entry(map, vaddr, out_entry))
4946 		return (KERN_INVALID_ADDRESS);
4947 
4948 	entry = *out_entry;
4949 
4950 	/*
4951 	 * Fail if the entry refers to a submap.
4952 	 */
4953 	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
4954 		return (KERN_FAILURE);
4955 
4956 	/*
4957 	 * Check whether this task is allowed to have this page.
4958 	 */
4959 	prot = entry->protection;
4960 	fault_type &= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
4961 	if ((fault_type & prot) != fault_type)
4962 		return (KERN_PROTECTION_FAILURE);
4963 
4964 	/*
4965 	 * If this page is not pageable, we have to get it for all possible
4966 	 * accesses.
4967 	 */
4968 	*wired = (entry->wired_count != 0);
4969 	if (*wired)
4970 		fault_type = entry->protection;
4971 
4972 	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4973 		/*
4974 		 * Fail if the entry was copy-on-write for a write fault.
4975 		 */
4976 		if (fault_type & VM_PROT_WRITE)
4977 			return (KERN_FAILURE);
4978 		/*
4979 		 * We're attempting to read a copy-on-write page --
4980 		 * don't allow writes.
4981 		 */
4982 		prot &= ~VM_PROT_WRITE;
4983 	}
4984 
4985 	/*
4986 	 * Fail if an object should be created.
4987 	 */
4988 	if (entry->object.vm_object == NULL && !map->system_map)
4989 		return (KERN_FAILURE);
4990 
4991 	/*
4992 	 * Return the object/offset from this entry.  If the entry was
4993 	 * copy-on-write or empty, it has been fixed up.
4994 	 */
4995 	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4996 	*object = entry->object.vm_object;
4997 
4998 	*out_prot = prot;
4999 	return (KERN_SUCCESS);
5000 }
5001 
5002 /*
5003  *	vm_map_lookup_done:
5004  *
5005  *	Releases locks acquired by a vm_map_lookup
5006  *	(according to the handle returned by that lookup).
5007  */
5008 void
5009 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry)
5010 {
5011 	/*
5012 	 * Unlock the main-level map
5013 	 */
5014 	vm_map_unlock_read(map);
5015 }
5016 
5017 vm_offset_t
5018 vm_map_max_KBI(const struct vm_map *map)
5019 {
5020 
5021 	return (vm_map_max(map));
5022 }
5023 
5024 vm_offset_t
5025 vm_map_min_KBI(const struct vm_map *map)
5026 {
5027 
5028 	return (vm_map_min(map));
5029 }
5030 
5031 pmap_t
5032 vm_map_pmap_KBI(vm_map_t map)
5033 {
5034 
5035 	return (map->pmap);
5036 }
5037 
5038 #ifdef INVARIANTS
5039 static void
5040 _vm_map_assert_consistent(vm_map_t map, int check)
5041 {
5042 	vm_map_entry_t entry, prev;
5043 	vm_map_entry_t cur, header, lbound, ubound;
5044 	vm_size_t max_left, max_right;
5045 
5046 #ifdef DIAGNOSTIC
5047 	++map->nupdates;
5048 #endif
5049 	if (enable_vmmap_check != check)
5050 		return;
5051 
5052 	header = prev = &map->header;
5053 	VM_MAP_ENTRY_FOREACH(entry, map) {
5054 		KASSERT(prev->end <= entry->start,
5055 		    ("map %p prev->end = %jx, start = %jx", map,
5056 		    (uintmax_t)prev->end, (uintmax_t)entry->start));
5057 		KASSERT(entry->start < entry->end,
5058 		    ("map %p start = %jx, end = %jx", map,
5059 		    (uintmax_t)entry->start, (uintmax_t)entry->end));
5060 		KASSERT(entry->left == header ||
5061 		    entry->left->start < entry->start,
5062 		    ("map %p left->start = %jx, start = %jx", map,
5063 		    (uintmax_t)entry->left->start, (uintmax_t)entry->start));
5064 		KASSERT(entry->right == header ||
5065 		    entry->start < entry->right->start,
5066 		    ("map %p start = %jx, right->start = %jx", map,
5067 		    (uintmax_t)entry->start, (uintmax_t)entry->right->start));
5068 		cur = map->root;
5069 		lbound = ubound = header;
5070 		for (;;) {
5071 			if (entry->start < cur->start) {
5072 				ubound = cur;
5073 				cur = cur->left;
5074 				KASSERT(cur != lbound,
5075 				    ("map %p cannot find %jx",
5076 				    map, (uintmax_t)entry->start));
5077 			} else if (cur->end <= entry->start) {
5078 				lbound = cur;
5079 				cur = cur->right;
5080 				KASSERT(cur != ubound,
5081 				    ("map %p cannot find %jx",
5082 				    map, (uintmax_t)entry->start));
5083 			} else {
5084 				KASSERT(cur == entry,
5085 				    ("map %p cannot find %jx",
5086 				    map, (uintmax_t)entry->start));
5087 				break;
5088 			}
5089 		}
5090 		max_left = vm_map_entry_max_free_left(entry, lbound);
5091 		max_right = vm_map_entry_max_free_right(entry, ubound);
5092 		KASSERT(entry->max_free == vm_size_max(max_left, max_right),
5093 		    ("map %p max = %jx, max_left = %jx, max_right = %jx", map,
5094 		    (uintmax_t)entry->max_free,
5095 		    (uintmax_t)max_left, (uintmax_t)max_right));
5096 		prev = entry;
5097 	}
5098 	KASSERT(prev->end <= entry->start,
5099 	    ("map %p prev->end = %jx, start = %jx", map,
5100 	    (uintmax_t)prev->end, (uintmax_t)entry->start));
5101 }
5102 #endif
5103 
5104 #include "opt_ddb.h"
5105 #ifdef DDB
5106 #include <sys/kernel.h>
5107 
5108 #include <ddb/ddb.h>
5109 
5110 static void
5111 vm_map_print(vm_map_t map)
5112 {
5113 	vm_map_entry_t entry, prev;
5114 
5115 	db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
5116 	    (void *)map,
5117 	    (void *)map->pmap, map->nentries, map->timestamp);
5118 
5119 	db_indent += 2;
5120 	prev = &map->header;
5121 	VM_MAP_ENTRY_FOREACH(entry, map) {
5122 		db_iprintf("map entry %p: start=%p, end=%p, eflags=%#x, \n",
5123 		    (void *)entry, (void *)entry->start, (void *)entry->end,
5124 		    entry->eflags);
5125 		{
5126 			static char *inheritance_name[4] =
5127 			{"share", "copy", "none", "donate_copy"};
5128 
5129 			db_iprintf(" prot=%x/%x/%s",
5130 			    entry->protection,
5131 			    entry->max_protection,
5132 			    inheritance_name[(int)(unsigned char)
5133 			    entry->inheritance]);
5134 			if (entry->wired_count != 0)
5135 				db_printf(", wired");
5136 		}
5137 		if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
5138 			db_printf(", share=%p, offset=0x%jx\n",
5139 			    (void *)entry->object.sub_map,
5140 			    (uintmax_t)entry->offset);
5141 			if (prev == &map->header ||
5142 			    prev->object.sub_map !=
5143 				entry->object.sub_map) {
5144 				db_indent += 2;
5145 				vm_map_print((vm_map_t)entry->object.sub_map);
5146 				db_indent -= 2;
5147 			}
5148 		} else {
5149 			if (entry->cred != NULL)
5150 				db_printf(", ruid %d", entry->cred->cr_ruid);
5151 			db_printf(", object=%p, offset=0x%jx",
5152 			    (void *)entry->object.vm_object,
5153 			    (uintmax_t)entry->offset);
5154 			if (entry->object.vm_object && entry->object.vm_object->cred)
5155 				db_printf(", obj ruid %d charge %jx",
5156 				    entry->object.vm_object->cred->cr_ruid,
5157 				    (uintmax_t)entry->object.vm_object->charge);
5158 			if (entry->eflags & MAP_ENTRY_COW)
5159 				db_printf(", copy (%s)",
5160 				    (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
5161 			db_printf("\n");
5162 
5163 			if (prev == &map->header ||
5164 			    prev->object.vm_object !=
5165 				entry->object.vm_object) {
5166 				db_indent += 2;
5167 				vm_object_print((db_expr_t)(intptr_t)
5168 						entry->object.vm_object,
5169 						0, 0, (char *)0);
5170 				db_indent -= 2;
5171 			}
5172 		}
5173 		prev = entry;
5174 	}
5175 	db_indent -= 2;
5176 }
5177 
5178 DB_SHOW_COMMAND(map, map)
5179 {
5180 
5181 	if (!have_addr) {
5182 		db_printf("usage: show map <addr>\n");
5183 		return;
5184 	}
5185 	vm_map_print((vm_map_t)addr);
5186 }
5187 
5188 DB_SHOW_COMMAND(procvm, procvm)
5189 {
5190 	struct proc *p;
5191 
5192 	if (have_addr) {
5193 		p = db_lookup_proc(addr);
5194 	} else {
5195 		p = curproc;
5196 	}
5197 
5198 	db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
5199 	    (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
5200 	    (void *)vmspace_pmap(p->p_vmspace));
5201 
5202 	vm_map_print((vm_map_t)&p->p_vmspace->vm_map);
5203 }
5204 
5205 #endif /* DDB */
5206