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