xref: /freebsd/sys/vm/vm_map.c (revision c0829bb1)
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, 0);
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_map_entry_max_free_right(root, rlist),	\
1032 	    ("%s: max_free invariant fails", __func__));		\
1033 	if (y == llist ? max_free > 0 : max_free - 1 < y->max_free)	\
1034 		max_free = vm_map_entry_max_free_right(root, rlist);	\
1035 	if (y != llist && (test)) {					\
1036 		/* Rotate right and make y root. */			\
1037 		z = y->right;						\
1038 		if (z != root) {					\
1039 			root->left = z;					\
1040 			y->right = root;				\
1041 			if (max_free < y->max_free)			\
1042 			    root->max_free = max_free =			\
1043 			    vm_size_max(max_free, z->max_free);		\
1044 		} else if (max_free < y->max_free)			\
1045 			root->max_free = max_free =			\
1046 			    vm_size_max(max_free, root->start - y->end);\
1047 		root = y;						\
1048 		y = root->left;						\
1049 	}								\
1050 	/* Copy right->max_free.  Put root on rlist. */			\
1051 	root->max_free = max_free;					\
1052 	KASSERT(max_free == vm_map_entry_max_free_right(root, rlist),	\
1053 	    ("%s: max_free not copied from right", __func__));		\
1054 	root->left = rlist;						\
1055 	rlist = root;							\
1056 	root = y != llist ? y : NULL;					\
1057 } while (0)
1058 
1059 #define SPLAY_RIGHT_STEP(root, y, llist, rlist, test) do {		\
1060 	vm_map_entry_t z;						\
1061 	vm_size_t max_free;						\
1062 									\
1063 	/*								\
1064 	 * Infer root->left->max_free == root->max_free when		\
1065 	 * y->max_free < root->max_free || root->max_free == 0.		\
1066 	 * Otherwise, look left to find it.				\
1067 	 */								\
1068 	y = root->right;						\
1069 	max_free = root->max_free;					\
1070 	KASSERT(max_free >= vm_map_entry_max_free_left(root, llist),	\
1071 	    ("%s: max_free invariant fails", __func__));		\
1072 	if (y == rlist ? max_free > 0 : max_free - 1 < y->max_free)	\
1073 		max_free = vm_map_entry_max_free_left(root, llist);	\
1074 	if (y != rlist && (test)) {					\
1075 		/* Rotate left and make y root. */			\
1076 		z = y->left;						\
1077 		if (z != root) {					\
1078 			root->right = z;				\
1079 			y->left = root;					\
1080 			if (max_free < y->max_free)			\
1081 			    root->max_free = max_free =			\
1082 			    vm_size_max(max_free, z->max_free);		\
1083 		} else if (max_free < y->max_free)			\
1084 			root->max_free = max_free =			\
1085 			    vm_size_max(max_free, y->start - root->end);\
1086 		root = y;						\
1087 		y = root->right;					\
1088 	}								\
1089 	/* Copy left->max_free.  Put root on llist. */			\
1090 	root->max_free = max_free;					\
1091 	KASSERT(max_free == vm_map_entry_max_free_left(root, llist),	\
1092 	    ("%s: max_free not copied from left", __func__));		\
1093 	root->right = llist;						\
1094 	llist = root;							\
1095 	root = y != rlist ? y : NULL;					\
1096 } while (0)
1097 
1098 /*
1099  * Walk down the tree until we find addr or a gap where addr would go, breaking
1100  * off left and right subtrees of nodes less than, or greater than addr.  Treat
1101  * subtrees with root->max_free < length as empty trees.  llist and rlist are
1102  * the two sides in reverse order (bottom-up), with llist linked by the right
1103  * pointer and rlist linked by the left pointer in the vm_map_entry, and both
1104  * lists terminated by &map->header.  This function, and the subsequent call to
1105  * vm_map_splay_merge_{left,right,pred,succ}, rely on the start and end address
1106  * values in &map->header.
1107  */
1108 static __always_inline vm_map_entry_t
1109 vm_map_splay_split(vm_map_t map, vm_offset_t addr, vm_size_t length,
1110     vm_map_entry_t *llist, vm_map_entry_t *rlist)
1111 {
1112 	vm_map_entry_t left, right, root, y;
1113 
1114 	left = right = &map->header;
1115 	root = map->root;
1116 	while (root != NULL && root->max_free >= length) {
1117 		KASSERT(left->end <= root->start &&
1118 		    root->end <= right->start,
1119 		    ("%s: root not within tree bounds", __func__));
1120 		if (addr < root->start) {
1121 			SPLAY_LEFT_STEP(root, y, left, right,
1122 			    y->max_free >= length && addr < y->start);
1123 		} else if (addr >= root->end) {
1124 			SPLAY_RIGHT_STEP(root, y, left, right,
1125 			    y->max_free >= length && addr >= y->end);
1126 		} else
1127 			break;
1128 	}
1129 	*llist = left;
1130 	*rlist = right;
1131 	return (root);
1132 }
1133 
1134 static __always_inline void
1135 vm_map_splay_findnext(vm_map_entry_t root, vm_map_entry_t *rlist)
1136 {
1137 	vm_map_entry_t hi, right, y;
1138 
1139 	right = *rlist;
1140 	hi = root->right == right ? NULL : root->right;
1141 	if (hi == NULL)
1142 		return;
1143 	do
1144 		SPLAY_LEFT_STEP(hi, y, root, right, true);
1145 	while (hi != NULL);
1146 	*rlist = right;
1147 }
1148 
1149 static __always_inline void
1150 vm_map_splay_findprev(vm_map_entry_t root, vm_map_entry_t *llist)
1151 {
1152 	vm_map_entry_t left, lo, y;
1153 
1154 	left = *llist;
1155 	lo = root->left == left ? NULL : root->left;
1156 	if (lo == NULL)
1157 		return;
1158 	do
1159 		SPLAY_RIGHT_STEP(lo, y, left, root, true);
1160 	while (lo != NULL);
1161 	*llist = left;
1162 }
1163 
1164 static inline void
1165 vm_map_entry_swap(vm_map_entry_t *a, vm_map_entry_t *b)
1166 {
1167 	vm_map_entry_t tmp;
1168 
1169 	tmp = *b;
1170 	*b = *a;
1171 	*a = tmp;
1172 }
1173 
1174 /*
1175  * Walk back up the two spines, flip the pointers and set max_free.  The
1176  * subtrees of the root go at the bottom of llist and rlist.
1177  */
1178 static vm_size_t
1179 vm_map_splay_merge_left_walk(vm_map_entry_t header, vm_map_entry_t root,
1180     vm_map_entry_t tail, vm_size_t max_free, vm_map_entry_t llist)
1181 {
1182 	do {
1183 		/*
1184 		 * The max_free values of the children of llist are in
1185 		 * llist->max_free and max_free.  Update with the
1186 		 * max value.
1187 		 */
1188 		llist->max_free = max_free =
1189 		    vm_size_max(llist->max_free, max_free);
1190 		vm_map_entry_swap(&llist->right, &tail);
1191 		vm_map_entry_swap(&tail, &llist);
1192 	} while (llist != header);
1193 	root->left = tail;
1194 	return (max_free);
1195 }
1196 
1197 /*
1198  * When llist is known to be the predecessor of root.
1199  */
1200 static inline vm_size_t
1201 vm_map_splay_merge_pred(vm_map_entry_t header, vm_map_entry_t root,
1202     vm_map_entry_t llist)
1203 {
1204 	vm_size_t max_free;
1205 
1206 	max_free = root->start - llist->end;
1207 	if (llist != header) {
1208 		max_free = vm_map_splay_merge_left_walk(header, root,
1209 		    root, max_free, llist);
1210 	} else {
1211 		root->left = header;
1212 		header->right = root;
1213 	}
1214 	return (max_free);
1215 }
1216 
1217 /*
1218  * When llist may or may not be the predecessor of root.
1219  */
1220 static inline vm_size_t
1221 vm_map_splay_merge_left(vm_map_entry_t header, vm_map_entry_t root,
1222     vm_map_entry_t llist)
1223 {
1224 	vm_size_t max_free;
1225 
1226 	max_free = vm_map_entry_max_free_left(root, llist);
1227 	if (llist != header) {
1228 		max_free = vm_map_splay_merge_left_walk(header, root,
1229 		    root->left == llist ? root : root->left,
1230 		    max_free, llist);
1231 	}
1232 	return (max_free);
1233 }
1234 
1235 static vm_size_t
1236 vm_map_splay_merge_right_walk(vm_map_entry_t header, vm_map_entry_t root,
1237     vm_map_entry_t tail, vm_size_t max_free, vm_map_entry_t rlist)
1238 {
1239 	do {
1240 		/*
1241 		 * The max_free values of the children of rlist are in
1242 		 * rlist->max_free and max_free.  Update with the
1243 		 * max value.
1244 		 */
1245 		rlist->max_free = max_free =
1246 		    vm_size_max(rlist->max_free, max_free);
1247 		vm_map_entry_swap(&rlist->left, &tail);
1248 		vm_map_entry_swap(&tail, &rlist);
1249 	} while (rlist != header);
1250 	root->right = tail;
1251 	return (max_free);
1252 }
1253 
1254 /*
1255  * When rlist is known to be the succecessor of root.
1256  */
1257 static inline vm_size_t
1258 vm_map_splay_merge_succ(vm_map_entry_t header, vm_map_entry_t root,
1259     vm_map_entry_t rlist)
1260 {
1261 	vm_size_t max_free;
1262 
1263 	max_free = rlist->start - root->end;
1264 	if (rlist != header) {
1265 		max_free = vm_map_splay_merge_right_walk(header, root,
1266 		    root, max_free, rlist);
1267 	} else {
1268 		root->right = header;
1269 		header->left = root;
1270 	}
1271 	return (max_free);
1272 }
1273 
1274 /*
1275  * When rlist may or may not be the succecessor of root.
1276  */
1277 static inline vm_size_t
1278 vm_map_splay_merge_right(vm_map_entry_t header, vm_map_entry_t root,
1279     vm_map_entry_t rlist)
1280 {
1281 	vm_size_t max_free;
1282 
1283 	max_free = vm_map_entry_max_free_right(root, rlist);
1284 	if (rlist != header) {
1285 		max_free = vm_map_splay_merge_right_walk(header, root,
1286 		    root->right == rlist ? root : root->right,
1287 		    max_free, rlist);
1288 	}
1289 	return (max_free);
1290 }
1291 
1292 /*
1293  *	vm_map_splay:
1294  *
1295  *	The Sleator and Tarjan top-down splay algorithm with the
1296  *	following variation.  Max_free must be computed bottom-up, so
1297  *	on the downward pass, maintain the left and right spines in
1298  *	reverse order.  Then, make a second pass up each side to fix
1299  *	the pointers and compute max_free.  The time bound is O(log n)
1300  *	amortized.
1301  *
1302  *	The tree is threaded, which means that there are no null pointers.
1303  *	When a node has no left child, its left pointer points to its
1304  *	predecessor, which the last ancestor on the search path from the root
1305  *	where the search branched right.  Likewise, when a node has no right
1306  *	child, its right pointer points to its successor.  The map header node
1307  *	is the predecessor of the first map entry, and the successor of the
1308  *	last.
1309  *
1310  *	The new root is the vm_map_entry containing "addr", or else an
1311  *	adjacent entry (lower if possible) if addr is not in the tree.
1312  *
1313  *	The map must be locked, and leaves it so.
1314  *
1315  *	Returns: the new root.
1316  */
1317 static vm_map_entry_t
1318 vm_map_splay(vm_map_t map, vm_offset_t addr)
1319 {
1320 	vm_map_entry_t header, llist, rlist, root;
1321 	vm_size_t max_free_left, max_free_right;
1322 
1323 	header = &map->header;
1324 	root = vm_map_splay_split(map, addr, 0, &llist, &rlist);
1325 	if (root != NULL) {
1326 		max_free_left = vm_map_splay_merge_left(header, root, llist);
1327 		max_free_right = vm_map_splay_merge_right(header, root, rlist);
1328 	} else if (llist != header) {
1329 		/*
1330 		 * Recover the greatest node in the left
1331 		 * subtree and make it the root.
1332 		 */
1333 		root = llist;
1334 		llist = root->right;
1335 		max_free_left = vm_map_splay_merge_left(header, root, llist);
1336 		max_free_right = vm_map_splay_merge_succ(header, root, rlist);
1337 	} else if (rlist != header) {
1338 		/*
1339 		 * Recover the least node in the right
1340 		 * subtree and make it the root.
1341 		 */
1342 		root = rlist;
1343 		rlist = root->left;
1344 		max_free_left = vm_map_splay_merge_pred(header, root, llist);
1345 		max_free_right = vm_map_splay_merge_right(header, root, rlist);
1346 	} else {
1347 		/* There is no root. */
1348 		return (NULL);
1349 	}
1350 	root->max_free = vm_size_max(max_free_left, max_free_right);
1351 	map->root = root;
1352 	VM_MAP_ASSERT_CONSISTENT(map);
1353 	return (root);
1354 }
1355 
1356 /*
1357  *	vm_map_entry_{un,}link:
1358  *
1359  *	Insert/remove entries from maps.
1360  */
1361 static void
1362 vm_map_entry_link(vm_map_t map, vm_map_entry_t entry)
1363 {
1364 	vm_map_entry_t header, llist, rlist, root;
1365 
1366 	CTR3(KTR_VM,
1367 	    "vm_map_entry_link: map %p, nentries %d, entry %p", map,
1368 	    map->nentries, entry);
1369 	VM_MAP_ASSERT_LOCKED(map);
1370 	map->nentries++;
1371 	header = &map->header;
1372 	root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
1373 	KASSERT(root == NULL,
1374 	    ("vm_map_entry_link: link object already mapped"));
1375 	root = entry;
1376 	root->max_free = vm_size_max(
1377 	    vm_map_splay_merge_pred(header, root, llist),
1378 	    vm_map_splay_merge_succ(header, root, rlist));
1379 	map->root = root;
1380 	VM_MAP_ASSERT_CONSISTENT(map);
1381 }
1382 
1383 enum unlink_merge_type {
1384 	UNLINK_MERGE_NONE,
1385 	UNLINK_MERGE_NEXT
1386 };
1387 
1388 static void
1389 vm_map_entry_unlink(vm_map_t map, vm_map_entry_t entry,
1390     enum unlink_merge_type op)
1391 {
1392 	vm_map_entry_t header, llist, rlist, root;
1393 	vm_size_t max_free_left, max_free_right;
1394 
1395 	VM_MAP_ASSERT_LOCKED(map);
1396 	header = &map->header;
1397 	root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
1398 	KASSERT(root != NULL,
1399 	    ("vm_map_entry_unlink: unlink object not mapped"));
1400 
1401 	vm_map_splay_findprev(root, &llist);
1402 	vm_map_splay_findnext(root, &rlist);
1403 	if (op == UNLINK_MERGE_NEXT) {
1404 		rlist->start = root->start;
1405 		rlist->offset = root->offset;
1406 	}
1407 	if (llist != header) {
1408 		root = llist;
1409 		llist = root->right;
1410 		max_free_left = vm_map_splay_merge_left(header, root, llist);
1411 		max_free_right = vm_map_splay_merge_succ(header, root, rlist);
1412 	} else if (rlist != header) {
1413 		root = rlist;
1414 		rlist = root->left;
1415 		max_free_left = vm_map_splay_merge_pred(header, root, llist);
1416 		max_free_right = vm_map_splay_merge_right(header, root, rlist);
1417 	} else {
1418 		header->left = header->right = header;
1419 		root = NULL;
1420 	}
1421 	if (root != NULL)
1422 		root->max_free = vm_size_max(max_free_left, max_free_right);
1423 	map->root = root;
1424 	VM_MAP_ASSERT_CONSISTENT(map);
1425 	map->nentries--;
1426 	CTR3(KTR_VM, "vm_map_entry_unlink: map %p, nentries %d, entry %p", map,
1427 	    map->nentries, entry);
1428 }
1429 
1430 /*
1431  *	vm_map_entry_resize:
1432  *
1433  *	Resize a vm_map_entry, recompute the amount of free space that
1434  *	follows it and propagate that value up the tree.
1435  *
1436  *	The map must be locked, and leaves it so.
1437  */
1438 static void
1439 vm_map_entry_resize(vm_map_t map, vm_map_entry_t entry, vm_size_t grow_amount)
1440 {
1441 	vm_map_entry_t header, llist, rlist, root;
1442 
1443 	VM_MAP_ASSERT_LOCKED(map);
1444 	header = &map->header;
1445 	root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
1446 	KASSERT(root != NULL, ("%s: resize object not mapped", __func__));
1447 	vm_map_splay_findnext(root, &rlist);
1448 	entry->end += grow_amount;
1449 	root->max_free = vm_size_max(
1450 	    vm_map_splay_merge_left(header, root, llist),
1451 	    vm_map_splay_merge_succ(header, root, rlist));
1452 	map->root = root;
1453 	VM_MAP_ASSERT_CONSISTENT(map);
1454 	CTR4(KTR_VM, "%s: map %p, nentries %d, entry %p",
1455 	    __func__, map, map->nentries, entry);
1456 }
1457 
1458 /*
1459  *	vm_map_lookup_entry:	[ internal use only ]
1460  *
1461  *	Finds the map entry containing (or
1462  *	immediately preceding) the specified address
1463  *	in the given map; the entry is returned
1464  *	in the "entry" parameter.  The boolean
1465  *	result indicates whether the address is
1466  *	actually contained in the map.
1467  */
1468 boolean_t
1469 vm_map_lookup_entry(
1470 	vm_map_t map,
1471 	vm_offset_t address,
1472 	vm_map_entry_t *entry)	/* OUT */
1473 {
1474 	vm_map_entry_t cur, header, lbound, ubound;
1475 	boolean_t locked;
1476 
1477 	/*
1478 	 * If the map is empty, then the map entry immediately preceding
1479 	 * "address" is the map's header.
1480 	 */
1481 	header = &map->header;
1482 	cur = map->root;
1483 	if (cur == NULL) {
1484 		*entry = header;
1485 		return (FALSE);
1486 	}
1487 	if (address >= cur->start && cur->end > address) {
1488 		*entry = cur;
1489 		return (TRUE);
1490 	}
1491 	if ((locked = vm_map_locked(map)) ||
1492 	    sx_try_upgrade(&map->lock)) {
1493 		/*
1494 		 * Splay requires a write lock on the map.  However, it only
1495 		 * restructures the binary search tree; it does not otherwise
1496 		 * change the map.  Thus, the map's timestamp need not change
1497 		 * on a temporary upgrade.
1498 		 */
1499 		cur = vm_map_splay(map, address);
1500 		if (!locked) {
1501 			VM_MAP_UNLOCK_CONSISTENT(map);
1502 			sx_downgrade(&map->lock);
1503 		}
1504 
1505 		/*
1506 		 * If "address" is contained within a map entry, the new root
1507 		 * is that map entry.  Otherwise, the new root is a map entry
1508 		 * immediately before or after "address".
1509 		 */
1510 		if (address < cur->start) {
1511 			*entry = header;
1512 			return (FALSE);
1513 		}
1514 		*entry = cur;
1515 		return (address < cur->end);
1516 	}
1517 	/*
1518 	 * Since the map is only locked for read access, perform a
1519 	 * standard binary search tree lookup for "address".
1520 	 */
1521 	lbound = ubound = header;
1522 	for (;;) {
1523 		if (address < cur->start) {
1524 			ubound = cur;
1525 			cur = cur->left;
1526 			if (cur == lbound)
1527 				break;
1528 		} else if (cur->end <= address) {
1529 			lbound = cur;
1530 			cur = cur->right;
1531 			if (cur == ubound)
1532 				break;
1533 		} else {
1534 			*entry = cur;
1535 			return (TRUE);
1536 		}
1537 	}
1538 	*entry = lbound;
1539 	return (FALSE);
1540 }
1541 
1542 /*
1543  *	vm_map_insert:
1544  *
1545  *	Inserts the given whole VM object into the target
1546  *	map at the specified address range.  The object's
1547  *	size should match that of the address range.
1548  *
1549  *	Requires that the map be locked, and leaves it so.
1550  *
1551  *	If object is non-NULL, ref count must be bumped by caller
1552  *	prior to making call to account for the new entry.
1553  */
1554 int
1555 vm_map_insert(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1556     vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max, int cow)
1557 {
1558 	vm_map_entry_t new_entry, next_entry, prev_entry;
1559 	struct ucred *cred;
1560 	vm_eflags_t protoeflags;
1561 	vm_inherit_t inheritance;
1562 
1563 	VM_MAP_ASSERT_LOCKED(map);
1564 	KASSERT(object != kernel_object ||
1565 	    (cow & MAP_COPY_ON_WRITE) == 0,
1566 	    ("vm_map_insert: kernel object and COW"));
1567 	KASSERT(object == NULL || (cow & MAP_NOFAULT) == 0,
1568 	    ("vm_map_insert: paradoxical MAP_NOFAULT request"));
1569 	KASSERT((prot & ~max) == 0,
1570 	    ("prot %#x is not subset of max_prot %#x", prot, max));
1571 
1572 	/*
1573 	 * Check that the start and end points are not bogus.
1574 	 */
1575 	if (start < vm_map_min(map) || end > vm_map_max(map) ||
1576 	    start >= end)
1577 		return (KERN_INVALID_ADDRESS);
1578 
1579 	/*
1580 	 * Find the entry prior to the proposed starting address; if it's part
1581 	 * of an existing entry, this range is bogus.
1582 	 */
1583 	if (vm_map_lookup_entry(map, start, &prev_entry))
1584 		return (KERN_NO_SPACE);
1585 
1586 	/*
1587 	 * Assert that the next entry doesn't overlap the end point.
1588 	 */
1589 	next_entry = vm_map_entry_succ(prev_entry);
1590 	if (next_entry->start < end)
1591 		return (KERN_NO_SPACE);
1592 
1593 	if ((cow & MAP_CREATE_GUARD) != 0 && (object != NULL ||
1594 	    max != VM_PROT_NONE))
1595 		return (KERN_INVALID_ARGUMENT);
1596 
1597 	protoeflags = 0;
1598 	if (cow & MAP_COPY_ON_WRITE)
1599 		protoeflags |= MAP_ENTRY_COW | MAP_ENTRY_NEEDS_COPY;
1600 	if (cow & MAP_NOFAULT)
1601 		protoeflags |= MAP_ENTRY_NOFAULT;
1602 	if (cow & MAP_DISABLE_SYNCER)
1603 		protoeflags |= MAP_ENTRY_NOSYNC;
1604 	if (cow & MAP_DISABLE_COREDUMP)
1605 		protoeflags |= MAP_ENTRY_NOCOREDUMP;
1606 	if (cow & MAP_STACK_GROWS_DOWN)
1607 		protoeflags |= MAP_ENTRY_GROWS_DOWN;
1608 	if (cow & MAP_STACK_GROWS_UP)
1609 		protoeflags |= MAP_ENTRY_GROWS_UP;
1610 	if (cow & MAP_WRITECOUNT)
1611 		protoeflags |= MAP_ENTRY_WRITECNT;
1612 	if (cow & MAP_VN_EXEC)
1613 		protoeflags |= MAP_ENTRY_VN_EXEC;
1614 	if ((cow & MAP_CREATE_GUARD) != 0)
1615 		protoeflags |= MAP_ENTRY_GUARD;
1616 	if ((cow & MAP_CREATE_STACK_GAP_DN) != 0)
1617 		protoeflags |= MAP_ENTRY_STACK_GAP_DN;
1618 	if ((cow & MAP_CREATE_STACK_GAP_UP) != 0)
1619 		protoeflags |= MAP_ENTRY_STACK_GAP_UP;
1620 	if (cow & MAP_INHERIT_SHARE)
1621 		inheritance = VM_INHERIT_SHARE;
1622 	else
1623 		inheritance = VM_INHERIT_DEFAULT;
1624 
1625 	cred = NULL;
1626 	if ((cow & (MAP_ACC_NO_CHARGE | MAP_NOFAULT | MAP_CREATE_GUARD)) != 0)
1627 		goto charged;
1628 	if ((cow & MAP_ACC_CHARGED) || ((prot & VM_PROT_WRITE) &&
1629 	    ((protoeflags & MAP_ENTRY_NEEDS_COPY) || object == NULL))) {
1630 		if (!(cow & MAP_ACC_CHARGED) && !swap_reserve(end - start))
1631 			return (KERN_RESOURCE_SHORTAGE);
1632 		KASSERT(object == NULL ||
1633 		    (protoeflags & MAP_ENTRY_NEEDS_COPY) != 0 ||
1634 		    object->cred == NULL,
1635 		    ("overcommit: vm_map_insert o %p", object));
1636 		cred = curthread->td_ucred;
1637 	}
1638 
1639 charged:
1640 	/* Expand the kernel pmap, if necessary. */
1641 	if (map == kernel_map && end > kernel_vm_end)
1642 		pmap_growkernel(end);
1643 	if (object != NULL) {
1644 		/*
1645 		 * OBJ_ONEMAPPING must be cleared unless this mapping
1646 		 * is trivially proven to be the only mapping for any
1647 		 * of the object's pages.  (Object granularity
1648 		 * reference counting is insufficient to recognize
1649 		 * aliases with precision.)
1650 		 */
1651 		if ((object->flags & OBJ_ANON) != 0) {
1652 			VM_OBJECT_WLOCK(object);
1653 			if (object->ref_count > 1 || object->shadow_count != 0)
1654 				vm_object_clear_flag(object, OBJ_ONEMAPPING);
1655 			VM_OBJECT_WUNLOCK(object);
1656 		}
1657 	} else if ((prev_entry->eflags & ~MAP_ENTRY_USER_WIRED) ==
1658 	    protoeflags &&
1659 	    (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP |
1660 	    MAP_VN_EXEC)) == 0 &&
1661 	    prev_entry->end == start && (prev_entry->cred == cred ||
1662 	    (prev_entry->object.vm_object != NULL &&
1663 	    prev_entry->object.vm_object->cred == cred)) &&
1664 	    vm_object_coalesce(prev_entry->object.vm_object,
1665 	    prev_entry->offset,
1666 	    (vm_size_t)(prev_entry->end - prev_entry->start),
1667 	    (vm_size_t)(end - prev_entry->end), cred != NULL &&
1668 	    (protoeflags & MAP_ENTRY_NEEDS_COPY) == 0)) {
1669 		/*
1670 		 * We were able to extend the object.  Determine if we
1671 		 * can extend the previous map entry to include the
1672 		 * new range as well.
1673 		 */
1674 		if (prev_entry->inheritance == inheritance &&
1675 		    prev_entry->protection == prot &&
1676 		    prev_entry->max_protection == max &&
1677 		    prev_entry->wired_count == 0) {
1678 			KASSERT((prev_entry->eflags & MAP_ENTRY_USER_WIRED) ==
1679 			    0, ("prev_entry %p has incoherent wiring",
1680 			    prev_entry));
1681 			if ((prev_entry->eflags & MAP_ENTRY_GUARD) == 0)
1682 				map->size += end - prev_entry->end;
1683 			vm_map_entry_resize(map, prev_entry,
1684 			    end - prev_entry->end);
1685 			vm_map_try_merge_entries(map, prev_entry, next_entry);
1686 			return (KERN_SUCCESS);
1687 		}
1688 
1689 		/*
1690 		 * If we can extend the object but cannot extend the
1691 		 * map entry, we have to create a new map entry.  We
1692 		 * must bump the ref count on the extended object to
1693 		 * account for it.  object may be NULL.
1694 		 */
1695 		object = prev_entry->object.vm_object;
1696 		offset = prev_entry->offset +
1697 		    (prev_entry->end - prev_entry->start);
1698 		vm_object_reference(object);
1699 		if (cred != NULL && object != NULL && object->cred != NULL &&
1700 		    !(prev_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
1701 			/* Object already accounts for this uid. */
1702 			cred = NULL;
1703 		}
1704 	}
1705 	if (cred != NULL)
1706 		crhold(cred);
1707 
1708 	/*
1709 	 * Create a new entry
1710 	 */
1711 	new_entry = vm_map_entry_create(map);
1712 	new_entry->start = start;
1713 	new_entry->end = end;
1714 	new_entry->cred = NULL;
1715 
1716 	new_entry->eflags = protoeflags;
1717 	new_entry->object.vm_object = object;
1718 	new_entry->offset = offset;
1719 
1720 	new_entry->inheritance = inheritance;
1721 	new_entry->protection = prot;
1722 	new_entry->max_protection = max;
1723 	new_entry->wired_count = 0;
1724 	new_entry->wiring_thread = NULL;
1725 	new_entry->read_ahead = VM_FAULT_READ_AHEAD_INIT;
1726 	new_entry->next_read = start;
1727 
1728 	KASSERT(cred == NULL || !ENTRY_CHARGED(new_entry),
1729 	    ("overcommit: vm_map_insert leaks vm_map %p", new_entry));
1730 	new_entry->cred = cred;
1731 
1732 	/*
1733 	 * Insert the new entry into the list
1734 	 */
1735 	vm_map_entry_link(map, new_entry);
1736 	if ((new_entry->eflags & MAP_ENTRY_GUARD) == 0)
1737 		map->size += new_entry->end - new_entry->start;
1738 
1739 	/*
1740 	 * Try to coalesce the new entry with both the previous and next
1741 	 * entries in the list.  Previously, we only attempted to coalesce
1742 	 * with the previous entry when object is NULL.  Here, we handle the
1743 	 * other cases, which are less common.
1744 	 */
1745 	vm_map_try_merge_entries(map, prev_entry, new_entry);
1746 	vm_map_try_merge_entries(map, new_entry, next_entry);
1747 
1748 	if ((cow & (MAP_PREFAULT | MAP_PREFAULT_PARTIAL)) != 0) {
1749 		vm_map_pmap_enter(map, start, prot, object, OFF_TO_IDX(offset),
1750 		    end - start, cow & MAP_PREFAULT_PARTIAL);
1751 	}
1752 
1753 	return (KERN_SUCCESS);
1754 }
1755 
1756 /*
1757  *	vm_map_findspace:
1758  *
1759  *	Find the first fit (lowest VM address) for "length" free bytes
1760  *	beginning at address >= start in the given map.
1761  *
1762  *	In a vm_map_entry, "max_free" is the maximum amount of
1763  *	contiguous free space between an entry in its subtree and a
1764  *	neighbor of that entry.  This allows finding a free region in
1765  *	one path down the tree, so O(log n) amortized with splay
1766  *	trees.
1767  *
1768  *	The map must be locked, and leaves it so.
1769  *
1770  *	Returns: starting address if sufficient space,
1771  *		 vm_map_max(map)-length+1 if insufficient space.
1772  */
1773 vm_offset_t
1774 vm_map_findspace(vm_map_t map, vm_offset_t start, vm_size_t length)
1775 {
1776 	vm_map_entry_t header, llist, rlist, root, y;
1777 	vm_size_t left_length, max_free_left, max_free_right;
1778 	vm_offset_t gap_end;
1779 
1780 	/*
1781 	 * Request must fit within min/max VM address and must avoid
1782 	 * address wrap.
1783 	 */
1784 	start = MAX(start, vm_map_min(map));
1785 	if (start >= vm_map_max(map) || length > vm_map_max(map) - start)
1786 		return (vm_map_max(map) - length + 1);
1787 
1788 	/* Empty tree means wide open address space. */
1789 	if (map->root == NULL)
1790 		return (start);
1791 
1792 	/*
1793 	 * After splay_split, if start is within an entry, push it to the start
1794 	 * of the following gap.  If rlist is at the end of the gap containing
1795 	 * start, save the end of that gap in gap_end to see if the gap is big
1796 	 * enough; otherwise set gap_end to start skip gap-checking and move
1797 	 * directly to a search of the right subtree.
1798 	 */
1799 	header = &map->header;
1800 	root = vm_map_splay_split(map, start, length, &llist, &rlist);
1801 	gap_end = rlist->start;
1802 	if (root != NULL) {
1803 		start = root->end;
1804 		if (root->right != rlist)
1805 			gap_end = start;
1806 		max_free_left = vm_map_splay_merge_left(header, root, llist);
1807 		max_free_right = vm_map_splay_merge_right(header, root, rlist);
1808 	} else if (rlist != header) {
1809 		root = rlist;
1810 		rlist = root->left;
1811 		max_free_left = vm_map_splay_merge_pred(header, root, llist);
1812 		max_free_right = vm_map_splay_merge_right(header, root, rlist);
1813 	} else {
1814 		root = llist;
1815 		llist = root->right;
1816 		max_free_left = vm_map_splay_merge_left(header, root, llist);
1817 		max_free_right = vm_map_splay_merge_succ(header, root, rlist);
1818 	}
1819 	root->max_free = vm_size_max(max_free_left, max_free_right);
1820 	map->root = root;
1821 	VM_MAP_ASSERT_CONSISTENT(map);
1822 	if (length <= gap_end - start)
1823 		return (start);
1824 
1825 	/* With max_free, can immediately tell if no solution. */
1826 	if (root->right == header || length > root->right->max_free)
1827 		return (vm_map_max(map) - length + 1);
1828 
1829 	/*
1830 	 * Splay for the least large-enough gap in the right subtree.
1831 	 */
1832 	llist = rlist = header;
1833 	for (left_length = 0;;
1834 	    left_length = vm_map_entry_max_free_left(root, llist)) {
1835 		if (length <= left_length)
1836 			SPLAY_LEFT_STEP(root, y, llist, rlist,
1837 			    length <= vm_map_entry_max_free_left(y, llist));
1838 		else
1839 			SPLAY_RIGHT_STEP(root, y, llist, rlist,
1840 			    length > vm_map_entry_max_free_left(y, root));
1841 		if (root == NULL)
1842 			break;
1843 	}
1844 	root = llist;
1845 	llist = root->right;
1846 	max_free_left = vm_map_splay_merge_left(header, root, llist);
1847 	if (rlist == header) {
1848 		root->max_free = vm_size_max(max_free_left,
1849 		    vm_map_splay_merge_succ(header, root, rlist));
1850 	} else {
1851 		y = rlist;
1852 		rlist = y->left;
1853 		y->max_free = vm_size_max(
1854 		    vm_map_splay_merge_pred(root, y, root),
1855 		    vm_map_splay_merge_right(header, y, rlist));
1856 		root->max_free = vm_size_max(max_free_left, y->max_free);
1857 	}
1858 	map->root = root;
1859 	VM_MAP_ASSERT_CONSISTENT(map);
1860 	return (root->end);
1861 }
1862 
1863 int
1864 vm_map_fixed(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1865     vm_offset_t start, vm_size_t length, vm_prot_t prot,
1866     vm_prot_t max, int cow)
1867 {
1868 	vm_offset_t end;
1869 	int result;
1870 
1871 	end = start + length;
1872 	KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
1873 	    object == NULL,
1874 	    ("vm_map_fixed: non-NULL backing object for stack"));
1875 	vm_map_lock(map);
1876 	VM_MAP_RANGE_CHECK(map, start, end);
1877 	if ((cow & MAP_CHECK_EXCL) == 0)
1878 		vm_map_delete(map, start, end);
1879 	if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
1880 		result = vm_map_stack_locked(map, start, length, sgrowsiz,
1881 		    prot, max, cow);
1882 	} else {
1883 		result = vm_map_insert(map, object, offset, start, end,
1884 		    prot, max, cow);
1885 	}
1886 	vm_map_unlock(map);
1887 	return (result);
1888 }
1889 
1890 static const int aslr_pages_rnd_64[2] = {0x1000, 0x10};
1891 static const int aslr_pages_rnd_32[2] = {0x100, 0x4};
1892 
1893 static int cluster_anon = 1;
1894 SYSCTL_INT(_vm, OID_AUTO, cluster_anon, CTLFLAG_RW,
1895     &cluster_anon, 0,
1896     "Cluster anonymous mappings: 0 = no, 1 = yes if no hint, 2 = always");
1897 
1898 static bool
1899 clustering_anon_allowed(vm_offset_t addr)
1900 {
1901 
1902 	switch (cluster_anon) {
1903 	case 0:
1904 		return (false);
1905 	case 1:
1906 		return (addr == 0);
1907 	case 2:
1908 	default:
1909 		return (true);
1910 	}
1911 }
1912 
1913 static long aslr_restarts;
1914 SYSCTL_LONG(_vm, OID_AUTO, aslr_restarts, CTLFLAG_RD,
1915     &aslr_restarts, 0,
1916     "Number of aslr failures");
1917 
1918 #define	MAP_32BIT_MAX_ADDR	((vm_offset_t)1 << 31)
1919 
1920 /*
1921  * Searches for the specified amount of free space in the given map with the
1922  * specified alignment.  Performs an address-ordered, first-fit search from
1923  * the given address "*addr", with an optional upper bound "max_addr".  If the
1924  * parameter "alignment" is zero, then the alignment is computed from the
1925  * given (object, offset) pair so as to enable the greatest possible use of
1926  * superpage mappings.  Returns KERN_SUCCESS and the address of the free space
1927  * in "*addr" if successful.  Otherwise, returns KERN_NO_SPACE.
1928  *
1929  * The map must be locked.  Initially, there must be at least "length" bytes
1930  * of free space at the given address.
1931  */
1932 static int
1933 vm_map_alignspace(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1934     vm_offset_t *addr, vm_size_t length, vm_offset_t max_addr,
1935     vm_offset_t alignment)
1936 {
1937 	vm_offset_t aligned_addr, free_addr;
1938 
1939 	VM_MAP_ASSERT_LOCKED(map);
1940 	free_addr = *addr;
1941 	KASSERT(free_addr == vm_map_findspace(map, free_addr, length),
1942 	    ("caller failed to provide space %#jx at address %p",
1943 	     (uintmax_t)length, (void *)free_addr));
1944 	for (;;) {
1945 		/*
1946 		 * At the start of every iteration, the free space at address
1947 		 * "*addr" is at least "length" bytes.
1948 		 */
1949 		if (alignment == 0)
1950 			pmap_align_superpage(object, offset, addr, length);
1951 		else if ((*addr & (alignment - 1)) != 0) {
1952 			*addr &= ~(alignment - 1);
1953 			*addr += alignment;
1954 		}
1955 		aligned_addr = *addr;
1956 		if (aligned_addr == free_addr) {
1957 			/*
1958 			 * Alignment did not change "*addr", so "*addr" must
1959 			 * still provide sufficient free space.
1960 			 */
1961 			return (KERN_SUCCESS);
1962 		}
1963 
1964 		/*
1965 		 * Test for address wrap on "*addr".  A wrapped "*addr" could
1966 		 * be a valid address, in which case vm_map_findspace() cannot
1967 		 * be relied upon to fail.
1968 		 */
1969 		if (aligned_addr < free_addr)
1970 			return (KERN_NO_SPACE);
1971 		*addr = vm_map_findspace(map, aligned_addr, length);
1972 		if (*addr + length > vm_map_max(map) ||
1973 		    (max_addr != 0 && *addr + length > max_addr))
1974 			return (KERN_NO_SPACE);
1975 		free_addr = *addr;
1976 		if (free_addr == aligned_addr) {
1977 			/*
1978 			 * If a successful call to vm_map_findspace() did not
1979 			 * change "*addr", then "*addr" must still be aligned
1980 			 * and provide sufficient free space.
1981 			 */
1982 			return (KERN_SUCCESS);
1983 		}
1984 	}
1985 }
1986 
1987 /*
1988  *	vm_map_find finds an unallocated region in the target address
1989  *	map with the given length.  The search is defined to be
1990  *	first-fit from the specified address; the region found is
1991  *	returned in the same parameter.
1992  *
1993  *	If object is non-NULL, ref count must be bumped by caller
1994  *	prior to making call to account for the new entry.
1995  */
1996 int
1997 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1998 	    vm_offset_t *addr,	/* IN/OUT */
1999 	    vm_size_t length, vm_offset_t max_addr, int find_space,
2000 	    vm_prot_t prot, vm_prot_t max, int cow)
2001 {
2002 	vm_offset_t alignment, curr_min_addr, min_addr;
2003 	int gap, pidx, rv, try;
2004 	bool cluster, en_aslr, update_anon;
2005 
2006 	KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
2007 	    object == NULL,
2008 	    ("vm_map_find: non-NULL backing object for stack"));
2009 	MPASS((cow & MAP_REMAP) == 0 || (find_space == VMFS_NO_SPACE &&
2010 	    (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0));
2011 	if (find_space == VMFS_OPTIMAL_SPACE && (object == NULL ||
2012 	    (object->flags & OBJ_COLORED) == 0))
2013 		find_space = VMFS_ANY_SPACE;
2014 	if (find_space >> 8 != 0) {
2015 		KASSERT((find_space & 0xff) == 0, ("bad VMFS flags"));
2016 		alignment = (vm_offset_t)1 << (find_space >> 8);
2017 	} else
2018 		alignment = 0;
2019 	en_aslr = (map->flags & MAP_ASLR) != 0;
2020 	update_anon = cluster = clustering_anon_allowed(*addr) &&
2021 	    (map->flags & MAP_IS_SUB_MAP) == 0 && max_addr == 0 &&
2022 	    find_space != VMFS_NO_SPACE && object == NULL &&
2023 	    (cow & (MAP_INHERIT_SHARE | MAP_STACK_GROWS_UP |
2024 	    MAP_STACK_GROWS_DOWN)) == 0 && prot != PROT_NONE;
2025 	curr_min_addr = min_addr = *addr;
2026 	if (en_aslr && min_addr == 0 && !cluster &&
2027 	    find_space != VMFS_NO_SPACE &&
2028 	    (map->flags & MAP_ASLR_IGNSTART) != 0)
2029 		curr_min_addr = min_addr = vm_map_min(map);
2030 	try = 0;
2031 	vm_map_lock(map);
2032 	if (cluster) {
2033 		curr_min_addr = map->anon_loc;
2034 		if (curr_min_addr == 0)
2035 			cluster = false;
2036 	}
2037 	if (find_space != VMFS_NO_SPACE) {
2038 		KASSERT(find_space == VMFS_ANY_SPACE ||
2039 		    find_space == VMFS_OPTIMAL_SPACE ||
2040 		    find_space == VMFS_SUPER_SPACE ||
2041 		    alignment != 0, ("unexpected VMFS flag"));
2042 again:
2043 		/*
2044 		 * When creating an anonymous mapping, try clustering
2045 		 * with an existing anonymous mapping first.
2046 		 *
2047 		 * We make up to two attempts to find address space
2048 		 * for a given find_space value. The first attempt may
2049 		 * apply randomization or may cluster with an existing
2050 		 * anonymous mapping. If this first attempt fails,
2051 		 * perform a first-fit search of the available address
2052 		 * space.
2053 		 *
2054 		 * If all tries failed, and find_space is
2055 		 * VMFS_OPTIMAL_SPACE, fallback to VMFS_ANY_SPACE.
2056 		 * Again enable clustering and randomization.
2057 		 */
2058 		try++;
2059 		MPASS(try <= 2);
2060 
2061 		if (try == 2) {
2062 			/*
2063 			 * Second try: we failed either to find a
2064 			 * suitable region for randomizing the
2065 			 * allocation, or to cluster with an existing
2066 			 * mapping.  Retry with free run.
2067 			 */
2068 			curr_min_addr = (map->flags & MAP_ASLR_IGNSTART) != 0 ?
2069 			    vm_map_min(map) : min_addr;
2070 			atomic_add_long(&aslr_restarts, 1);
2071 		}
2072 
2073 		if (try == 1 && en_aslr && !cluster) {
2074 			/*
2075 			 * Find space for allocation, including
2076 			 * gap needed for later randomization.
2077 			 */
2078 			pidx = MAXPAGESIZES > 1 && pagesizes[1] != 0 &&
2079 			    (find_space == VMFS_SUPER_SPACE || find_space ==
2080 			    VMFS_OPTIMAL_SPACE) ? 1 : 0;
2081 			gap = vm_map_max(map) > MAP_32BIT_MAX_ADDR &&
2082 			    (max_addr == 0 || max_addr > MAP_32BIT_MAX_ADDR) ?
2083 			    aslr_pages_rnd_64[pidx] : aslr_pages_rnd_32[pidx];
2084 			*addr = vm_map_findspace(map, curr_min_addr,
2085 			    length + gap * pagesizes[pidx]);
2086 			if (*addr + length + gap * pagesizes[pidx] >
2087 			    vm_map_max(map))
2088 				goto again;
2089 			/* And randomize the start address. */
2090 			*addr += (arc4random() % gap) * pagesizes[pidx];
2091 			if (max_addr != 0 && *addr + length > max_addr)
2092 				goto again;
2093 		} else {
2094 			*addr = vm_map_findspace(map, curr_min_addr, length);
2095 			if (*addr + length > vm_map_max(map) ||
2096 			    (max_addr != 0 && *addr + length > max_addr)) {
2097 				if (cluster) {
2098 					cluster = false;
2099 					MPASS(try == 1);
2100 					goto again;
2101 				}
2102 				rv = KERN_NO_SPACE;
2103 				goto done;
2104 			}
2105 		}
2106 
2107 		if (find_space != VMFS_ANY_SPACE &&
2108 		    (rv = vm_map_alignspace(map, object, offset, addr, length,
2109 		    max_addr, alignment)) != KERN_SUCCESS) {
2110 			if (find_space == VMFS_OPTIMAL_SPACE) {
2111 				find_space = VMFS_ANY_SPACE;
2112 				curr_min_addr = min_addr;
2113 				cluster = update_anon;
2114 				try = 0;
2115 				goto again;
2116 			}
2117 			goto done;
2118 		}
2119 	} else if ((cow & MAP_REMAP) != 0) {
2120 		if (*addr < vm_map_min(map) ||
2121 		    *addr + length > vm_map_max(map) ||
2122 		    *addr + length <= length) {
2123 			rv = KERN_INVALID_ADDRESS;
2124 			goto done;
2125 		}
2126 		vm_map_delete(map, *addr, *addr + length);
2127 	}
2128 	if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
2129 		rv = vm_map_stack_locked(map, *addr, length, sgrowsiz, prot,
2130 		    max, cow);
2131 	} else {
2132 		rv = vm_map_insert(map, object, offset, *addr, *addr + length,
2133 		    prot, max, cow);
2134 	}
2135 	if (rv == KERN_SUCCESS && update_anon)
2136 		map->anon_loc = *addr + length;
2137 done:
2138 	vm_map_unlock(map);
2139 	return (rv);
2140 }
2141 
2142 /*
2143  *	vm_map_find_min() is a variant of vm_map_find() that takes an
2144  *	additional parameter (min_addr) and treats the given address
2145  *	(*addr) differently.  Specifically, it treats *addr as a hint
2146  *	and not as the minimum address where the mapping is created.
2147  *
2148  *	This function works in two phases.  First, it tries to
2149  *	allocate above the hint.  If that fails and the hint is
2150  *	greater than min_addr, it performs a second pass, replacing
2151  *	the hint with min_addr as the minimum address for the
2152  *	allocation.
2153  */
2154 int
2155 vm_map_find_min(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
2156     vm_offset_t *addr, vm_size_t length, vm_offset_t min_addr,
2157     vm_offset_t max_addr, int find_space, vm_prot_t prot, vm_prot_t max,
2158     int cow)
2159 {
2160 	vm_offset_t hint;
2161 	int rv;
2162 
2163 	hint = *addr;
2164 	for (;;) {
2165 		rv = vm_map_find(map, object, offset, addr, length, max_addr,
2166 		    find_space, prot, max, cow);
2167 		if (rv == KERN_SUCCESS || min_addr >= hint)
2168 			return (rv);
2169 		*addr = hint = min_addr;
2170 	}
2171 }
2172 
2173 /*
2174  * A map entry with any of the following flags set must not be merged with
2175  * another entry.
2176  */
2177 #define	MAP_ENTRY_NOMERGE_MASK	(MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP | \
2178 	    MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_IS_SUB_MAP | MAP_ENTRY_VN_EXEC)
2179 
2180 static bool
2181 vm_map_mergeable_neighbors(vm_map_entry_t prev, vm_map_entry_t entry)
2182 {
2183 
2184 	KASSERT((prev->eflags & MAP_ENTRY_NOMERGE_MASK) == 0 ||
2185 	    (entry->eflags & MAP_ENTRY_NOMERGE_MASK) == 0,
2186 	    ("vm_map_mergeable_neighbors: neither %p nor %p are mergeable",
2187 	    prev, entry));
2188 	return (prev->end == entry->start &&
2189 	    prev->object.vm_object == entry->object.vm_object &&
2190 	    (prev->object.vm_object == NULL ||
2191 	    prev->offset + (prev->end - prev->start) == entry->offset) &&
2192 	    prev->eflags == entry->eflags &&
2193 	    prev->protection == entry->protection &&
2194 	    prev->max_protection == entry->max_protection &&
2195 	    prev->inheritance == entry->inheritance &&
2196 	    prev->wired_count == entry->wired_count &&
2197 	    prev->cred == entry->cred);
2198 }
2199 
2200 static void
2201 vm_map_merged_neighbor_dispose(vm_map_t map, vm_map_entry_t entry)
2202 {
2203 
2204 	/*
2205 	 * If the backing object is a vnode object, vm_object_deallocate()
2206 	 * calls vrele().  However, vrele() does not lock the vnode because
2207 	 * the vnode has additional references.  Thus, the map lock can be
2208 	 * kept without causing a lock-order reversal with the vnode lock.
2209 	 *
2210 	 * Since we count the number of virtual page mappings in
2211 	 * object->un_pager.vnp.writemappings, the writemappings value
2212 	 * should not be adjusted when the entry is disposed of.
2213 	 */
2214 	if (entry->object.vm_object != NULL)
2215 		vm_object_deallocate(entry->object.vm_object);
2216 	if (entry->cred != NULL)
2217 		crfree(entry->cred);
2218 	vm_map_entry_dispose(map, entry);
2219 }
2220 
2221 /*
2222  *	vm_map_try_merge_entries:
2223  *
2224  *	Compare the given map entry to its predecessor, and merge its precessor
2225  *	into it if possible.  The entry remains valid, and may be extended.
2226  *	The predecessor may be deleted.
2227  *
2228  *	The map must be locked.
2229  */
2230 void
2231 vm_map_try_merge_entries(vm_map_t map, vm_map_entry_t prev_entry,
2232     vm_map_entry_t entry)
2233 {
2234 
2235 	VM_MAP_ASSERT_LOCKED(map);
2236 	if ((entry->eflags & MAP_ENTRY_NOMERGE_MASK) == 0 &&
2237 	    vm_map_mergeable_neighbors(prev_entry, entry)) {
2238 		vm_map_entry_unlink(map, prev_entry, UNLINK_MERGE_NEXT);
2239 		vm_map_merged_neighbor_dispose(map, prev_entry);
2240 	}
2241 }
2242 
2243 /*
2244  *	vm_map_entry_back:
2245  *
2246  *	Allocate an object to back a map entry.
2247  */
2248 static inline void
2249 vm_map_entry_back(vm_map_entry_t entry)
2250 {
2251 	vm_object_t object;
2252 
2253 	KASSERT(entry->object.vm_object == NULL,
2254 	    ("map entry %p has backing object", entry));
2255 	KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
2256 	    ("map entry %p is a submap", entry));
2257 	object = vm_object_allocate_anon(atop(entry->end - entry->start), NULL,
2258 	    entry->cred, entry->end - entry->start);
2259 	entry->object.vm_object = object;
2260 	entry->offset = 0;
2261 	entry->cred = NULL;
2262 }
2263 
2264 /*
2265  *	vm_map_entry_charge_object
2266  *
2267  *	If there is no object backing this entry, create one.  Otherwise, if
2268  *	the entry has cred, give it to the backing object.
2269  */
2270 static inline void
2271 vm_map_entry_charge_object(vm_map_t map, vm_map_entry_t entry)
2272 {
2273 
2274 	VM_MAP_ASSERT_LOCKED(map);
2275 	KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
2276 	    ("map entry %p is a submap", entry));
2277 	if (entry->object.vm_object == NULL && !map->system_map &&
2278 	    (entry->eflags & MAP_ENTRY_GUARD) == 0)
2279 		vm_map_entry_back(entry);
2280 	else if (entry->object.vm_object != NULL &&
2281 	    ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
2282 	    entry->cred != NULL) {
2283 		VM_OBJECT_WLOCK(entry->object.vm_object);
2284 		KASSERT(entry->object.vm_object->cred == NULL,
2285 		    ("OVERCOMMIT: %s: both cred e %p", __func__, entry));
2286 		entry->object.vm_object->cred = entry->cred;
2287 		entry->object.vm_object->charge = entry->end - entry->start;
2288 		VM_OBJECT_WUNLOCK(entry->object.vm_object);
2289 		entry->cred = NULL;
2290 	}
2291 }
2292 
2293 /*
2294  *	vm_map_clip_start:	[ internal use only ]
2295  *
2296  *	Asserts that the given entry begins at or after
2297  *	the specified address; if necessary,
2298  *	it splits the entry into two.
2299  */
2300 #define vm_map_clip_start(map, entry, startaddr) \
2301 { \
2302 	if (startaddr > entry->start) \
2303 		_vm_map_clip_start(map, entry, startaddr); \
2304 }
2305 
2306 /*
2307  *	This routine is called only when it is known that
2308  *	the entry must be split.
2309  */
2310 static void
2311 _vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t start)
2312 {
2313 	vm_map_entry_t new_entry;
2314 
2315 	VM_MAP_ASSERT_LOCKED(map);
2316 	KASSERT(entry->end > start && entry->start < start,
2317 	    ("_vm_map_clip_start: invalid clip of entry %p", entry));
2318 
2319 	/*
2320 	 * Create a backing object now, if none exists, so that more individual
2321 	 * objects won't be created after the map entry is split.
2322 	 */
2323 	vm_map_entry_charge_object(map, entry);
2324 
2325 	/* Clone the entry. */
2326 	new_entry = vm_map_entry_create(map);
2327 	*new_entry = *entry;
2328 
2329 	/*
2330 	 * Split off the front portion.  Insert the new entry BEFORE this one,
2331 	 * so that this entry has the specified starting address.
2332 	 */
2333 	new_entry->end = start;
2334 	entry->offset += (start - entry->start);
2335 	entry->start = start;
2336 	if (new_entry->cred != NULL)
2337 		crhold(entry->cred);
2338 
2339 	vm_map_entry_link(map, new_entry);
2340 
2341 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
2342 		vm_object_reference(new_entry->object.vm_object);
2343 		vm_map_entry_set_vnode_text(new_entry, true);
2344 		/*
2345 		 * The object->un_pager.vnp.writemappings for the
2346 		 * object of MAP_ENTRY_WRITECNT type entry shall be
2347 		 * kept as is here.  The virtual pages are
2348 		 * re-distributed among the clipped entries, so the sum is
2349 		 * left the same.
2350 		 */
2351 	}
2352 }
2353 
2354 /*
2355  *	vm_map_clip_end:	[ internal use only ]
2356  *
2357  *	Asserts that the given entry ends at or before
2358  *	the specified address; if necessary,
2359  *	it splits the entry into two.
2360  */
2361 #define vm_map_clip_end(map, entry, endaddr) \
2362 { \
2363 	if ((endaddr) < (entry->end)) \
2364 		_vm_map_clip_end((map), (entry), (endaddr)); \
2365 }
2366 
2367 /*
2368  *	This routine is called only when it is known that
2369  *	the entry must be split.
2370  */
2371 static void
2372 _vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t end)
2373 {
2374 	vm_map_entry_t new_entry;
2375 
2376 	VM_MAP_ASSERT_LOCKED(map);
2377 	KASSERT(entry->start < end && entry->end > end,
2378 	    ("_vm_map_clip_end: invalid clip of entry %p", entry));
2379 
2380 	/*
2381 	 * Create a backing object now, if none exists, so that more individual
2382 	 * objects won't be created after the map entry is split.
2383 	 */
2384 	vm_map_entry_charge_object(map, entry);
2385 
2386 	/* Clone the entry. */
2387 	new_entry = vm_map_entry_create(map);
2388 	*new_entry = *entry;
2389 
2390 	/*
2391 	 * Split off the back portion.  Insert the new entry AFTER this one,
2392 	 * so that this entry has the specified ending address.
2393 	 */
2394 	new_entry->start = entry->end = end;
2395 	new_entry->offset += (end - entry->start);
2396 	if (new_entry->cred != NULL)
2397 		crhold(entry->cred);
2398 
2399 	vm_map_entry_link(map, new_entry);
2400 
2401 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
2402 		vm_object_reference(new_entry->object.vm_object);
2403 		vm_map_entry_set_vnode_text(new_entry, true);
2404 	}
2405 }
2406 
2407 /*
2408  *	vm_map_submap:		[ kernel use only ]
2409  *
2410  *	Mark the given range as handled by a subordinate map.
2411  *
2412  *	This range must have been created with vm_map_find,
2413  *	and no other operations may have been performed on this
2414  *	range prior to calling vm_map_submap.
2415  *
2416  *	Only a limited number of operations can be performed
2417  *	within this rage after calling vm_map_submap:
2418  *		vm_fault
2419  *	[Don't try vm_map_copy!]
2420  *
2421  *	To remove a submapping, one must first remove the
2422  *	range from the superior map, and then destroy the
2423  *	submap (if desired).  [Better yet, don't try it.]
2424  */
2425 int
2426 vm_map_submap(
2427 	vm_map_t map,
2428 	vm_offset_t start,
2429 	vm_offset_t end,
2430 	vm_map_t submap)
2431 {
2432 	vm_map_entry_t entry;
2433 	int result;
2434 
2435 	result = KERN_INVALID_ARGUMENT;
2436 
2437 	vm_map_lock(submap);
2438 	submap->flags |= MAP_IS_SUB_MAP;
2439 	vm_map_unlock(submap);
2440 
2441 	vm_map_lock(map);
2442 
2443 	VM_MAP_RANGE_CHECK(map, start, end);
2444 
2445 	if (vm_map_lookup_entry(map, start, &entry)) {
2446 		vm_map_clip_start(map, entry, start);
2447 	} else
2448 		entry = vm_map_entry_succ(entry);
2449 
2450 	vm_map_clip_end(map, entry, end);
2451 
2452 	if ((entry->start == start) && (entry->end == end) &&
2453 	    ((entry->eflags & MAP_ENTRY_COW) == 0) &&
2454 	    (entry->object.vm_object == NULL)) {
2455 		entry->object.sub_map = submap;
2456 		entry->eflags |= MAP_ENTRY_IS_SUB_MAP;
2457 		result = KERN_SUCCESS;
2458 	}
2459 	vm_map_unlock(map);
2460 
2461 	if (result != KERN_SUCCESS) {
2462 		vm_map_lock(submap);
2463 		submap->flags &= ~MAP_IS_SUB_MAP;
2464 		vm_map_unlock(submap);
2465 	}
2466 	return (result);
2467 }
2468 
2469 /*
2470  * The maximum number of pages to map if MAP_PREFAULT_PARTIAL is specified
2471  */
2472 #define	MAX_INIT_PT	96
2473 
2474 /*
2475  *	vm_map_pmap_enter:
2476  *
2477  *	Preload the specified map's pmap with mappings to the specified
2478  *	object's memory-resident pages.  No further physical pages are
2479  *	allocated, and no further virtual pages are retrieved from secondary
2480  *	storage.  If the specified flags include MAP_PREFAULT_PARTIAL, then a
2481  *	limited number of page mappings are created at the low-end of the
2482  *	specified address range.  (For this purpose, a superpage mapping
2483  *	counts as one page mapping.)  Otherwise, all resident pages within
2484  *	the specified address range are mapped.
2485  */
2486 static void
2487 vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
2488     vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags)
2489 {
2490 	vm_offset_t start;
2491 	vm_page_t p, p_start;
2492 	vm_pindex_t mask, psize, threshold, tmpidx;
2493 
2494 	if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0 || object == NULL)
2495 		return;
2496 	if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
2497 		VM_OBJECT_WLOCK(object);
2498 		if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
2499 			pmap_object_init_pt(map->pmap, addr, object, pindex,
2500 			    size);
2501 			VM_OBJECT_WUNLOCK(object);
2502 			return;
2503 		}
2504 		VM_OBJECT_LOCK_DOWNGRADE(object);
2505 	} else
2506 		VM_OBJECT_RLOCK(object);
2507 
2508 	psize = atop(size);
2509 	if (psize + pindex > object->size) {
2510 		if (pindex >= object->size) {
2511 			VM_OBJECT_RUNLOCK(object);
2512 			return;
2513 		}
2514 		psize = object->size - pindex;
2515 	}
2516 
2517 	start = 0;
2518 	p_start = NULL;
2519 	threshold = MAX_INIT_PT;
2520 
2521 	p = vm_page_find_least(object, pindex);
2522 	/*
2523 	 * Assert: the variable p is either (1) the page with the
2524 	 * least pindex greater than or equal to the parameter pindex
2525 	 * or (2) NULL.
2526 	 */
2527 	for (;
2528 	     p != NULL && (tmpidx = p->pindex - pindex) < psize;
2529 	     p = TAILQ_NEXT(p, listq)) {
2530 		/*
2531 		 * don't allow an madvise to blow away our really
2532 		 * free pages allocating pv entries.
2533 		 */
2534 		if (((flags & MAP_PREFAULT_MADVISE) != 0 &&
2535 		    vm_page_count_severe()) ||
2536 		    ((flags & MAP_PREFAULT_PARTIAL) != 0 &&
2537 		    tmpidx >= threshold)) {
2538 			psize = tmpidx;
2539 			break;
2540 		}
2541 		if (vm_page_all_valid(p)) {
2542 			if (p_start == NULL) {
2543 				start = addr + ptoa(tmpidx);
2544 				p_start = p;
2545 			}
2546 			/* Jump ahead if a superpage mapping is possible. */
2547 			if (p->psind > 0 && ((addr + ptoa(tmpidx)) &
2548 			    (pagesizes[p->psind] - 1)) == 0) {
2549 				mask = atop(pagesizes[p->psind]) - 1;
2550 				if (tmpidx + mask < psize &&
2551 				    vm_page_ps_test(p, PS_ALL_VALID, NULL)) {
2552 					p += mask;
2553 					threshold += mask;
2554 				}
2555 			}
2556 		} else if (p_start != NULL) {
2557 			pmap_enter_object(map->pmap, start, addr +
2558 			    ptoa(tmpidx), p_start, prot);
2559 			p_start = NULL;
2560 		}
2561 	}
2562 	if (p_start != NULL)
2563 		pmap_enter_object(map->pmap, start, addr + ptoa(psize),
2564 		    p_start, prot);
2565 	VM_OBJECT_RUNLOCK(object);
2566 }
2567 
2568 /*
2569  *	vm_map_protect:
2570  *
2571  *	Sets the protection of the specified address
2572  *	region in the target map.  If "set_max" is
2573  *	specified, the maximum protection is to be set;
2574  *	otherwise, only the current protection is affected.
2575  */
2576 int
2577 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
2578 	       vm_prot_t new_prot, boolean_t set_max)
2579 {
2580 	vm_map_entry_t entry, first_entry, in_tran, prev_entry;
2581 	vm_object_t obj;
2582 	struct ucred *cred;
2583 	vm_prot_t old_prot;
2584 	int rv;
2585 
2586 	if (start == end)
2587 		return (KERN_SUCCESS);
2588 
2589 again:
2590 	in_tran = NULL;
2591 	vm_map_lock(map);
2592 
2593 	/*
2594 	 * Ensure that we are not concurrently wiring pages.  vm_map_wire() may
2595 	 * need to fault pages into the map and will drop the map lock while
2596 	 * doing so, and the VM object may end up in an inconsistent state if we
2597 	 * update the protection on the map entry in between faults.
2598 	 */
2599 	vm_map_wait_busy(map);
2600 
2601 	VM_MAP_RANGE_CHECK(map, start, end);
2602 
2603 	if (!vm_map_lookup_entry(map, start, &first_entry))
2604 		first_entry = vm_map_entry_succ(first_entry);
2605 
2606 	/*
2607 	 * Make a first pass to check for protection violations.
2608 	 */
2609 	for (entry = first_entry; entry->start < end;
2610 	    entry = vm_map_entry_succ(entry)) {
2611 		if ((entry->eflags & MAP_ENTRY_GUARD) != 0)
2612 			continue;
2613 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0) {
2614 			vm_map_unlock(map);
2615 			return (KERN_INVALID_ARGUMENT);
2616 		}
2617 		if ((new_prot & entry->max_protection) != new_prot) {
2618 			vm_map_unlock(map);
2619 			return (KERN_PROTECTION_FAILURE);
2620 		}
2621 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0)
2622 			in_tran = entry;
2623 	}
2624 
2625 	/*
2626 	 * Postpone the operation until all in-transition map entries have
2627 	 * stabilized.  An in-transition entry might already have its pages
2628 	 * wired and wired_count incremented, but not yet have its
2629 	 * MAP_ENTRY_USER_WIRED flag set.  In which case, we would fail to call
2630 	 * vm_fault_copy_entry() in the final loop below.
2631 	 */
2632 	if (in_tran != NULL) {
2633 		in_tran->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2634 		vm_map_unlock_and_wait(map, 0);
2635 		goto again;
2636 	}
2637 
2638 	/*
2639 	 * Before changing the protections, try to reserve swap space for any
2640 	 * private (i.e., copy-on-write) mappings that are transitioning from
2641 	 * read-only to read/write access.  If a reservation fails, break out
2642 	 * of this loop early and let the next loop simplify the entries, since
2643 	 * some may now be mergeable.
2644 	 */
2645 	rv = KERN_SUCCESS;
2646 	vm_map_clip_start(map, first_entry, start);
2647 	for (entry = first_entry; entry->start < end;
2648 	    entry = vm_map_entry_succ(entry)) {
2649 		vm_map_clip_end(map, entry, end);
2650 
2651 		if (set_max ||
2652 		    ((new_prot & ~entry->protection) & VM_PROT_WRITE) == 0 ||
2653 		    ENTRY_CHARGED(entry) ||
2654 		    (entry->eflags & MAP_ENTRY_GUARD) != 0) {
2655 			continue;
2656 		}
2657 
2658 		cred = curthread->td_ucred;
2659 		obj = entry->object.vm_object;
2660 
2661 		if (obj == NULL ||
2662 		    (entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0) {
2663 			if (!swap_reserve(entry->end - entry->start)) {
2664 				rv = KERN_RESOURCE_SHORTAGE;
2665 				end = entry->end;
2666 				break;
2667 			}
2668 			crhold(cred);
2669 			entry->cred = cred;
2670 			continue;
2671 		}
2672 
2673 		if (obj->type != OBJT_DEFAULT && obj->type != OBJT_SWAP)
2674 			continue;
2675 		VM_OBJECT_WLOCK(obj);
2676 		if (obj->type != OBJT_DEFAULT && obj->type != OBJT_SWAP) {
2677 			VM_OBJECT_WUNLOCK(obj);
2678 			continue;
2679 		}
2680 
2681 		/*
2682 		 * Charge for the whole object allocation now, since
2683 		 * we cannot distinguish between non-charged and
2684 		 * charged clipped mapping of the same object later.
2685 		 */
2686 		KASSERT(obj->charge == 0,
2687 		    ("vm_map_protect: object %p overcharged (entry %p)",
2688 		    obj, entry));
2689 		if (!swap_reserve(ptoa(obj->size))) {
2690 			VM_OBJECT_WUNLOCK(obj);
2691 			rv = KERN_RESOURCE_SHORTAGE;
2692 			end = entry->end;
2693 			break;
2694 		}
2695 
2696 		crhold(cred);
2697 		obj->cred = cred;
2698 		obj->charge = ptoa(obj->size);
2699 		VM_OBJECT_WUNLOCK(obj);
2700 	}
2701 
2702 	/*
2703 	 * If enough swap space was available, go back and fix up protections.
2704 	 * Otherwise, just simplify entries, since some may have been modified.
2705 	 * [Note that clipping is not necessary the second time.]
2706 	 */
2707 	for (prev_entry = vm_map_entry_pred(first_entry), entry = first_entry;
2708 	    entry->start < end;
2709 	    vm_map_try_merge_entries(map, prev_entry, entry),
2710 	    prev_entry = entry, entry = vm_map_entry_succ(entry)) {
2711 		if (rv != KERN_SUCCESS ||
2712 		    (entry->eflags & MAP_ENTRY_GUARD) != 0)
2713 			continue;
2714 
2715 		old_prot = entry->protection;
2716 
2717 		if (set_max)
2718 			entry->protection =
2719 			    (entry->max_protection = new_prot) &
2720 			    old_prot;
2721 		else
2722 			entry->protection = new_prot;
2723 
2724 		/*
2725 		 * For user wired map entries, the normal lazy evaluation of
2726 		 * write access upgrades through soft page faults is
2727 		 * undesirable.  Instead, immediately copy any pages that are
2728 		 * copy-on-write and enable write access in the physical map.
2729 		 */
2730 		if ((entry->eflags & MAP_ENTRY_USER_WIRED) != 0 &&
2731 		    (entry->protection & VM_PROT_WRITE) != 0 &&
2732 		    (old_prot & VM_PROT_WRITE) == 0)
2733 			vm_fault_copy_entry(map, map, entry, entry, NULL);
2734 
2735 		/*
2736 		 * When restricting access, update the physical map.  Worry
2737 		 * about copy-on-write here.
2738 		 */
2739 		if ((old_prot & ~entry->protection) != 0) {
2740 #define MASK(entry)	(((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
2741 							VM_PROT_ALL)
2742 			pmap_protect(map->pmap, entry->start,
2743 			    entry->end,
2744 			    entry->protection & MASK(entry));
2745 #undef	MASK
2746 		}
2747 	}
2748 	vm_map_try_merge_entries(map, prev_entry, entry);
2749 	vm_map_unlock(map);
2750 	return (rv);
2751 }
2752 
2753 /*
2754  *	vm_map_madvise:
2755  *
2756  *	This routine traverses a processes map handling the madvise
2757  *	system call.  Advisories are classified as either those effecting
2758  *	the vm_map_entry structure, or those effecting the underlying
2759  *	objects.
2760  */
2761 int
2762 vm_map_madvise(
2763 	vm_map_t map,
2764 	vm_offset_t start,
2765 	vm_offset_t end,
2766 	int behav)
2767 {
2768 	vm_map_entry_t entry, prev_entry;
2769 	bool modify_map;
2770 
2771 	/*
2772 	 * Some madvise calls directly modify the vm_map_entry, in which case
2773 	 * we need to use an exclusive lock on the map and we need to perform
2774 	 * various clipping operations.  Otherwise we only need a read-lock
2775 	 * on the map.
2776 	 */
2777 	switch(behav) {
2778 	case MADV_NORMAL:
2779 	case MADV_SEQUENTIAL:
2780 	case MADV_RANDOM:
2781 	case MADV_NOSYNC:
2782 	case MADV_AUTOSYNC:
2783 	case MADV_NOCORE:
2784 	case MADV_CORE:
2785 		if (start == end)
2786 			return (0);
2787 		modify_map = true;
2788 		vm_map_lock(map);
2789 		break;
2790 	case MADV_WILLNEED:
2791 	case MADV_DONTNEED:
2792 	case MADV_FREE:
2793 		if (start == end)
2794 			return (0);
2795 		modify_map = false;
2796 		vm_map_lock_read(map);
2797 		break;
2798 	default:
2799 		return (EINVAL);
2800 	}
2801 
2802 	/*
2803 	 * Locate starting entry and clip if necessary.
2804 	 */
2805 	VM_MAP_RANGE_CHECK(map, start, end);
2806 
2807 	if (vm_map_lookup_entry(map, start, &entry)) {
2808 		if (modify_map)
2809 			vm_map_clip_start(map, entry, start);
2810 		prev_entry = vm_map_entry_pred(entry);
2811 	} else {
2812 		prev_entry = entry;
2813 		entry = vm_map_entry_succ(entry);
2814 	}
2815 
2816 	if (modify_map) {
2817 		/*
2818 		 * madvise behaviors that are implemented in the vm_map_entry.
2819 		 *
2820 		 * We clip the vm_map_entry so that behavioral changes are
2821 		 * limited to the specified address range.
2822 		 */
2823 		for (; entry->start < end;
2824 		     prev_entry = entry, entry = vm_map_entry_succ(entry)) {
2825 			if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2826 				continue;
2827 
2828 			vm_map_clip_end(map, entry, end);
2829 
2830 			switch (behav) {
2831 			case MADV_NORMAL:
2832 				vm_map_entry_set_behavior(entry,
2833 				    MAP_ENTRY_BEHAV_NORMAL);
2834 				break;
2835 			case MADV_SEQUENTIAL:
2836 				vm_map_entry_set_behavior(entry,
2837 				    MAP_ENTRY_BEHAV_SEQUENTIAL);
2838 				break;
2839 			case MADV_RANDOM:
2840 				vm_map_entry_set_behavior(entry,
2841 				    MAP_ENTRY_BEHAV_RANDOM);
2842 				break;
2843 			case MADV_NOSYNC:
2844 				entry->eflags |= MAP_ENTRY_NOSYNC;
2845 				break;
2846 			case MADV_AUTOSYNC:
2847 				entry->eflags &= ~MAP_ENTRY_NOSYNC;
2848 				break;
2849 			case MADV_NOCORE:
2850 				entry->eflags |= MAP_ENTRY_NOCOREDUMP;
2851 				break;
2852 			case MADV_CORE:
2853 				entry->eflags &= ~MAP_ENTRY_NOCOREDUMP;
2854 				break;
2855 			default:
2856 				break;
2857 			}
2858 			vm_map_try_merge_entries(map, prev_entry, entry);
2859 		}
2860 		vm_map_try_merge_entries(map, prev_entry, entry);
2861 		vm_map_unlock(map);
2862 	} else {
2863 		vm_pindex_t pstart, pend;
2864 
2865 		/*
2866 		 * madvise behaviors that are implemented in the underlying
2867 		 * vm_object.
2868 		 *
2869 		 * Since we don't clip the vm_map_entry, we have to clip
2870 		 * the vm_object pindex and count.
2871 		 */
2872 		for (; entry->start < end;
2873 		    entry = vm_map_entry_succ(entry)) {
2874 			vm_offset_t useEnd, useStart;
2875 
2876 			if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2877 				continue;
2878 
2879 			/*
2880 			 * MADV_FREE would otherwise rewind time to
2881 			 * the creation of the shadow object.  Because
2882 			 * we hold the VM map read-locked, neither the
2883 			 * entry's object nor the presence of a
2884 			 * backing object can change.
2885 			 */
2886 			if (behav == MADV_FREE &&
2887 			    entry->object.vm_object != NULL &&
2888 			    entry->object.vm_object->backing_object != NULL)
2889 				continue;
2890 
2891 			pstart = OFF_TO_IDX(entry->offset);
2892 			pend = pstart + atop(entry->end - entry->start);
2893 			useStart = entry->start;
2894 			useEnd = entry->end;
2895 
2896 			if (entry->start < start) {
2897 				pstart += atop(start - entry->start);
2898 				useStart = start;
2899 			}
2900 			if (entry->end > end) {
2901 				pend -= atop(entry->end - end);
2902 				useEnd = end;
2903 			}
2904 
2905 			if (pstart >= pend)
2906 				continue;
2907 
2908 			/*
2909 			 * Perform the pmap_advise() before clearing
2910 			 * PGA_REFERENCED in vm_page_advise().  Otherwise, a
2911 			 * concurrent pmap operation, such as pmap_remove(),
2912 			 * could clear a reference in the pmap and set
2913 			 * PGA_REFERENCED on the page before the pmap_advise()
2914 			 * had completed.  Consequently, the page would appear
2915 			 * referenced based upon an old reference that
2916 			 * occurred before this pmap_advise() ran.
2917 			 */
2918 			if (behav == MADV_DONTNEED || behav == MADV_FREE)
2919 				pmap_advise(map->pmap, useStart, useEnd,
2920 				    behav);
2921 
2922 			vm_object_madvise(entry->object.vm_object, pstart,
2923 			    pend, behav);
2924 
2925 			/*
2926 			 * Pre-populate paging structures in the
2927 			 * WILLNEED case.  For wired entries, the
2928 			 * paging structures are already populated.
2929 			 */
2930 			if (behav == MADV_WILLNEED &&
2931 			    entry->wired_count == 0) {
2932 				vm_map_pmap_enter(map,
2933 				    useStart,
2934 				    entry->protection,
2935 				    entry->object.vm_object,
2936 				    pstart,
2937 				    ptoa(pend - pstart),
2938 				    MAP_PREFAULT_MADVISE
2939 				);
2940 			}
2941 		}
2942 		vm_map_unlock_read(map);
2943 	}
2944 	return (0);
2945 }
2946 
2947 
2948 /*
2949  *	vm_map_inherit:
2950  *
2951  *	Sets the inheritance of the specified address
2952  *	range in the target map.  Inheritance
2953  *	affects how the map will be shared with
2954  *	child maps at the time of vmspace_fork.
2955  */
2956 int
2957 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
2958 	       vm_inherit_t new_inheritance)
2959 {
2960 	vm_map_entry_t entry, prev_entry;
2961 
2962 	switch (new_inheritance) {
2963 	case VM_INHERIT_NONE:
2964 	case VM_INHERIT_COPY:
2965 	case VM_INHERIT_SHARE:
2966 	case VM_INHERIT_ZERO:
2967 		break;
2968 	default:
2969 		return (KERN_INVALID_ARGUMENT);
2970 	}
2971 	if (start == end)
2972 		return (KERN_SUCCESS);
2973 	vm_map_lock(map);
2974 	VM_MAP_RANGE_CHECK(map, start, end);
2975 	if (vm_map_lookup_entry(map, start, &prev_entry)) {
2976 		entry = prev_entry;
2977 		vm_map_clip_start(map, entry, start);
2978 		prev_entry = vm_map_entry_pred(entry);
2979 	} else
2980 		entry = vm_map_entry_succ(prev_entry);
2981 	for (; entry->start < end;
2982 	    prev_entry = entry, entry = vm_map_entry_succ(entry)) {
2983 		vm_map_clip_end(map, entry, end);
2984 		if ((entry->eflags & MAP_ENTRY_GUARD) == 0 ||
2985 		    new_inheritance != VM_INHERIT_ZERO)
2986 			entry->inheritance = new_inheritance;
2987 		vm_map_try_merge_entries(map, prev_entry, entry);
2988 	}
2989 	vm_map_try_merge_entries(map, prev_entry, entry);
2990 	vm_map_unlock(map);
2991 	return (KERN_SUCCESS);
2992 }
2993 
2994 /*
2995  *	vm_map_entry_in_transition:
2996  *
2997  *	Release the map lock, and sleep until the entry is no longer in
2998  *	transition.  Awake and acquire the map lock.  If the map changed while
2999  *	another held the lock, lookup a possibly-changed entry at or after the
3000  *	'start' position of the old entry.
3001  */
3002 static vm_map_entry_t
3003 vm_map_entry_in_transition(vm_map_t map, vm_offset_t in_start,
3004     vm_offset_t *io_end, bool holes_ok, vm_map_entry_t in_entry)
3005 {
3006 	vm_map_entry_t entry;
3007 	vm_offset_t start;
3008 	u_int last_timestamp;
3009 
3010 	VM_MAP_ASSERT_LOCKED(map);
3011 	KASSERT((in_entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3012 	    ("not in-tranition map entry %p", in_entry));
3013 	/*
3014 	 * We have not yet clipped the entry.
3015 	 */
3016 	start = MAX(in_start, in_entry->start);
3017 	in_entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
3018 	last_timestamp = map->timestamp;
3019 	if (vm_map_unlock_and_wait(map, 0)) {
3020 		/*
3021 		 * Allow interruption of user wiring/unwiring?
3022 		 */
3023 	}
3024 	vm_map_lock(map);
3025 	if (last_timestamp + 1 == map->timestamp)
3026 		return (in_entry);
3027 
3028 	/*
3029 	 * Look again for the entry because the map was modified while it was
3030 	 * unlocked.  Specifically, the entry may have been clipped, merged, or
3031 	 * deleted.
3032 	 */
3033 	if (!vm_map_lookup_entry(map, start, &entry)) {
3034 		if (!holes_ok) {
3035 			*io_end = start;
3036 			return (NULL);
3037 		}
3038 		entry = vm_map_entry_succ(entry);
3039 	}
3040 	return (entry);
3041 }
3042 
3043 /*
3044  *	vm_map_unwire:
3045  *
3046  *	Implements both kernel and user unwiring.
3047  */
3048 int
3049 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t end,
3050     int flags)
3051 {
3052 	vm_map_entry_t entry, first_entry, next_entry, prev_entry;
3053 	int rv;
3054 	bool holes_ok, need_wakeup, user_unwire;
3055 
3056 	if (start == end)
3057 		return (KERN_SUCCESS);
3058 	holes_ok = (flags & VM_MAP_WIRE_HOLESOK) != 0;
3059 	user_unwire = (flags & VM_MAP_WIRE_USER) != 0;
3060 	vm_map_lock(map);
3061 	VM_MAP_RANGE_CHECK(map, start, end);
3062 	if (!vm_map_lookup_entry(map, start, &first_entry)) {
3063 		if (holes_ok)
3064 			first_entry = vm_map_entry_succ(first_entry);
3065 		else {
3066 			vm_map_unlock(map);
3067 			return (KERN_INVALID_ADDRESS);
3068 		}
3069 	}
3070 	rv = KERN_SUCCESS;
3071 	for (entry = first_entry; entry->start < end; entry = next_entry) {
3072 		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
3073 			/*
3074 			 * We have not yet clipped the entry.
3075 			 */
3076 			next_entry = vm_map_entry_in_transition(map, start,
3077 			    &end, holes_ok, entry);
3078 			if (next_entry == NULL) {
3079 				if (entry == first_entry) {
3080 					vm_map_unlock(map);
3081 					return (KERN_INVALID_ADDRESS);
3082 				}
3083 				rv = KERN_INVALID_ADDRESS;
3084 				break;
3085 			}
3086 			first_entry = (entry == first_entry) ?
3087 			    next_entry : NULL;
3088 			continue;
3089 		}
3090 		vm_map_clip_start(map, entry, start);
3091 		vm_map_clip_end(map, entry, end);
3092 		/*
3093 		 * Mark the entry in case the map lock is released.  (See
3094 		 * above.)
3095 		 */
3096 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
3097 		    entry->wiring_thread == NULL,
3098 		    ("owned map entry %p", entry));
3099 		entry->eflags |= MAP_ENTRY_IN_TRANSITION;
3100 		entry->wiring_thread = curthread;
3101 		next_entry = vm_map_entry_succ(entry);
3102 		/*
3103 		 * Check the map for holes in the specified region.
3104 		 * If holes_ok, skip this check.
3105 		 */
3106 		if (!holes_ok &&
3107 		    entry->end < end && next_entry->start > entry->end) {
3108 			end = entry->end;
3109 			rv = KERN_INVALID_ADDRESS;
3110 			break;
3111 		}
3112 		/*
3113 		 * If system unwiring, require that the entry is system wired.
3114 		 */
3115 		if (!user_unwire &&
3116 		    vm_map_entry_system_wired_count(entry) == 0) {
3117 			end = entry->end;
3118 			rv = KERN_INVALID_ARGUMENT;
3119 			break;
3120 		}
3121 	}
3122 	need_wakeup = false;
3123 	if (first_entry == NULL &&
3124 	    !vm_map_lookup_entry(map, start, &first_entry)) {
3125 		KASSERT(holes_ok, ("vm_map_unwire: lookup failed"));
3126 		prev_entry = first_entry;
3127 		entry = vm_map_entry_succ(first_entry);
3128 	} else {
3129 		prev_entry = vm_map_entry_pred(first_entry);
3130 		entry = first_entry;
3131 	}
3132 	for (; entry->start < end;
3133 	    prev_entry = entry, entry = vm_map_entry_succ(entry)) {
3134 		/*
3135 		 * If holes_ok was specified, an empty
3136 		 * space in the unwired region could have been mapped
3137 		 * while the map lock was dropped for draining
3138 		 * MAP_ENTRY_IN_TRANSITION.  Moreover, another thread
3139 		 * could be simultaneously wiring this new mapping
3140 		 * entry.  Detect these cases and skip any entries
3141 		 * marked as in transition by us.
3142 		 */
3143 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
3144 		    entry->wiring_thread != curthread) {
3145 			KASSERT(holes_ok,
3146 			    ("vm_map_unwire: !HOLESOK and new/changed entry"));
3147 			continue;
3148 		}
3149 
3150 		if (rv == KERN_SUCCESS && (!user_unwire ||
3151 		    (entry->eflags & MAP_ENTRY_USER_WIRED))) {
3152 			if (entry->wired_count == 1)
3153 				vm_map_entry_unwire(map, entry);
3154 			else
3155 				entry->wired_count--;
3156 			if (user_unwire)
3157 				entry->eflags &= ~MAP_ENTRY_USER_WIRED;
3158 		}
3159 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3160 		    ("vm_map_unwire: in-transition flag missing %p", entry));
3161 		KASSERT(entry->wiring_thread == curthread,
3162 		    ("vm_map_unwire: alien wire %p", entry));
3163 		entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
3164 		entry->wiring_thread = NULL;
3165 		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
3166 			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
3167 			need_wakeup = true;
3168 		}
3169 		vm_map_try_merge_entries(map, prev_entry, entry);
3170 	}
3171 	vm_map_try_merge_entries(map, prev_entry, entry);
3172 	vm_map_unlock(map);
3173 	if (need_wakeup)
3174 		vm_map_wakeup(map);
3175 	return (rv);
3176 }
3177 
3178 static void
3179 vm_map_wire_user_count_sub(u_long npages)
3180 {
3181 
3182 	atomic_subtract_long(&vm_user_wire_count, npages);
3183 }
3184 
3185 static bool
3186 vm_map_wire_user_count_add(u_long npages)
3187 {
3188 	u_long wired;
3189 
3190 	wired = vm_user_wire_count;
3191 	do {
3192 		if (npages + wired > vm_page_max_user_wired)
3193 			return (false);
3194 	} while (!atomic_fcmpset_long(&vm_user_wire_count, &wired,
3195 	    npages + wired));
3196 
3197 	return (true);
3198 }
3199 
3200 /*
3201  *	vm_map_wire_entry_failure:
3202  *
3203  *	Handle a wiring failure on the given entry.
3204  *
3205  *	The map should be locked.
3206  */
3207 static void
3208 vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
3209     vm_offset_t failed_addr)
3210 {
3211 
3212 	VM_MAP_ASSERT_LOCKED(map);
3213 	KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 &&
3214 	    entry->wired_count == 1,
3215 	    ("vm_map_wire_entry_failure: entry %p isn't being wired", entry));
3216 	KASSERT(failed_addr < entry->end,
3217 	    ("vm_map_wire_entry_failure: entry %p was fully wired", entry));
3218 
3219 	/*
3220 	 * If any pages at the start of this entry were successfully wired,
3221 	 * then unwire them.
3222 	 */
3223 	if (failed_addr > entry->start) {
3224 		pmap_unwire(map->pmap, entry->start, failed_addr);
3225 		vm_object_unwire(entry->object.vm_object, entry->offset,
3226 		    failed_addr - entry->start, PQ_ACTIVE);
3227 	}
3228 
3229 	/*
3230 	 * Assign an out-of-range value to represent the failure to wire this
3231 	 * entry.
3232 	 */
3233 	entry->wired_count = -1;
3234 }
3235 
3236 int
3237 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t end, int flags)
3238 {
3239 	int rv;
3240 
3241 	vm_map_lock(map);
3242 	rv = vm_map_wire_locked(map, start, end, flags);
3243 	vm_map_unlock(map);
3244 	return (rv);
3245 }
3246 
3247 
3248 /*
3249  *	vm_map_wire_locked:
3250  *
3251  *	Implements both kernel and user wiring.  Returns with the map locked,
3252  *	the map lock may be dropped.
3253  */
3254 int
3255 vm_map_wire_locked(vm_map_t map, vm_offset_t start, vm_offset_t end, int flags)
3256 {
3257 	vm_map_entry_t entry, first_entry, next_entry, prev_entry;
3258 	vm_offset_t faddr, saved_end, saved_start;
3259 	u_long npages;
3260 	u_int last_timestamp;
3261 	int rv;
3262 	bool holes_ok, need_wakeup, user_wire;
3263 	vm_prot_t prot;
3264 
3265 	VM_MAP_ASSERT_LOCKED(map);
3266 
3267 	if (start == end)
3268 		return (KERN_SUCCESS);
3269 	prot = 0;
3270 	if (flags & VM_MAP_WIRE_WRITE)
3271 		prot |= VM_PROT_WRITE;
3272 	holes_ok = (flags & VM_MAP_WIRE_HOLESOK) != 0;
3273 	user_wire = (flags & VM_MAP_WIRE_USER) != 0;
3274 	VM_MAP_RANGE_CHECK(map, start, end);
3275 	if (!vm_map_lookup_entry(map, start, &first_entry)) {
3276 		if (holes_ok)
3277 			first_entry = vm_map_entry_succ(first_entry);
3278 		else
3279 			return (KERN_INVALID_ADDRESS);
3280 	}
3281 	for (entry = first_entry; entry->start < end; entry = next_entry) {
3282 		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
3283 			/*
3284 			 * We have not yet clipped the entry.
3285 			 */
3286 			next_entry = vm_map_entry_in_transition(map, start,
3287 			    &end, holes_ok, entry);
3288 			if (next_entry == NULL) {
3289 				if (entry == first_entry)
3290 					return (KERN_INVALID_ADDRESS);
3291 				rv = KERN_INVALID_ADDRESS;
3292 				goto done;
3293 			}
3294 			first_entry = (entry == first_entry) ?
3295 			    next_entry : NULL;
3296 			continue;
3297 		}
3298 		vm_map_clip_start(map, entry, start);
3299 		vm_map_clip_end(map, entry, end);
3300 		/*
3301 		 * Mark the entry in case the map lock is released.  (See
3302 		 * above.)
3303 		 */
3304 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
3305 		    entry->wiring_thread == NULL,
3306 		    ("owned map entry %p", entry));
3307 		entry->eflags |= MAP_ENTRY_IN_TRANSITION;
3308 		entry->wiring_thread = curthread;
3309 		if ((entry->protection & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0
3310 		    || (entry->protection & prot) != prot) {
3311 			entry->eflags |= MAP_ENTRY_WIRE_SKIPPED;
3312 			if (!holes_ok) {
3313 				end = entry->end;
3314 				rv = KERN_INVALID_ADDRESS;
3315 				goto done;
3316 			}
3317 		} else if (entry->wired_count == 0) {
3318 			entry->wired_count++;
3319 
3320 			npages = atop(entry->end - entry->start);
3321 			if (user_wire && !vm_map_wire_user_count_add(npages)) {
3322 				vm_map_wire_entry_failure(map, entry,
3323 				    entry->start);
3324 				end = entry->end;
3325 				rv = KERN_RESOURCE_SHORTAGE;
3326 				goto done;
3327 			}
3328 
3329 			/*
3330 			 * Release the map lock, relying on the in-transition
3331 			 * mark.  Mark the map busy for fork.
3332 			 */
3333 			saved_start = entry->start;
3334 			saved_end = entry->end;
3335 			last_timestamp = map->timestamp;
3336 			vm_map_busy(map);
3337 			vm_map_unlock(map);
3338 
3339 			faddr = saved_start;
3340 			do {
3341 				/*
3342 				 * Simulate a fault to get the page and enter
3343 				 * it into the physical map.
3344 				 */
3345 				if ((rv = vm_fault(map, faddr,
3346 				    VM_PROT_NONE, VM_FAULT_WIRE, NULL)) !=
3347 				    KERN_SUCCESS)
3348 					break;
3349 			} while ((faddr += PAGE_SIZE) < saved_end);
3350 			vm_map_lock(map);
3351 			vm_map_unbusy(map);
3352 			if (last_timestamp + 1 != map->timestamp) {
3353 				/*
3354 				 * Look again for the entry because the map was
3355 				 * modified while it was unlocked.  The entry
3356 				 * may have been clipped, but NOT merged or
3357 				 * deleted.
3358 				 */
3359 				if (!vm_map_lookup_entry(map, saved_start,
3360 				    &next_entry))
3361 					KASSERT(false,
3362 					    ("vm_map_wire: lookup failed"));
3363 				first_entry = (entry == first_entry) ?
3364 				    next_entry : NULL;
3365 				for (entry = next_entry; entry->end < saved_end;
3366 				    entry = vm_map_entry_succ(entry)) {
3367 					/*
3368 					 * In case of failure, handle entries
3369 					 * that were not fully wired here;
3370 					 * fully wired entries are handled
3371 					 * later.
3372 					 */
3373 					if (rv != KERN_SUCCESS &&
3374 					    faddr < entry->end)
3375 						vm_map_wire_entry_failure(map,
3376 						    entry, faddr);
3377 				}
3378 			}
3379 			if (rv != KERN_SUCCESS) {
3380 				vm_map_wire_entry_failure(map, entry, faddr);
3381 				if (user_wire)
3382 					vm_map_wire_user_count_sub(npages);
3383 				end = entry->end;
3384 				goto done;
3385 			}
3386 		} else if (!user_wire ||
3387 			   (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
3388 			entry->wired_count++;
3389 		}
3390 		/*
3391 		 * Check the map for holes in the specified region.
3392 		 * If holes_ok was specified, skip this check.
3393 		 */
3394 		next_entry = vm_map_entry_succ(entry);
3395 		if (!holes_ok &&
3396 		    entry->end < end && next_entry->start > entry->end) {
3397 			end = entry->end;
3398 			rv = KERN_INVALID_ADDRESS;
3399 			goto done;
3400 		}
3401 	}
3402 	rv = KERN_SUCCESS;
3403 done:
3404 	need_wakeup = false;
3405 	if (first_entry == NULL &&
3406 	    !vm_map_lookup_entry(map, start, &first_entry)) {
3407 		KASSERT(holes_ok, ("vm_map_wire: lookup failed"));
3408 		prev_entry = first_entry;
3409 		entry = vm_map_entry_succ(first_entry);
3410 	} else {
3411 		prev_entry = vm_map_entry_pred(first_entry);
3412 		entry = first_entry;
3413 	}
3414 	for (; entry->start < end;
3415 	    prev_entry = entry, entry = vm_map_entry_succ(entry)) {
3416 		/*
3417 		 * If holes_ok was specified, an empty
3418 		 * space in the unwired region could have been mapped
3419 		 * while the map lock was dropped for faulting in the
3420 		 * pages or draining MAP_ENTRY_IN_TRANSITION.
3421 		 * Moreover, another thread could be simultaneously
3422 		 * wiring this new mapping entry.  Detect these cases
3423 		 * and skip any entries marked as in transition not by us.
3424 		 */
3425 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
3426 		    entry->wiring_thread != curthread) {
3427 			KASSERT(holes_ok,
3428 			    ("vm_map_wire: !HOLESOK and new/changed entry"));
3429 			continue;
3430 		}
3431 
3432 		if ((entry->eflags & MAP_ENTRY_WIRE_SKIPPED) != 0) {
3433 			/* do nothing */
3434 		} else if (rv == KERN_SUCCESS) {
3435 			if (user_wire)
3436 				entry->eflags |= MAP_ENTRY_USER_WIRED;
3437 		} else if (entry->wired_count == -1) {
3438 			/*
3439 			 * Wiring failed on this entry.  Thus, unwiring is
3440 			 * unnecessary.
3441 			 */
3442 			entry->wired_count = 0;
3443 		} else if (!user_wire ||
3444 		    (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
3445 			/*
3446 			 * Undo the wiring.  Wiring succeeded on this entry
3447 			 * but failed on a later entry.
3448 			 */
3449 			if (entry->wired_count == 1) {
3450 				vm_map_entry_unwire(map, entry);
3451 				if (user_wire)
3452 					vm_map_wire_user_count_sub(
3453 					    atop(entry->end - entry->start));
3454 			} else
3455 				entry->wired_count--;
3456 		}
3457 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3458 		    ("vm_map_wire: in-transition flag missing %p", entry));
3459 		KASSERT(entry->wiring_thread == curthread,
3460 		    ("vm_map_wire: alien wire %p", entry));
3461 		entry->eflags &= ~(MAP_ENTRY_IN_TRANSITION |
3462 		    MAP_ENTRY_WIRE_SKIPPED);
3463 		entry->wiring_thread = NULL;
3464 		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
3465 			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
3466 			need_wakeup = true;
3467 		}
3468 		vm_map_try_merge_entries(map, prev_entry, entry);
3469 	}
3470 	vm_map_try_merge_entries(map, prev_entry, entry);
3471 	if (need_wakeup)
3472 		vm_map_wakeup(map);
3473 	return (rv);
3474 }
3475 
3476 /*
3477  * vm_map_sync
3478  *
3479  * Push any dirty cached pages in the address range to their pager.
3480  * If syncio is TRUE, dirty pages are written synchronously.
3481  * If invalidate is TRUE, any cached pages are freed as well.
3482  *
3483  * If the size of the region from start to end is zero, we are
3484  * supposed to flush all modified pages within the region containing
3485  * start.  Unfortunately, a region can be split or coalesced with
3486  * neighboring regions, making it difficult to determine what the
3487  * original region was.  Therefore, we approximate this requirement by
3488  * flushing the current region containing start.
3489  *
3490  * Returns an error if any part of the specified range is not mapped.
3491  */
3492 int
3493 vm_map_sync(
3494 	vm_map_t map,
3495 	vm_offset_t start,
3496 	vm_offset_t end,
3497 	boolean_t syncio,
3498 	boolean_t invalidate)
3499 {
3500 	vm_map_entry_t entry, first_entry, next_entry;
3501 	vm_size_t size;
3502 	vm_object_t object;
3503 	vm_ooffset_t offset;
3504 	unsigned int last_timestamp;
3505 	boolean_t failed;
3506 
3507 	vm_map_lock_read(map);
3508 	VM_MAP_RANGE_CHECK(map, start, end);
3509 	if (!vm_map_lookup_entry(map, start, &first_entry)) {
3510 		vm_map_unlock_read(map);
3511 		return (KERN_INVALID_ADDRESS);
3512 	} else if (start == end) {
3513 		start = first_entry->start;
3514 		end = first_entry->end;
3515 	}
3516 	/*
3517 	 * Make a first pass to check for user-wired memory and holes.
3518 	 */
3519 	for (entry = first_entry; entry->start < end; entry = next_entry) {
3520 		if (invalidate &&
3521 		    (entry->eflags & MAP_ENTRY_USER_WIRED) != 0) {
3522 			vm_map_unlock_read(map);
3523 			return (KERN_INVALID_ARGUMENT);
3524 		}
3525 		next_entry = vm_map_entry_succ(entry);
3526 		if (end > entry->end &&
3527 		    entry->end != next_entry->start) {
3528 			vm_map_unlock_read(map);
3529 			return (KERN_INVALID_ADDRESS);
3530 		}
3531 	}
3532 
3533 	if (invalidate)
3534 		pmap_remove(map->pmap, start, end);
3535 	failed = FALSE;
3536 
3537 	/*
3538 	 * Make a second pass, cleaning/uncaching pages from the indicated
3539 	 * objects as we go.
3540 	 */
3541 	for (entry = first_entry; entry->start < end;) {
3542 		offset = entry->offset + (start - entry->start);
3543 		size = (end <= entry->end ? end : entry->end) - start;
3544 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0) {
3545 			vm_map_t smap;
3546 			vm_map_entry_t tentry;
3547 			vm_size_t tsize;
3548 
3549 			smap = entry->object.sub_map;
3550 			vm_map_lock_read(smap);
3551 			(void) vm_map_lookup_entry(smap, offset, &tentry);
3552 			tsize = tentry->end - offset;
3553 			if (tsize < size)
3554 				size = tsize;
3555 			object = tentry->object.vm_object;
3556 			offset = tentry->offset + (offset - tentry->start);
3557 			vm_map_unlock_read(smap);
3558 		} else {
3559 			object = entry->object.vm_object;
3560 		}
3561 		vm_object_reference(object);
3562 		last_timestamp = map->timestamp;
3563 		vm_map_unlock_read(map);
3564 		if (!vm_object_sync(object, offset, size, syncio, invalidate))
3565 			failed = TRUE;
3566 		start += size;
3567 		vm_object_deallocate(object);
3568 		vm_map_lock_read(map);
3569 		if (last_timestamp == map->timestamp ||
3570 		    !vm_map_lookup_entry(map, start, &entry))
3571 			entry = vm_map_entry_succ(entry);
3572 	}
3573 
3574 	vm_map_unlock_read(map);
3575 	return (failed ? KERN_FAILURE : KERN_SUCCESS);
3576 }
3577 
3578 /*
3579  *	vm_map_entry_unwire:	[ internal use only ]
3580  *
3581  *	Make the region specified by this entry pageable.
3582  *
3583  *	The map in question should be locked.
3584  *	[This is the reason for this routine's existence.]
3585  */
3586 static void
3587 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
3588 {
3589 	vm_size_t size;
3590 
3591 	VM_MAP_ASSERT_LOCKED(map);
3592 	KASSERT(entry->wired_count > 0,
3593 	    ("vm_map_entry_unwire: entry %p isn't wired", entry));
3594 
3595 	size = entry->end - entry->start;
3596 	if ((entry->eflags & MAP_ENTRY_USER_WIRED) != 0)
3597 		vm_map_wire_user_count_sub(atop(size));
3598 	pmap_unwire(map->pmap, entry->start, entry->end);
3599 	vm_object_unwire(entry->object.vm_object, entry->offset, size,
3600 	    PQ_ACTIVE);
3601 	entry->wired_count = 0;
3602 }
3603 
3604 static void
3605 vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map)
3606 {
3607 
3608 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0)
3609 		vm_object_deallocate(entry->object.vm_object);
3610 	uma_zfree(system_map ? kmapentzone : mapentzone, entry);
3611 }
3612 
3613 /*
3614  *	vm_map_entry_delete:	[ internal use only ]
3615  *
3616  *	Deallocate the given entry from the target map.
3617  */
3618 static void
3619 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry)
3620 {
3621 	vm_object_t object;
3622 	vm_pindex_t offidxstart, offidxend, count, size1;
3623 	vm_size_t size;
3624 
3625 	vm_map_entry_unlink(map, entry, UNLINK_MERGE_NONE);
3626 	object = entry->object.vm_object;
3627 
3628 	if ((entry->eflags & MAP_ENTRY_GUARD) != 0) {
3629 		MPASS(entry->cred == NULL);
3630 		MPASS((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0);
3631 		MPASS(object == NULL);
3632 		vm_map_entry_deallocate(entry, map->system_map);
3633 		return;
3634 	}
3635 
3636 	size = entry->end - entry->start;
3637 	map->size -= size;
3638 
3639 	if (entry->cred != NULL) {
3640 		swap_release_by_cred(size, entry->cred);
3641 		crfree(entry->cred);
3642 	}
3643 
3644 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0 || object == NULL) {
3645 		entry->object.vm_object = NULL;
3646 	} else if ((object->flags & OBJ_ANON) != 0 ||
3647 	    object == kernel_object) {
3648 		KASSERT(entry->cred == NULL || object->cred == NULL ||
3649 		    (entry->eflags & MAP_ENTRY_NEEDS_COPY),
3650 		    ("OVERCOMMIT vm_map_entry_delete: both cred %p", entry));
3651 		count = atop(size);
3652 		offidxstart = OFF_TO_IDX(entry->offset);
3653 		offidxend = offidxstart + count;
3654 		VM_OBJECT_WLOCK(object);
3655 		if (object->ref_count != 1 &&
3656 		    ((object->flags & OBJ_ONEMAPPING) != 0 ||
3657 		    object == kernel_object)) {
3658 			vm_object_collapse(object);
3659 
3660 			/*
3661 			 * The option OBJPR_NOTMAPPED can be passed here
3662 			 * because vm_map_delete() already performed
3663 			 * pmap_remove() on the only mapping to this range
3664 			 * of pages.
3665 			 */
3666 			vm_object_page_remove(object, offidxstart, offidxend,
3667 			    OBJPR_NOTMAPPED);
3668 			if (object->type == OBJT_SWAP)
3669 				swap_pager_freespace(object, offidxstart,
3670 				    count);
3671 			if (offidxend >= object->size &&
3672 			    offidxstart < object->size) {
3673 				size1 = object->size;
3674 				object->size = offidxstart;
3675 				if (object->cred != NULL) {
3676 					size1 -= object->size;
3677 					KASSERT(object->charge >= ptoa(size1),
3678 					    ("object %p charge < 0", object));
3679 					swap_release_by_cred(ptoa(size1),
3680 					    object->cred);
3681 					object->charge -= ptoa(size1);
3682 				}
3683 			}
3684 		}
3685 		VM_OBJECT_WUNLOCK(object);
3686 	}
3687 	if (map->system_map)
3688 		vm_map_entry_deallocate(entry, TRUE);
3689 	else {
3690 		entry->defer_next = curthread->td_map_def_user;
3691 		curthread->td_map_def_user = entry;
3692 	}
3693 }
3694 
3695 /*
3696  *	vm_map_delete:	[ internal use only ]
3697  *
3698  *	Deallocates the given address range from the target
3699  *	map.
3700  */
3701 int
3702 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
3703 {
3704 	vm_map_entry_t entry;
3705 	vm_map_entry_t first_entry;
3706 
3707 	VM_MAP_ASSERT_LOCKED(map);
3708 	if (start == end)
3709 		return (KERN_SUCCESS);
3710 
3711 	/*
3712 	 * Find the start of the region, and clip it
3713 	 */
3714 	if (!vm_map_lookup_entry(map, start, &first_entry))
3715 		entry = vm_map_entry_succ(first_entry);
3716 	else {
3717 		entry = first_entry;
3718 		vm_map_clip_start(map, entry, start);
3719 	}
3720 
3721 	/*
3722 	 * Step through all entries in this region
3723 	 */
3724 	while (entry->start < end) {
3725 		vm_map_entry_t next;
3726 
3727 		/*
3728 		 * Wait for wiring or unwiring of an entry to complete.
3729 		 * Also wait for any system wirings to disappear on
3730 		 * user maps.
3731 		 */
3732 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 ||
3733 		    (vm_map_pmap(map) != kernel_pmap &&
3734 		    vm_map_entry_system_wired_count(entry) != 0)) {
3735 			unsigned int last_timestamp;
3736 			vm_offset_t saved_start;
3737 			vm_map_entry_t tmp_entry;
3738 
3739 			saved_start = entry->start;
3740 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
3741 			last_timestamp = map->timestamp;
3742 			(void) vm_map_unlock_and_wait(map, 0);
3743 			vm_map_lock(map);
3744 			if (last_timestamp + 1 != map->timestamp) {
3745 				/*
3746 				 * Look again for the entry because the map was
3747 				 * modified while it was unlocked.
3748 				 * Specifically, the entry may have been
3749 				 * clipped, merged, or deleted.
3750 				 */
3751 				if (!vm_map_lookup_entry(map, saved_start,
3752 							 &tmp_entry))
3753 					entry = vm_map_entry_succ(tmp_entry);
3754 				else {
3755 					entry = tmp_entry;
3756 					vm_map_clip_start(map, entry,
3757 							  saved_start);
3758 				}
3759 			}
3760 			continue;
3761 		}
3762 		vm_map_clip_end(map, entry, end);
3763 
3764 		next = vm_map_entry_succ(entry);
3765 
3766 		/*
3767 		 * Unwire before removing addresses from the pmap; otherwise,
3768 		 * unwiring will put the entries back in the pmap.
3769 		 */
3770 		if (entry->wired_count != 0)
3771 			vm_map_entry_unwire(map, entry);
3772 
3773 		/*
3774 		 * Remove mappings for the pages, but only if the
3775 		 * mappings could exist.  For instance, it does not
3776 		 * make sense to call pmap_remove() for guard entries.
3777 		 */
3778 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0 ||
3779 		    entry->object.vm_object != NULL)
3780 			pmap_remove(map->pmap, entry->start, entry->end);
3781 
3782 		if (entry->end == map->anon_loc)
3783 			map->anon_loc = entry->start;
3784 
3785 		/*
3786 		 * Delete the entry only after removing all pmap
3787 		 * entries pointing to its pages.  (Otherwise, its
3788 		 * page frames may be reallocated, and any modify bits
3789 		 * will be set in the wrong object!)
3790 		 */
3791 		vm_map_entry_delete(map, entry);
3792 		entry = next;
3793 	}
3794 	return (KERN_SUCCESS);
3795 }
3796 
3797 /*
3798  *	vm_map_remove:
3799  *
3800  *	Remove the given address range from the target map.
3801  *	This is the exported form of vm_map_delete.
3802  */
3803 int
3804 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
3805 {
3806 	int result;
3807 
3808 	vm_map_lock(map);
3809 	VM_MAP_RANGE_CHECK(map, start, end);
3810 	result = vm_map_delete(map, start, end);
3811 	vm_map_unlock(map);
3812 	return (result);
3813 }
3814 
3815 /*
3816  *	vm_map_check_protection:
3817  *
3818  *	Assert that the target map allows the specified privilege on the
3819  *	entire address region given.  The entire region must be allocated.
3820  *
3821  *	WARNING!  This code does not and should not check whether the
3822  *	contents of the region is accessible.  For example a smaller file
3823  *	might be mapped into a larger address space.
3824  *
3825  *	NOTE!  This code is also called by munmap().
3826  *
3827  *	The map must be locked.  A read lock is sufficient.
3828  */
3829 boolean_t
3830 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
3831 			vm_prot_t protection)
3832 {
3833 	vm_map_entry_t entry;
3834 	vm_map_entry_t tmp_entry;
3835 
3836 	if (!vm_map_lookup_entry(map, start, &tmp_entry))
3837 		return (FALSE);
3838 	entry = tmp_entry;
3839 
3840 	while (start < end) {
3841 		/*
3842 		 * No holes allowed!
3843 		 */
3844 		if (start < entry->start)
3845 			return (FALSE);
3846 		/*
3847 		 * Check protection associated with entry.
3848 		 */
3849 		if ((entry->protection & protection) != protection)
3850 			return (FALSE);
3851 		/* go to next entry */
3852 		start = entry->end;
3853 		entry = vm_map_entry_succ(entry);
3854 	}
3855 	return (TRUE);
3856 }
3857 
3858 
3859 /*
3860  *
3861  *	vm_map_copy_swap_object:
3862  *
3863  *	Copies a swap-backed object from an existing map entry to a
3864  *	new one.  Carries forward the swap charge.  May change the
3865  *	src object on return.
3866  */
3867 static void
3868 vm_map_copy_swap_object(vm_map_entry_t src_entry, vm_map_entry_t dst_entry,
3869     vm_offset_t size, vm_ooffset_t *fork_charge)
3870 {
3871 	vm_object_t src_object;
3872 	struct ucred *cred;
3873 	int charged;
3874 
3875 	src_object = src_entry->object.vm_object;
3876 	VM_OBJECT_WLOCK(src_object);
3877 	charged = ENTRY_CHARGED(src_entry);
3878 	vm_object_collapse(src_object);
3879 	if ((src_object->flags & OBJ_ONEMAPPING) != 0) {
3880 		vm_object_split(src_entry);
3881 		src_object = src_entry->object.vm_object;
3882 	}
3883 	vm_object_reference_locked(src_object);
3884 	vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
3885 	if (src_entry->cred != NULL &&
3886 	    !(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
3887 		KASSERT(src_object->cred == NULL,
3888 		    ("OVERCOMMIT: vm_map_copy_anon_entry: cred %p",
3889 		     src_object));
3890 		src_object->cred = src_entry->cred;
3891 		src_object->charge = size;
3892 	}
3893 	VM_OBJECT_WUNLOCK(src_object);
3894 	dst_entry->object.vm_object = src_object;
3895 	if (charged) {
3896 		cred = curthread->td_ucred;
3897 		crhold(cred);
3898 		dst_entry->cred = cred;
3899 		*fork_charge += size;
3900 		if (!(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
3901 			crhold(cred);
3902 			src_entry->cred = cred;
3903 			*fork_charge += size;
3904 		}
3905 	}
3906 }
3907 
3908 /*
3909  *	vm_map_copy_entry:
3910  *
3911  *	Copies the contents of the source entry to the destination
3912  *	entry.  The entries *must* be aligned properly.
3913  */
3914 static void
3915 vm_map_copy_entry(
3916 	vm_map_t src_map,
3917 	vm_map_t dst_map,
3918 	vm_map_entry_t src_entry,
3919 	vm_map_entry_t dst_entry,
3920 	vm_ooffset_t *fork_charge)
3921 {
3922 	vm_object_t src_object;
3923 	vm_map_entry_t fake_entry;
3924 	vm_offset_t size;
3925 
3926 	VM_MAP_ASSERT_LOCKED(dst_map);
3927 
3928 	if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
3929 		return;
3930 
3931 	if (src_entry->wired_count == 0 ||
3932 	    (src_entry->protection & VM_PROT_WRITE) == 0) {
3933 		/*
3934 		 * If the source entry is marked needs_copy, it is already
3935 		 * write-protected.
3936 		 */
3937 		if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0 &&
3938 		    (src_entry->protection & VM_PROT_WRITE) != 0) {
3939 			pmap_protect(src_map->pmap,
3940 			    src_entry->start,
3941 			    src_entry->end,
3942 			    src_entry->protection & ~VM_PROT_WRITE);
3943 		}
3944 
3945 		/*
3946 		 * Make a copy of the object.
3947 		 */
3948 		size = src_entry->end - src_entry->start;
3949 		if ((src_object = src_entry->object.vm_object) != NULL) {
3950 			if (src_object->type == OBJT_DEFAULT ||
3951 			    src_object->type == OBJT_SWAP) {
3952 				vm_map_copy_swap_object(src_entry, dst_entry,
3953 				    size, fork_charge);
3954 				/* May have split/collapsed, reload obj. */
3955 				src_object = src_entry->object.vm_object;
3956 			} else {
3957 				vm_object_reference(src_object);
3958 				dst_entry->object.vm_object = src_object;
3959 			}
3960 			src_entry->eflags |= MAP_ENTRY_COW |
3961 			    MAP_ENTRY_NEEDS_COPY;
3962 			dst_entry->eflags |= MAP_ENTRY_COW |
3963 			    MAP_ENTRY_NEEDS_COPY;
3964 			dst_entry->offset = src_entry->offset;
3965 			if (src_entry->eflags & MAP_ENTRY_WRITECNT) {
3966 				/*
3967 				 * MAP_ENTRY_WRITECNT cannot
3968 				 * indicate write reference from
3969 				 * src_entry, since the entry is
3970 				 * marked as needs copy.  Allocate a
3971 				 * fake entry that is used to
3972 				 * decrement object->un_pager writecount
3973 				 * at the appropriate time.  Attach
3974 				 * fake_entry to the deferred list.
3975 				 */
3976 				fake_entry = vm_map_entry_create(dst_map);
3977 				fake_entry->eflags = MAP_ENTRY_WRITECNT;
3978 				src_entry->eflags &= ~MAP_ENTRY_WRITECNT;
3979 				vm_object_reference(src_object);
3980 				fake_entry->object.vm_object = src_object;
3981 				fake_entry->start = src_entry->start;
3982 				fake_entry->end = src_entry->end;
3983 				fake_entry->defer_next =
3984 				    curthread->td_map_def_user;
3985 				curthread->td_map_def_user = fake_entry;
3986 			}
3987 
3988 			pmap_copy(dst_map->pmap, src_map->pmap,
3989 			    dst_entry->start, dst_entry->end - dst_entry->start,
3990 			    src_entry->start);
3991 		} else {
3992 			dst_entry->object.vm_object = NULL;
3993 			dst_entry->offset = 0;
3994 			if (src_entry->cred != NULL) {
3995 				dst_entry->cred = curthread->td_ucred;
3996 				crhold(dst_entry->cred);
3997 				*fork_charge += size;
3998 			}
3999 		}
4000 	} else {
4001 		/*
4002 		 * We don't want to make writeable wired pages copy-on-write.
4003 		 * Immediately copy these pages into the new map by simulating
4004 		 * page faults.  The new pages are pageable.
4005 		 */
4006 		vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry,
4007 		    fork_charge);
4008 	}
4009 }
4010 
4011 /*
4012  * vmspace_map_entry_forked:
4013  * Update the newly-forked vmspace each time a map entry is inherited
4014  * or copied.  The values for vm_dsize and vm_tsize are approximate
4015  * (and mostly-obsolete ideas in the face of mmap(2) et al.)
4016  */
4017 static void
4018 vmspace_map_entry_forked(const struct vmspace *vm1, struct vmspace *vm2,
4019     vm_map_entry_t entry)
4020 {
4021 	vm_size_t entrysize;
4022 	vm_offset_t newend;
4023 
4024 	if ((entry->eflags & MAP_ENTRY_GUARD) != 0)
4025 		return;
4026 	entrysize = entry->end - entry->start;
4027 	vm2->vm_map.size += entrysize;
4028 	if (entry->eflags & (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP)) {
4029 		vm2->vm_ssize += btoc(entrysize);
4030 	} else if (entry->start >= (vm_offset_t)vm1->vm_daddr &&
4031 	    entry->start < (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize)) {
4032 		newend = MIN(entry->end,
4033 		    (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize));
4034 		vm2->vm_dsize += btoc(newend - entry->start);
4035 	} else if (entry->start >= (vm_offset_t)vm1->vm_taddr &&
4036 	    entry->start < (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize)) {
4037 		newend = MIN(entry->end,
4038 		    (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize));
4039 		vm2->vm_tsize += btoc(newend - entry->start);
4040 	}
4041 }
4042 
4043 /*
4044  * vmspace_fork:
4045  * Create a new process vmspace structure and vm_map
4046  * based on those of an existing process.  The new map
4047  * is based on the old map, according to the inheritance
4048  * values on the regions in that map.
4049  *
4050  * XXX It might be worth coalescing the entries added to the new vmspace.
4051  *
4052  * The source map must not be locked.
4053  */
4054 struct vmspace *
4055 vmspace_fork(struct vmspace *vm1, vm_ooffset_t *fork_charge)
4056 {
4057 	struct vmspace *vm2;
4058 	vm_map_t new_map, old_map;
4059 	vm_map_entry_t new_entry, old_entry;
4060 	vm_object_t object;
4061 	int error, locked;
4062 	vm_inherit_t inh;
4063 
4064 	old_map = &vm1->vm_map;
4065 	/* Copy immutable fields of vm1 to vm2. */
4066 	vm2 = vmspace_alloc(vm_map_min(old_map), vm_map_max(old_map),
4067 	    pmap_pinit);
4068 	if (vm2 == NULL)
4069 		return (NULL);
4070 
4071 	vm2->vm_taddr = vm1->vm_taddr;
4072 	vm2->vm_daddr = vm1->vm_daddr;
4073 	vm2->vm_maxsaddr = vm1->vm_maxsaddr;
4074 	vm_map_lock(old_map);
4075 	if (old_map->busy)
4076 		vm_map_wait_busy(old_map);
4077 	new_map = &vm2->vm_map;
4078 	locked = vm_map_trylock(new_map); /* trylock to silence WITNESS */
4079 	KASSERT(locked, ("vmspace_fork: lock failed"));
4080 
4081 	error = pmap_vmspace_copy(new_map->pmap, old_map->pmap);
4082 	if (error != 0) {
4083 		sx_xunlock(&old_map->lock);
4084 		sx_xunlock(&new_map->lock);
4085 		vm_map_process_deferred();
4086 		vmspace_free(vm2);
4087 		return (NULL);
4088 	}
4089 
4090 	new_map->anon_loc = old_map->anon_loc;
4091 
4092 	VM_MAP_ENTRY_FOREACH(old_entry, old_map) {
4093 		if ((old_entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
4094 			panic("vm_map_fork: encountered a submap");
4095 
4096 		inh = old_entry->inheritance;
4097 		if ((old_entry->eflags & MAP_ENTRY_GUARD) != 0 &&
4098 		    inh != VM_INHERIT_NONE)
4099 			inh = VM_INHERIT_COPY;
4100 
4101 		switch (inh) {
4102 		case VM_INHERIT_NONE:
4103 			break;
4104 
4105 		case VM_INHERIT_SHARE:
4106 			/*
4107 			 * Clone the entry, creating the shared object if
4108 			 * necessary.
4109 			 */
4110 			object = old_entry->object.vm_object;
4111 			if (object == NULL) {
4112 				vm_map_entry_back(old_entry);
4113 				object = old_entry->object.vm_object;
4114 			}
4115 
4116 			/*
4117 			 * Add the reference before calling vm_object_shadow
4118 			 * to insure that a shadow object is created.
4119 			 */
4120 			vm_object_reference(object);
4121 			if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4122 				vm_object_shadow(&old_entry->object.vm_object,
4123 				    &old_entry->offset,
4124 				    old_entry->end - old_entry->start,
4125 				    old_entry->cred,
4126 				    /* Transfer the second reference too. */
4127 				    true);
4128 				old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
4129 				old_entry->cred = NULL;
4130 				vm_object_reference(
4131 				    old_entry->object.vm_object);
4132 
4133 				/*
4134 				 * As in vm_map_merged_neighbor_dispose(),
4135 				 * the vnode lock will not be acquired in
4136 				 * this call to vm_object_deallocate().
4137 				 */
4138 				vm_object_deallocate(object);
4139 				object = old_entry->object.vm_object;
4140 			} else {
4141 				VM_OBJECT_WLOCK(object);
4142 				vm_object_clear_flag(object, OBJ_ONEMAPPING);
4143 				if (old_entry->cred != NULL) {
4144 					KASSERT(object->cred == NULL,
4145 					    ("vmspace_fork both cred"));
4146 					object->cred = old_entry->cred;
4147 					object->charge = old_entry->end -
4148 					    old_entry->start;
4149 					old_entry->cred = NULL;
4150 				}
4151 
4152 				/*
4153 				 * Assert the correct state of the vnode
4154 				 * v_writecount while the object is locked, to
4155 				 * not relock it later for the assertion
4156 				 * correctness.
4157 				 */
4158 				if (old_entry->eflags & MAP_ENTRY_WRITECNT &&
4159 				    object->type == OBJT_VNODE) {
4160 					KASSERT(((struct vnode *)object->
4161 					    handle)->v_writecount > 0,
4162 					    ("vmspace_fork: v_writecount %p",
4163 					    object));
4164 					KASSERT(object->un_pager.vnp.
4165 					    writemappings > 0,
4166 					    ("vmspace_fork: vnp.writecount %p",
4167 					    object));
4168 				}
4169 				VM_OBJECT_WUNLOCK(object);
4170 			}
4171 
4172 			/*
4173 			 * Clone the entry, referencing the shared object.
4174 			 */
4175 			new_entry = vm_map_entry_create(new_map);
4176 			*new_entry = *old_entry;
4177 			new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
4178 			    MAP_ENTRY_IN_TRANSITION);
4179 			new_entry->wiring_thread = NULL;
4180 			new_entry->wired_count = 0;
4181 			if (new_entry->eflags & MAP_ENTRY_WRITECNT) {
4182 				vm_pager_update_writecount(object,
4183 				    new_entry->start, new_entry->end);
4184 			}
4185 			vm_map_entry_set_vnode_text(new_entry, true);
4186 
4187 			/*
4188 			 * Insert the entry into the new map -- we know we're
4189 			 * inserting at the end of the new map.
4190 			 */
4191 			vm_map_entry_link(new_map, new_entry);
4192 			vmspace_map_entry_forked(vm1, vm2, new_entry);
4193 
4194 			/*
4195 			 * Update the physical map
4196 			 */
4197 			pmap_copy(new_map->pmap, old_map->pmap,
4198 			    new_entry->start,
4199 			    (old_entry->end - old_entry->start),
4200 			    old_entry->start);
4201 			break;
4202 
4203 		case VM_INHERIT_COPY:
4204 			/*
4205 			 * Clone the entry and link into the map.
4206 			 */
4207 			new_entry = vm_map_entry_create(new_map);
4208 			*new_entry = *old_entry;
4209 			/*
4210 			 * Copied entry is COW over the old object.
4211 			 */
4212 			new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
4213 			    MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_WRITECNT);
4214 			new_entry->wiring_thread = NULL;
4215 			new_entry->wired_count = 0;
4216 			new_entry->object.vm_object = NULL;
4217 			new_entry->cred = NULL;
4218 			vm_map_entry_link(new_map, new_entry);
4219 			vmspace_map_entry_forked(vm1, vm2, new_entry);
4220 			vm_map_copy_entry(old_map, new_map, old_entry,
4221 			    new_entry, fork_charge);
4222 			vm_map_entry_set_vnode_text(new_entry, true);
4223 			break;
4224 
4225 		case VM_INHERIT_ZERO:
4226 			/*
4227 			 * Create a new anonymous mapping entry modelled from
4228 			 * the old one.
4229 			 */
4230 			new_entry = vm_map_entry_create(new_map);
4231 			memset(new_entry, 0, sizeof(*new_entry));
4232 
4233 			new_entry->start = old_entry->start;
4234 			new_entry->end = old_entry->end;
4235 			new_entry->eflags = old_entry->eflags &
4236 			    ~(MAP_ENTRY_USER_WIRED | MAP_ENTRY_IN_TRANSITION |
4237 			    MAP_ENTRY_WRITECNT | MAP_ENTRY_VN_EXEC);
4238 			new_entry->protection = old_entry->protection;
4239 			new_entry->max_protection = old_entry->max_protection;
4240 			new_entry->inheritance = VM_INHERIT_ZERO;
4241 
4242 			vm_map_entry_link(new_map, new_entry);
4243 			vmspace_map_entry_forked(vm1, vm2, new_entry);
4244 
4245 			new_entry->cred = curthread->td_ucred;
4246 			crhold(new_entry->cred);
4247 			*fork_charge += (new_entry->end - new_entry->start);
4248 
4249 			break;
4250 		}
4251 	}
4252 	/*
4253 	 * Use inlined vm_map_unlock() to postpone handling the deferred
4254 	 * map entries, which cannot be done until both old_map and
4255 	 * new_map locks are released.
4256 	 */
4257 	sx_xunlock(&old_map->lock);
4258 	sx_xunlock(&new_map->lock);
4259 	vm_map_process_deferred();
4260 
4261 	return (vm2);
4262 }
4263 
4264 /*
4265  * Create a process's stack for exec_new_vmspace().  This function is never
4266  * asked to wire the newly created stack.
4267  */
4268 int
4269 vm_map_stack(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
4270     vm_prot_t prot, vm_prot_t max, int cow)
4271 {
4272 	vm_size_t growsize, init_ssize;
4273 	rlim_t vmemlim;
4274 	int rv;
4275 
4276 	MPASS((map->flags & MAP_WIREFUTURE) == 0);
4277 	growsize = sgrowsiz;
4278 	init_ssize = (max_ssize < growsize) ? max_ssize : growsize;
4279 	vm_map_lock(map);
4280 	vmemlim = lim_cur(curthread, RLIMIT_VMEM);
4281 	/* If we would blow our VMEM resource limit, no go */
4282 	if (map->size + init_ssize > vmemlim) {
4283 		rv = KERN_NO_SPACE;
4284 		goto out;
4285 	}
4286 	rv = vm_map_stack_locked(map, addrbos, max_ssize, growsize, prot,
4287 	    max, cow);
4288 out:
4289 	vm_map_unlock(map);
4290 	return (rv);
4291 }
4292 
4293 static int stack_guard_page = 1;
4294 SYSCTL_INT(_security_bsd, OID_AUTO, stack_guard_page, CTLFLAG_RWTUN,
4295     &stack_guard_page, 0,
4296     "Specifies the number of guard pages for a stack that grows");
4297 
4298 static int
4299 vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
4300     vm_size_t growsize, vm_prot_t prot, vm_prot_t max, int cow)
4301 {
4302 	vm_map_entry_t new_entry, prev_entry;
4303 	vm_offset_t bot, gap_bot, gap_top, top;
4304 	vm_size_t init_ssize, sgp;
4305 	int orient, rv;
4306 
4307 	/*
4308 	 * The stack orientation is piggybacked with the cow argument.
4309 	 * Extract it into orient and mask the cow argument so that we
4310 	 * don't pass it around further.
4311 	 */
4312 	orient = cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP);
4313 	KASSERT(orient != 0, ("No stack grow direction"));
4314 	KASSERT(orient != (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP),
4315 	    ("bi-dir stack"));
4316 
4317 	if (addrbos < vm_map_min(map) ||
4318 	    addrbos + max_ssize > vm_map_max(map) ||
4319 	    addrbos + max_ssize <= addrbos)
4320 		return (KERN_INVALID_ADDRESS);
4321 	sgp = ((curproc->p_flag2 & P2_STKGAP_DISABLE) != 0 ||
4322 	    (curproc->p_fctl0 & NT_FREEBSD_FCTL_STKGAP_DISABLE) != 0) ? 0 :
4323 	    (vm_size_t)stack_guard_page * PAGE_SIZE;
4324 	if (sgp >= max_ssize)
4325 		return (KERN_INVALID_ARGUMENT);
4326 
4327 	init_ssize = growsize;
4328 	if (max_ssize < init_ssize + sgp)
4329 		init_ssize = max_ssize - sgp;
4330 
4331 	/* If addr is already mapped, no go */
4332 	if (vm_map_lookup_entry(map, addrbos, &prev_entry))
4333 		return (KERN_NO_SPACE);
4334 
4335 	/*
4336 	 * If we can't accommodate max_ssize in the current mapping, no go.
4337 	 */
4338 	if (vm_map_entry_succ(prev_entry)->start < addrbos + max_ssize)
4339 		return (KERN_NO_SPACE);
4340 
4341 	/*
4342 	 * We initially map a stack of only init_ssize.  We will grow as
4343 	 * needed later.  Depending on the orientation of the stack (i.e.
4344 	 * the grow direction) we either map at the top of the range, the
4345 	 * bottom of the range or in the middle.
4346 	 *
4347 	 * Note: we would normally expect prot and max to be VM_PROT_ALL,
4348 	 * and cow to be 0.  Possibly we should eliminate these as input
4349 	 * parameters, and just pass these values here in the insert call.
4350 	 */
4351 	if (orient == MAP_STACK_GROWS_DOWN) {
4352 		bot = addrbos + max_ssize - init_ssize;
4353 		top = bot + init_ssize;
4354 		gap_bot = addrbos;
4355 		gap_top = bot;
4356 	} else /* if (orient == MAP_STACK_GROWS_UP) */ {
4357 		bot = addrbos;
4358 		top = bot + init_ssize;
4359 		gap_bot = top;
4360 		gap_top = addrbos + max_ssize;
4361 	}
4362 	rv = vm_map_insert(map, NULL, 0, bot, top, prot, max, cow);
4363 	if (rv != KERN_SUCCESS)
4364 		return (rv);
4365 	new_entry = vm_map_entry_succ(prev_entry);
4366 	KASSERT(new_entry->end == top || new_entry->start == bot,
4367 	    ("Bad entry start/end for new stack entry"));
4368 	KASSERT((orient & MAP_STACK_GROWS_DOWN) == 0 ||
4369 	    (new_entry->eflags & MAP_ENTRY_GROWS_DOWN) != 0,
4370 	    ("new entry lacks MAP_ENTRY_GROWS_DOWN"));
4371 	KASSERT((orient & MAP_STACK_GROWS_UP) == 0 ||
4372 	    (new_entry->eflags & MAP_ENTRY_GROWS_UP) != 0,
4373 	    ("new entry lacks MAP_ENTRY_GROWS_UP"));
4374 	if (gap_bot == gap_top)
4375 		return (KERN_SUCCESS);
4376 	rv = vm_map_insert(map, NULL, 0, gap_bot, gap_top, VM_PROT_NONE,
4377 	    VM_PROT_NONE, MAP_CREATE_GUARD | (orient == MAP_STACK_GROWS_DOWN ?
4378 	    MAP_CREATE_STACK_GAP_DN : MAP_CREATE_STACK_GAP_UP));
4379 	if (rv == KERN_SUCCESS) {
4380 		/*
4381 		 * Gap can never successfully handle a fault, so
4382 		 * read-ahead logic is never used for it.  Re-use
4383 		 * next_read of the gap entry to store
4384 		 * stack_guard_page for vm_map_growstack().
4385 		 */
4386 		if (orient == MAP_STACK_GROWS_DOWN)
4387 			vm_map_entry_pred(new_entry)->next_read = sgp;
4388 		else
4389 			vm_map_entry_succ(new_entry)->next_read = sgp;
4390 	} else {
4391 		(void)vm_map_delete(map, bot, top);
4392 	}
4393 	return (rv);
4394 }
4395 
4396 /*
4397  * Attempts to grow a vm stack entry.  Returns KERN_SUCCESS if we
4398  * successfully grow the stack.
4399  */
4400 static int
4401 vm_map_growstack(vm_map_t map, vm_offset_t addr, vm_map_entry_t gap_entry)
4402 {
4403 	vm_map_entry_t stack_entry;
4404 	struct proc *p;
4405 	struct vmspace *vm;
4406 	struct ucred *cred;
4407 	vm_offset_t gap_end, gap_start, grow_start;
4408 	vm_size_t grow_amount, guard, max_grow;
4409 	rlim_t lmemlim, stacklim, vmemlim;
4410 	int rv, rv1;
4411 	bool gap_deleted, grow_down, is_procstack;
4412 #ifdef notyet
4413 	uint64_t limit;
4414 #endif
4415 #ifdef RACCT
4416 	int error;
4417 #endif
4418 
4419 	p = curproc;
4420 	vm = p->p_vmspace;
4421 
4422 	/*
4423 	 * Disallow stack growth when the access is performed by a
4424 	 * debugger or AIO daemon.  The reason is that the wrong
4425 	 * resource limits are applied.
4426 	 */
4427 	if (p != initproc && (map != &p->p_vmspace->vm_map ||
4428 	    p->p_textvp == NULL))
4429 		return (KERN_FAILURE);
4430 
4431 	MPASS(!map->system_map);
4432 
4433 	lmemlim = lim_cur(curthread, RLIMIT_MEMLOCK);
4434 	stacklim = lim_cur(curthread, RLIMIT_STACK);
4435 	vmemlim = lim_cur(curthread, RLIMIT_VMEM);
4436 retry:
4437 	/* If addr is not in a hole for a stack grow area, no need to grow. */
4438 	if (gap_entry == NULL && !vm_map_lookup_entry(map, addr, &gap_entry))
4439 		return (KERN_FAILURE);
4440 	if ((gap_entry->eflags & MAP_ENTRY_GUARD) == 0)
4441 		return (KERN_SUCCESS);
4442 	if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_DN) != 0) {
4443 		stack_entry = vm_map_entry_succ(gap_entry);
4444 		if ((stack_entry->eflags & MAP_ENTRY_GROWS_DOWN) == 0 ||
4445 		    stack_entry->start != gap_entry->end)
4446 			return (KERN_FAILURE);
4447 		grow_amount = round_page(stack_entry->start - addr);
4448 		grow_down = true;
4449 	} else if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_UP) != 0) {
4450 		stack_entry = vm_map_entry_pred(gap_entry);
4451 		if ((stack_entry->eflags & MAP_ENTRY_GROWS_UP) == 0 ||
4452 		    stack_entry->end != gap_entry->start)
4453 			return (KERN_FAILURE);
4454 		grow_amount = round_page(addr + 1 - stack_entry->end);
4455 		grow_down = false;
4456 	} else {
4457 		return (KERN_FAILURE);
4458 	}
4459 	guard = ((curproc->p_flag2 & P2_STKGAP_DISABLE) != 0 ||
4460 	    (curproc->p_fctl0 & NT_FREEBSD_FCTL_STKGAP_DISABLE) != 0) ? 0 :
4461 	    gap_entry->next_read;
4462 	max_grow = gap_entry->end - gap_entry->start;
4463 	if (guard > max_grow)
4464 		return (KERN_NO_SPACE);
4465 	max_grow -= guard;
4466 	if (grow_amount > max_grow)
4467 		return (KERN_NO_SPACE);
4468 
4469 	/*
4470 	 * If this is the main process stack, see if we're over the stack
4471 	 * limit.
4472 	 */
4473 	is_procstack = addr >= (vm_offset_t)vm->vm_maxsaddr &&
4474 	    addr < (vm_offset_t)p->p_sysent->sv_usrstack;
4475 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim))
4476 		return (KERN_NO_SPACE);
4477 
4478 #ifdef RACCT
4479 	if (racct_enable) {
4480 		PROC_LOCK(p);
4481 		if (is_procstack && racct_set(p, RACCT_STACK,
4482 		    ctob(vm->vm_ssize) + grow_amount)) {
4483 			PROC_UNLOCK(p);
4484 			return (KERN_NO_SPACE);
4485 		}
4486 		PROC_UNLOCK(p);
4487 	}
4488 #endif
4489 
4490 	grow_amount = roundup(grow_amount, sgrowsiz);
4491 	if (grow_amount > max_grow)
4492 		grow_amount = max_grow;
4493 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
4494 		grow_amount = trunc_page((vm_size_t)stacklim) -
4495 		    ctob(vm->vm_ssize);
4496 	}
4497 
4498 #ifdef notyet
4499 	PROC_LOCK(p);
4500 	limit = racct_get_available(p, RACCT_STACK);
4501 	PROC_UNLOCK(p);
4502 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > limit))
4503 		grow_amount = limit - ctob(vm->vm_ssize);
4504 #endif
4505 
4506 	if (!old_mlock && (map->flags & MAP_WIREFUTURE) != 0) {
4507 		if (ptoa(pmap_wired_count(map->pmap)) + grow_amount > lmemlim) {
4508 			rv = KERN_NO_SPACE;
4509 			goto out;
4510 		}
4511 #ifdef RACCT
4512 		if (racct_enable) {
4513 			PROC_LOCK(p);
4514 			if (racct_set(p, RACCT_MEMLOCK,
4515 			    ptoa(pmap_wired_count(map->pmap)) + grow_amount)) {
4516 				PROC_UNLOCK(p);
4517 				rv = KERN_NO_SPACE;
4518 				goto out;
4519 			}
4520 			PROC_UNLOCK(p);
4521 		}
4522 #endif
4523 	}
4524 
4525 	/* If we would blow our VMEM resource limit, no go */
4526 	if (map->size + grow_amount > vmemlim) {
4527 		rv = KERN_NO_SPACE;
4528 		goto out;
4529 	}
4530 #ifdef RACCT
4531 	if (racct_enable) {
4532 		PROC_LOCK(p);
4533 		if (racct_set(p, RACCT_VMEM, map->size + grow_amount)) {
4534 			PROC_UNLOCK(p);
4535 			rv = KERN_NO_SPACE;
4536 			goto out;
4537 		}
4538 		PROC_UNLOCK(p);
4539 	}
4540 #endif
4541 
4542 	if (vm_map_lock_upgrade(map)) {
4543 		gap_entry = NULL;
4544 		vm_map_lock_read(map);
4545 		goto retry;
4546 	}
4547 
4548 	if (grow_down) {
4549 		grow_start = gap_entry->end - grow_amount;
4550 		if (gap_entry->start + grow_amount == gap_entry->end) {
4551 			gap_start = gap_entry->start;
4552 			gap_end = gap_entry->end;
4553 			vm_map_entry_delete(map, gap_entry);
4554 			gap_deleted = true;
4555 		} else {
4556 			MPASS(gap_entry->start < gap_entry->end - grow_amount);
4557 			vm_map_entry_resize(map, gap_entry, -grow_amount);
4558 			gap_deleted = false;
4559 		}
4560 		rv = vm_map_insert(map, NULL, 0, grow_start,
4561 		    grow_start + grow_amount,
4562 		    stack_entry->protection, stack_entry->max_protection,
4563 		    MAP_STACK_GROWS_DOWN);
4564 		if (rv != KERN_SUCCESS) {
4565 			if (gap_deleted) {
4566 				rv1 = vm_map_insert(map, NULL, 0, gap_start,
4567 				    gap_end, VM_PROT_NONE, VM_PROT_NONE,
4568 				    MAP_CREATE_GUARD | MAP_CREATE_STACK_GAP_DN);
4569 				MPASS(rv1 == KERN_SUCCESS);
4570 			} else
4571 				vm_map_entry_resize(map, gap_entry,
4572 				    grow_amount);
4573 		}
4574 	} else {
4575 		grow_start = stack_entry->end;
4576 		cred = stack_entry->cred;
4577 		if (cred == NULL && stack_entry->object.vm_object != NULL)
4578 			cred = stack_entry->object.vm_object->cred;
4579 		if (cred != NULL && !swap_reserve_by_cred(grow_amount, cred))
4580 			rv = KERN_NO_SPACE;
4581 		/* Grow the underlying object if applicable. */
4582 		else if (stack_entry->object.vm_object == NULL ||
4583 		    vm_object_coalesce(stack_entry->object.vm_object,
4584 		    stack_entry->offset,
4585 		    (vm_size_t)(stack_entry->end - stack_entry->start),
4586 		    grow_amount, cred != NULL)) {
4587 			if (gap_entry->start + grow_amount == gap_entry->end) {
4588 				vm_map_entry_delete(map, gap_entry);
4589 				vm_map_entry_resize(map, stack_entry,
4590 				    grow_amount);
4591 			} else {
4592 				gap_entry->start += grow_amount;
4593 				stack_entry->end += grow_amount;
4594 			}
4595 			map->size += grow_amount;
4596 			rv = KERN_SUCCESS;
4597 		} else
4598 			rv = KERN_FAILURE;
4599 	}
4600 	if (rv == KERN_SUCCESS && is_procstack)
4601 		vm->vm_ssize += btoc(grow_amount);
4602 
4603 	/*
4604 	 * Heed the MAP_WIREFUTURE flag if it was set for this process.
4605 	 */
4606 	if (rv == KERN_SUCCESS && (map->flags & MAP_WIREFUTURE) != 0) {
4607 		rv = vm_map_wire_locked(map, grow_start,
4608 		    grow_start + grow_amount,
4609 		    VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
4610 	}
4611 	vm_map_lock_downgrade(map);
4612 
4613 out:
4614 #ifdef RACCT
4615 	if (racct_enable && rv != KERN_SUCCESS) {
4616 		PROC_LOCK(p);
4617 		error = racct_set(p, RACCT_VMEM, map->size);
4618 		KASSERT(error == 0, ("decreasing RACCT_VMEM failed"));
4619 		if (!old_mlock) {
4620 			error = racct_set(p, RACCT_MEMLOCK,
4621 			    ptoa(pmap_wired_count(map->pmap)));
4622 			KASSERT(error == 0, ("decreasing RACCT_MEMLOCK failed"));
4623 		}
4624 	    	error = racct_set(p, RACCT_STACK, ctob(vm->vm_ssize));
4625 		KASSERT(error == 0, ("decreasing RACCT_STACK failed"));
4626 		PROC_UNLOCK(p);
4627 	}
4628 #endif
4629 
4630 	return (rv);
4631 }
4632 
4633 /*
4634  * Unshare the specified VM space for exec.  If other processes are
4635  * mapped to it, then create a new one.  The new vmspace is null.
4636  */
4637 int
4638 vmspace_exec(struct proc *p, vm_offset_t minuser, vm_offset_t maxuser)
4639 {
4640 	struct vmspace *oldvmspace = p->p_vmspace;
4641 	struct vmspace *newvmspace;
4642 
4643 	KASSERT((curthread->td_pflags & TDP_EXECVMSPC) == 0,
4644 	    ("vmspace_exec recursed"));
4645 	newvmspace = vmspace_alloc(minuser, maxuser, pmap_pinit);
4646 	if (newvmspace == NULL)
4647 		return (ENOMEM);
4648 	newvmspace->vm_swrss = oldvmspace->vm_swrss;
4649 	/*
4650 	 * This code is written like this for prototype purposes.  The
4651 	 * goal is to avoid running down the vmspace here, but let the
4652 	 * other process's that are still using the vmspace to finally
4653 	 * run it down.  Even though there is little or no chance of blocking
4654 	 * here, it is a good idea to keep this form for future mods.
4655 	 */
4656 	PROC_VMSPACE_LOCK(p);
4657 	p->p_vmspace = newvmspace;
4658 	PROC_VMSPACE_UNLOCK(p);
4659 	if (p == curthread->td_proc)
4660 		pmap_activate(curthread);
4661 	curthread->td_pflags |= TDP_EXECVMSPC;
4662 	return (0);
4663 }
4664 
4665 /*
4666  * Unshare the specified VM space for forcing COW.  This
4667  * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
4668  */
4669 int
4670 vmspace_unshare(struct proc *p)
4671 {
4672 	struct vmspace *oldvmspace = p->p_vmspace;
4673 	struct vmspace *newvmspace;
4674 	vm_ooffset_t fork_charge;
4675 
4676 	if (oldvmspace->vm_refcnt == 1)
4677 		return (0);
4678 	fork_charge = 0;
4679 	newvmspace = vmspace_fork(oldvmspace, &fork_charge);
4680 	if (newvmspace == NULL)
4681 		return (ENOMEM);
4682 	if (!swap_reserve_by_cred(fork_charge, p->p_ucred)) {
4683 		vmspace_free(newvmspace);
4684 		return (ENOMEM);
4685 	}
4686 	PROC_VMSPACE_LOCK(p);
4687 	p->p_vmspace = newvmspace;
4688 	PROC_VMSPACE_UNLOCK(p);
4689 	if (p == curthread->td_proc)
4690 		pmap_activate(curthread);
4691 	vmspace_free(oldvmspace);
4692 	return (0);
4693 }
4694 
4695 /*
4696  *	vm_map_lookup:
4697  *
4698  *	Finds the VM object, offset, and
4699  *	protection for a given virtual address in the
4700  *	specified map, assuming a page fault of the
4701  *	type specified.
4702  *
4703  *	Leaves the map in question locked for read; return
4704  *	values are guaranteed until a vm_map_lookup_done
4705  *	call is performed.  Note that the map argument
4706  *	is in/out; the returned map must be used in
4707  *	the call to vm_map_lookup_done.
4708  *
4709  *	A handle (out_entry) is returned for use in
4710  *	vm_map_lookup_done, to make that fast.
4711  *
4712  *	If a lookup is requested with "write protection"
4713  *	specified, the map may be changed to perform virtual
4714  *	copying operations, although the data referenced will
4715  *	remain the same.
4716  */
4717 int
4718 vm_map_lookup(vm_map_t *var_map,		/* IN/OUT */
4719 	      vm_offset_t vaddr,
4720 	      vm_prot_t fault_typea,
4721 	      vm_map_entry_t *out_entry,	/* OUT */
4722 	      vm_object_t *object,		/* OUT */
4723 	      vm_pindex_t *pindex,		/* OUT */
4724 	      vm_prot_t *out_prot,		/* OUT */
4725 	      boolean_t *wired)			/* OUT */
4726 {
4727 	vm_map_entry_t entry;
4728 	vm_map_t map = *var_map;
4729 	vm_prot_t prot;
4730 	vm_prot_t fault_type;
4731 	vm_object_t eobject;
4732 	vm_size_t size;
4733 	struct ucred *cred;
4734 
4735 RetryLookup:
4736 
4737 	vm_map_lock_read(map);
4738 
4739 RetryLookupLocked:
4740 	/*
4741 	 * Lookup the faulting address.
4742 	 */
4743 	if (!vm_map_lookup_entry(map, vaddr, out_entry)) {
4744 		vm_map_unlock_read(map);
4745 		return (KERN_INVALID_ADDRESS);
4746 	}
4747 
4748 	entry = *out_entry;
4749 
4750 	/*
4751 	 * Handle submaps.
4752 	 */
4753 	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
4754 		vm_map_t old_map = map;
4755 
4756 		*var_map = map = entry->object.sub_map;
4757 		vm_map_unlock_read(old_map);
4758 		goto RetryLookup;
4759 	}
4760 
4761 	/*
4762 	 * Check whether this task is allowed to have this page.
4763 	 */
4764 	prot = entry->protection;
4765 	if ((fault_typea & VM_PROT_FAULT_LOOKUP) != 0) {
4766 		fault_typea &= ~VM_PROT_FAULT_LOOKUP;
4767 		if (prot == VM_PROT_NONE && map != kernel_map &&
4768 		    (entry->eflags & MAP_ENTRY_GUARD) != 0 &&
4769 		    (entry->eflags & (MAP_ENTRY_STACK_GAP_DN |
4770 		    MAP_ENTRY_STACK_GAP_UP)) != 0 &&
4771 		    vm_map_growstack(map, vaddr, entry) == KERN_SUCCESS)
4772 			goto RetryLookupLocked;
4773 	}
4774 	fault_type = fault_typea & VM_PROT_ALL;
4775 	if ((fault_type & prot) != fault_type || prot == VM_PROT_NONE) {
4776 		vm_map_unlock_read(map);
4777 		return (KERN_PROTECTION_FAILURE);
4778 	}
4779 	KASSERT((prot & VM_PROT_WRITE) == 0 || (entry->eflags &
4780 	    (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY)) !=
4781 	    (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY),
4782 	    ("entry %p flags %x", entry, entry->eflags));
4783 	if ((fault_typea & VM_PROT_COPY) != 0 &&
4784 	    (entry->max_protection & VM_PROT_WRITE) == 0 &&
4785 	    (entry->eflags & MAP_ENTRY_COW) == 0) {
4786 		vm_map_unlock_read(map);
4787 		return (KERN_PROTECTION_FAILURE);
4788 	}
4789 
4790 	/*
4791 	 * If this page is not pageable, we have to get it for all possible
4792 	 * accesses.
4793 	 */
4794 	*wired = (entry->wired_count != 0);
4795 	if (*wired)
4796 		fault_type = entry->protection;
4797 	size = entry->end - entry->start;
4798 
4799 	/*
4800 	 * If the entry was copy-on-write, we either ...
4801 	 */
4802 	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4803 		/*
4804 		 * If we want to write the page, we may as well handle that
4805 		 * now since we've got the map locked.
4806 		 *
4807 		 * If we don't need to write the page, we just demote the
4808 		 * permissions allowed.
4809 		 */
4810 		if ((fault_type & VM_PROT_WRITE) != 0 ||
4811 		    (fault_typea & VM_PROT_COPY) != 0) {
4812 			/*
4813 			 * Make a new object, and place it in the object
4814 			 * chain.  Note that no new references have appeared
4815 			 * -- one just moved from the map to the new
4816 			 * object.
4817 			 */
4818 			if (vm_map_lock_upgrade(map))
4819 				goto RetryLookup;
4820 
4821 			if (entry->cred == NULL) {
4822 				/*
4823 				 * The debugger owner is charged for
4824 				 * the memory.
4825 				 */
4826 				cred = curthread->td_ucred;
4827 				crhold(cred);
4828 				if (!swap_reserve_by_cred(size, cred)) {
4829 					crfree(cred);
4830 					vm_map_unlock(map);
4831 					return (KERN_RESOURCE_SHORTAGE);
4832 				}
4833 				entry->cred = cred;
4834 			}
4835 			eobject = entry->object.vm_object;
4836 			vm_object_shadow(&entry->object.vm_object,
4837 			    &entry->offset, size, entry->cred, false);
4838 			if (eobject == entry->object.vm_object) {
4839 				/*
4840 				 * The object was not shadowed.
4841 				 */
4842 				swap_release_by_cred(size, entry->cred);
4843 				crfree(entry->cred);
4844 			}
4845 			entry->cred = NULL;
4846 			entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
4847 
4848 			vm_map_lock_downgrade(map);
4849 		} else {
4850 			/*
4851 			 * We're attempting to read a copy-on-write page --
4852 			 * don't allow writes.
4853 			 */
4854 			prot &= ~VM_PROT_WRITE;
4855 		}
4856 	}
4857 
4858 	/*
4859 	 * Create an object if necessary.
4860 	 */
4861 	if (entry->object.vm_object == NULL && !map->system_map) {
4862 		if (vm_map_lock_upgrade(map))
4863 			goto RetryLookup;
4864 		entry->object.vm_object = vm_object_allocate_anon(atop(size),
4865 		    NULL, entry->cred, entry->cred != NULL ? size : 0);
4866 		entry->offset = 0;
4867 		entry->cred = NULL;
4868 		vm_map_lock_downgrade(map);
4869 	}
4870 
4871 	/*
4872 	 * Return the object/offset from this entry.  If the entry was
4873 	 * copy-on-write or empty, it has been fixed up.
4874 	 */
4875 	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4876 	*object = entry->object.vm_object;
4877 
4878 	*out_prot = prot;
4879 	return (KERN_SUCCESS);
4880 }
4881 
4882 /*
4883  *	vm_map_lookup_locked:
4884  *
4885  *	Lookup the faulting address.  A version of vm_map_lookup that returns
4886  *      KERN_FAILURE instead of blocking on map lock or memory allocation.
4887  */
4888 int
4889 vm_map_lookup_locked(vm_map_t *var_map,		/* IN/OUT */
4890 		     vm_offset_t vaddr,
4891 		     vm_prot_t fault_typea,
4892 		     vm_map_entry_t *out_entry,	/* OUT */
4893 		     vm_object_t *object,	/* OUT */
4894 		     vm_pindex_t *pindex,	/* OUT */
4895 		     vm_prot_t *out_prot,	/* OUT */
4896 		     boolean_t *wired)		/* OUT */
4897 {
4898 	vm_map_entry_t entry;
4899 	vm_map_t map = *var_map;
4900 	vm_prot_t prot;
4901 	vm_prot_t fault_type = fault_typea;
4902 
4903 	/*
4904 	 * Lookup the faulting address.
4905 	 */
4906 	if (!vm_map_lookup_entry(map, vaddr, out_entry))
4907 		return (KERN_INVALID_ADDRESS);
4908 
4909 	entry = *out_entry;
4910 
4911 	/*
4912 	 * Fail if the entry refers to a submap.
4913 	 */
4914 	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
4915 		return (KERN_FAILURE);
4916 
4917 	/*
4918 	 * Check whether this task is allowed to have this page.
4919 	 */
4920 	prot = entry->protection;
4921 	fault_type &= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
4922 	if ((fault_type & prot) != fault_type)
4923 		return (KERN_PROTECTION_FAILURE);
4924 
4925 	/*
4926 	 * If this page is not pageable, we have to get it for all possible
4927 	 * accesses.
4928 	 */
4929 	*wired = (entry->wired_count != 0);
4930 	if (*wired)
4931 		fault_type = entry->protection;
4932 
4933 	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4934 		/*
4935 		 * Fail if the entry was copy-on-write for a write fault.
4936 		 */
4937 		if (fault_type & VM_PROT_WRITE)
4938 			return (KERN_FAILURE);
4939 		/*
4940 		 * We're attempting to read a copy-on-write page --
4941 		 * don't allow writes.
4942 		 */
4943 		prot &= ~VM_PROT_WRITE;
4944 	}
4945 
4946 	/*
4947 	 * Fail if an object should be created.
4948 	 */
4949 	if (entry->object.vm_object == NULL && !map->system_map)
4950 		return (KERN_FAILURE);
4951 
4952 	/*
4953 	 * Return the object/offset from this entry.  If the entry was
4954 	 * copy-on-write or empty, it has been fixed up.
4955 	 */
4956 	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4957 	*object = entry->object.vm_object;
4958 
4959 	*out_prot = prot;
4960 	return (KERN_SUCCESS);
4961 }
4962 
4963 /*
4964  *	vm_map_lookup_done:
4965  *
4966  *	Releases locks acquired by a vm_map_lookup
4967  *	(according to the handle returned by that lookup).
4968  */
4969 void
4970 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry)
4971 {
4972 	/*
4973 	 * Unlock the main-level map
4974 	 */
4975 	vm_map_unlock_read(map);
4976 }
4977 
4978 vm_offset_t
4979 vm_map_max_KBI(const struct vm_map *map)
4980 {
4981 
4982 	return (vm_map_max(map));
4983 }
4984 
4985 vm_offset_t
4986 vm_map_min_KBI(const struct vm_map *map)
4987 {
4988 
4989 	return (vm_map_min(map));
4990 }
4991 
4992 pmap_t
4993 vm_map_pmap_KBI(vm_map_t map)
4994 {
4995 
4996 	return (map->pmap);
4997 }
4998 
4999 #ifdef INVARIANTS
5000 static void
5001 _vm_map_assert_consistent(vm_map_t map, int check)
5002 {
5003 	vm_map_entry_t entry, prev;
5004 	vm_map_entry_t cur, header, lbound, ubound;
5005 	vm_size_t max_left, max_right;
5006 
5007 #ifdef DIAGNOSTIC
5008 	++map->nupdates;
5009 #endif
5010 	if (enable_vmmap_check != check)
5011 		return;
5012 
5013 	header = prev = &map->header;
5014 	VM_MAP_ENTRY_FOREACH(entry, map) {
5015 		KASSERT(prev->end <= entry->start,
5016 		    ("map %p prev->end = %jx, start = %jx", map,
5017 		    (uintmax_t)prev->end, (uintmax_t)entry->start));
5018 		KASSERT(entry->start < entry->end,
5019 		    ("map %p start = %jx, end = %jx", map,
5020 		    (uintmax_t)entry->start, (uintmax_t)entry->end));
5021 		KASSERT(entry->left == header ||
5022 		    entry->left->start < entry->start,
5023 		    ("map %p left->start = %jx, start = %jx", map,
5024 		    (uintmax_t)entry->left->start, (uintmax_t)entry->start));
5025 		KASSERT(entry->right == header ||
5026 		    entry->start < entry->right->start,
5027 		    ("map %p start = %jx, right->start = %jx", map,
5028 		    (uintmax_t)entry->start, (uintmax_t)entry->right->start));
5029 		cur = map->root;
5030 		lbound = ubound = header;
5031 		for (;;) {
5032 			if (entry->start < cur->start) {
5033 				ubound = cur;
5034 				cur = cur->left;
5035 				KASSERT(cur != lbound,
5036 				    ("map %p cannot find %jx",
5037 				    map, (uintmax_t)entry->start));
5038 			} else if (cur->end <= entry->start) {
5039 				lbound = cur;
5040 				cur = cur->right;
5041 				KASSERT(cur != ubound,
5042 				    ("map %p cannot find %jx",
5043 				    map, (uintmax_t)entry->start));
5044 			} else {
5045 				KASSERT(cur == entry,
5046 				    ("map %p cannot find %jx",
5047 				    map, (uintmax_t)entry->start));
5048 				break;
5049 			}
5050 		}
5051 		max_left = vm_map_entry_max_free_left(entry, lbound);
5052 		max_right = vm_map_entry_max_free_right(entry, ubound);
5053 		KASSERT(entry->max_free == vm_size_max(max_left, max_right),
5054 		    ("map %p max = %jx, max_left = %jx, max_right = %jx", map,
5055 		    (uintmax_t)entry->max_free,
5056 		    (uintmax_t)max_left, (uintmax_t)max_right));
5057 		prev = entry;
5058 	}
5059 	KASSERT(prev->end <= entry->start,
5060 	    ("map %p prev->end = %jx, start = %jx", map,
5061 	    (uintmax_t)prev->end, (uintmax_t)entry->start));
5062 }
5063 #endif
5064 
5065 #include "opt_ddb.h"
5066 #ifdef DDB
5067 #include <sys/kernel.h>
5068 
5069 #include <ddb/ddb.h>
5070 
5071 static void
5072 vm_map_print(vm_map_t map)
5073 {
5074 	vm_map_entry_t entry, prev;
5075 
5076 	db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
5077 	    (void *)map,
5078 	    (void *)map->pmap, map->nentries, map->timestamp);
5079 
5080 	db_indent += 2;
5081 	prev = &map->header;
5082 	VM_MAP_ENTRY_FOREACH(entry, map) {
5083 		db_iprintf("map entry %p: start=%p, end=%p, eflags=%#x, \n",
5084 		    (void *)entry, (void *)entry->start, (void *)entry->end,
5085 		    entry->eflags);
5086 		{
5087 			static char *inheritance_name[4] =
5088 			{"share", "copy", "none", "donate_copy"};
5089 
5090 			db_iprintf(" prot=%x/%x/%s",
5091 			    entry->protection,
5092 			    entry->max_protection,
5093 			    inheritance_name[(int)(unsigned char)
5094 			    entry->inheritance]);
5095 			if (entry->wired_count != 0)
5096 				db_printf(", wired");
5097 		}
5098 		if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
5099 			db_printf(", share=%p, offset=0x%jx\n",
5100 			    (void *)entry->object.sub_map,
5101 			    (uintmax_t)entry->offset);
5102 			if (prev == &map->header ||
5103 			    prev->object.sub_map !=
5104 				entry->object.sub_map) {
5105 				db_indent += 2;
5106 				vm_map_print((vm_map_t)entry->object.sub_map);
5107 				db_indent -= 2;
5108 			}
5109 		} else {
5110 			if (entry->cred != NULL)
5111 				db_printf(", ruid %d", entry->cred->cr_ruid);
5112 			db_printf(", object=%p, offset=0x%jx",
5113 			    (void *)entry->object.vm_object,
5114 			    (uintmax_t)entry->offset);
5115 			if (entry->object.vm_object && entry->object.vm_object->cred)
5116 				db_printf(", obj ruid %d charge %jx",
5117 				    entry->object.vm_object->cred->cr_ruid,
5118 				    (uintmax_t)entry->object.vm_object->charge);
5119 			if (entry->eflags & MAP_ENTRY_COW)
5120 				db_printf(", copy (%s)",
5121 				    (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
5122 			db_printf("\n");
5123 
5124 			if (prev == &map->header ||
5125 			    prev->object.vm_object !=
5126 				entry->object.vm_object) {
5127 				db_indent += 2;
5128 				vm_object_print((db_expr_t)(intptr_t)
5129 						entry->object.vm_object,
5130 						0, 0, (char *)0);
5131 				db_indent -= 2;
5132 			}
5133 		}
5134 		prev = entry;
5135 	}
5136 	db_indent -= 2;
5137 }
5138 
5139 DB_SHOW_COMMAND(map, map)
5140 {
5141 
5142 	if (!have_addr) {
5143 		db_printf("usage: show map <addr>\n");
5144 		return;
5145 	}
5146 	vm_map_print((vm_map_t)addr);
5147 }
5148 
5149 DB_SHOW_COMMAND(procvm, procvm)
5150 {
5151 	struct proc *p;
5152 
5153 	if (have_addr) {
5154 		p = db_lookup_proc(addr);
5155 	} else {
5156 		p = curproc;
5157 	}
5158 
5159 	db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
5160 	    (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
5161 	    (void *)vmspace_pmap(p->p_vmspace));
5162 
5163 	vm_map_print((vm_map_t)&p->p_vmspace->vm_map);
5164 }
5165 
5166 #endif /* DDB */
5167