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