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