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