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