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