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