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