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