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