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