xref: /freebsd/sys/vm/vm_map.c (revision ee7b0571c2c18bdec848ed2044223cc88db29bd8)
1 /*-
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * The Mach Operating System project at Carnegie-Mellon University.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	from: @(#)vm_map.c	8.3 (Berkeley) 1/12/94
33  *
34  *
35  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
36  * All rights reserved.
37  *
38  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
39  *
40  * Permission to use, copy, modify and distribute this software and
41  * its documentation is hereby granted, provided that both the copyright
42  * notice and this permission notice appear in all copies of the
43  * software, derivative works or modified versions, and any portions
44  * thereof, and that both notices appear in supporting documentation.
45  *
46  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
47  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
48  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
49  *
50  * Carnegie Mellon requests users of this software to return to
51  *
52  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
53  *  School of Computer Science
54  *  Carnegie Mellon University
55  *  Pittsburgh PA 15213-3890
56  *
57  * any improvements or extensions that they make and grant Carnegie the
58  * rights to redistribute these changes.
59  */
60 
61 /*
62  *	Virtual memory mapping module.
63  */
64 
65 #include <sys/cdefs.h>
66 __FBSDID("$FreeBSD$");
67 
68 #include <sys/param.h>
69 #include <sys/systm.h>
70 #include <sys/kernel.h>
71 #include <sys/ktr.h>
72 #include <sys/lock.h>
73 #include <sys/mutex.h>
74 #include <sys/proc.h>
75 #include <sys/vmmeter.h>
76 #include <sys/mman.h>
77 #include <sys/vnode.h>
78 #include <sys/racct.h>
79 #include <sys/resourcevar.h>
80 #include <sys/rwlock.h>
81 #include <sys/file.h>
82 #include <sys/sysctl.h>
83 #include <sys/sysent.h>
84 #include <sys/shm.h>
85 
86 #include <vm/vm.h>
87 #include <vm/vm_param.h>
88 #include <vm/pmap.h>
89 #include <vm/vm_map.h>
90 #include <vm/vm_page.h>
91 #include <vm/vm_object.h>
92 #include <vm/vm_pager.h>
93 #include <vm/vm_kern.h>
94 #include <vm/vm_extern.h>
95 #include <vm/vnode_pager.h>
96 #include <vm/swap_pager.h>
97 #include <vm/uma.h>
98 
99 /*
100  *	Virtual memory maps provide for the mapping, protection,
101  *	and sharing of virtual memory objects.  In addition,
102  *	this module provides for an efficient virtual copy of
103  *	memory from one map to another.
104  *
105  *	Synchronization is required prior to most operations.
106  *
107  *	Maps consist of an ordered doubly-linked list of simple
108  *	entries; a self-adjusting binary search tree of these
109  *	entries is used to speed up lookups.
110  *
111  *	Since portions of maps are specified by start/end addresses,
112  *	which may not align with existing map entries, all
113  *	routines merely "clip" entries to these start/end values.
114  *	[That is, an entry is split into two, bordering at a
115  *	start or end value.]  Note that these clippings may not
116  *	always be necessary (as the two resulting entries are then
117  *	not changed); however, the clipping is done for convenience.
118  *
119  *	As mentioned above, virtual copy operations are performed
120  *	by copying VM object references from one map to
121  *	another, and then marking both regions as copy-on-write.
122  */
123 
124 static struct mtx map_sleep_mtx;
125 static uma_zone_t mapentzone;
126 static uma_zone_t kmapentzone;
127 static uma_zone_t mapzone;
128 static uma_zone_t vmspace_zone;
129 static int vmspace_zinit(void *mem, int size, int flags);
130 static int vm_map_zinit(void *mem, int ize, int flags);
131 static void _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min,
132     vm_offset_t max);
133 static void vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map);
134 static void vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry);
135 static void vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry);
136 #ifdef INVARIANTS
137 static void vm_map_zdtor(void *mem, int size, void *arg);
138 static void vmspace_zdtor(void *mem, int size, void *arg);
139 #endif
140 static int vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos,
141     vm_size_t max_ssize, vm_size_t growsize, vm_prot_t prot, vm_prot_t max,
142     int cow);
143 
144 #define	ENTRY_CHARGED(e) ((e)->cred != NULL || \
145     ((e)->object.vm_object != NULL && (e)->object.vm_object->cred != NULL && \
146      !((e)->eflags & MAP_ENTRY_NEEDS_COPY)))
147 
148 /*
149  * PROC_VMSPACE_{UN,}LOCK() can be a noop as long as vmspaces are type
150  * stable.
151  */
152 #define PROC_VMSPACE_LOCK(p) do { } while (0)
153 #define PROC_VMSPACE_UNLOCK(p) do { } while (0)
154 
155 /*
156  *	VM_MAP_RANGE_CHECK:	[ internal use only ]
157  *
158  *	Asserts that the starting and ending region
159  *	addresses fall within the valid range of the map.
160  */
161 #define	VM_MAP_RANGE_CHECK(map, start, end)		\
162 		{					\
163 		if (start < vm_map_min(map))		\
164 			start = vm_map_min(map);	\
165 		if (end > vm_map_max(map))		\
166 			end = vm_map_max(map);		\
167 		if (start > end)			\
168 			start = end;			\
169 		}
170 
171 /*
172  *	vm_map_startup:
173  *
174  *	Initialize the vm_map module.  Must be called before
175  *	any other vm_map routines.
176  *
177  *	Map and entry structures are allocated from the general
178  *	purpose memory pool with some exceptions:
179  *
180  *	- The kernel map and kmem submap are allocated statically.
181  *	- Kernel map entries are allocated out of a static pool.
182  *
183  *	These restrictions are necessary since malloc() uses the
184  *	maps and requires map entries.
185  */
186 
187 void
188 vm_map_startup(void)
189 {
190 	mtx_init(&map_sleep_mtx, "vm map sleep mutex", NULL, MTX_DEF);
191 	mapzone = uma_zcreate("MAP", sizeof(struct vm_map), NULL,
192 #ifdef INVARIANTS
193 	    vm_map_zdtor,
194 #else
195 	    NULL,
196 #endif
197 	    vm_map_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
198 	uma_prealloc(mapzone, MAX_KMAP);
199 	kmapentzone = uma_zcreate("KMAP ENTRY", sizeof(struct vm_map_entry),
200 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
201 	    UMA_ZONE_MTXCLASS | UMA_ZONE_VM);
202 	mapentzone = uma_zcreate("MAP ENTRY", sizeof(struct vm_map_entry),
203 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
204 	vmspace_zone = uma_zcreate("VMSPACE", sizeof(struct vmspace), NULL,
205 #ifdef INVARIANTS
206 	    vmspace_zdtor,
207 #else
208 	    NULL,
209 #endif
210 	    vmspace_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
211 }
212 
213 static int
214 vmspace_zinit(void *mem, int size, int flags)
215 {
216 	struct vmspace *vm;
217 
218 	vm = (struct vmspace *)mem;
219 
220 	vm->vm_map.pmap = NULL;
221 	(void)vm_map_zinit(&vm->vm_map, sizeof(vm->vm_map), flags);
222 	PMAP_LOCK_INIT(vmspace_pmap(vm));
223 	return (0);
224 }
225 
226 static int
227 vm_map_zinit(void *mem, int size, int flags)
228 {
229 	vm_map_t map;
230 
231 	map = (vm_map_t)mem;
232 	memset(map, 0, sizeof(*map));
233 	mtx_init(&map->system_mtx, "vm map (system)", NULL, MTX_DEF | MTX_DUPOK);
234 	sx_init(&map->lock, "vm map (user)");
235 	return (0);
236 }
237 
238 #ifdef INVARIANTS
239 static void
240 vmspace_zdtor(void *mem, int size, void *arg)
241 {
242 	struct vmspace *vm;
243 
244 	vm = (struct vmspace *)mem;
245 
246 	vm_map_zdtor(&vm->vm_map, sizeof(vm->vm_map), arg);
247 }
248 static void
249 vm_map_zdtor(void *mem, int size, void *arg)
250 {
251 	vm_map_t map;
252 
253 	map = (vm_map_t)mem;
254 	KASSERT(map->nentries == 0,
255 	    ("map %p nentries == %d on free.",
256 	    map, map->nentries));
257 	KASSERT(map->size == 0,
258 	    ("map %p size == %lu on free.",
259 	    map, (unsigned long)map->size));
260 }
261 #endif	/* INVARIANTS */
262 
263 /*
264  * Allocate a vmspace structure, including a vm_map and pmap,
265  * and initialize those structures.  The refcnt is set to 1.
266  *
267  * If 'pinit' is NULL then the embedded pmap is initialized via pmap_pinit().
268  */
269 struct vmspace *
270 vmspace_alloc(vm_offset_t min, vm_offset_t max, pmap_pinit_t pinit)
271 {
272 	struct vmspace *vm;
273 
274 	vm = uma_zalloc(vmspace_zone, M_WAITOK);
275 
276 	KASSERT(vm->vm_map.pmap == NULL, ("vm_map.pmap must be NULL"));
277 
278 	if (pinit == NULL)
279 		pinit = &pmap_pinit;
280 
281 	if (!pinit(vmspace_pmap(vm))) {
282 		uma_zfree(vmspace_zone, vm);
283 		return (NULL);
284 	}
285 	CTR1(KTR_VM, "vmspace_alloc: %p", vm);
286 	_vm_map_init(&vm->vm_map, vmspace_pmap(vm), min, max);
287 	vm->vm_refcnt = 1;
288 	vm->vm_shm = NULL;
289 	vm->vm_swrss = 0;
290 	vm->vm_tsize = 0;
291 	vm->vm_dsize = 0;
292 	vm->vm_ssize = 0;
293 	vm->vm_taddr = 0;
294 	vm->vm_daddr = 0;
295 	vm->vm_maxsaddr = 0;
296 	return (vm);
297 }
298 
299 static void
300 vmspace_container_reset(struct proc *p)
301 {
302 
303 #ifdef RACCT
304 	PROC_LOCK(p);
305 	racct_set(p, RACCT_DATA, 0);
306 	racct_set(p, RACCT_STACK, 0);
307 	racct_set(p, RACCT_RSS, 0);
308 	racct_set(p, RACCT_MEMLOCK, 0);
309 	racct_set(p, RACCT_VMEM, 0);
310 	PROC_UNLOCK(p);
311 #endif
312 }
313 
314 static inline void
315 vmspace_dofree(struct vmspace *vm)
316 {
317 
318 	CTR1(KTR_VM, "vmspace_free: %p", vm);
319 
320 	/*
321 	 * Make sure any SysV shm is freed, it might not have been in
322 	 * exit1().
323 	 */
324 	shmexit(vm);
325 
326 	/*
327 	 * Lock the map, to wait out all other references to it.
328 	 * Delete all of the mappings and pages they hold, then call
329 	 * the pmap module to reclaim anything left.
330 	 */
331 	(void)vm_map_remove(&vm->vm_map, vm->vm_map.min_offset,
332 	    vm->vm_map.max_offset);
333 
334 	pmap_release(vmspace_pmap(vm));
335 	vm->vm_map.pmap = NULL;
336 	uma_zfree(vmspace_zone, vm);
337 }
338 
339 void
340 vmspace_free(struct vmspace *vm)
341 {
342 
343 	if (vm->vm_refcnt == 0)
344 		panic("vmspace_free: attempt to free already freed vmspace");
345 
346 	if (atomic_fetchadd_int(&vm->vm_refcnt, -1) == 1)
347 		vmspace_dofree(vm);
348 }
349 
350 void
351 vmspace_exitfree(struct proc *p)
352 {
353 	struct vmspace *vm;
354 
355 	PROC_VMSPACE_LOCK(p);
356 	vm = p->p_vmspace;
357 	p->p_vmspace = NULL;
358 	PROC_VMSPACE_UNLOCK(p);
359 	KASSERT(vm == &vmspace0, ("vmspace_exitfree: wrong vmspace"));
360 	vmspace_free(vm);
361 }
362 
363 void
364 vmspace_exit(struct thread *td)
365 {
366 	int refcnt;
367 	struct vmspace *vm;
368 	struct proc *p;
369 
370 	/*
371 	 * Release user portion of address space.
372 	 * This releases references to vnodes,
373 	 * which could cause I/O if the file has been unlinked.
374 	 * Need to do this early enough that we can still sleep.
375 	 *
376 	 * The last exiting process to reach this point releases as
377 	 * much of the environment as it can. vmspace_dofree() is the
378 	 * slower fallback in case another process had a temporary
379 	 * reference to the vmspace.
380 	 */
381 
382 	p = td->td_proc;
383 	vm = p->p_vmspace;
384 	atomic_add_int(&vmspace0.vm_refcnt, 1);
385 	do {
386 		refcnt = vm->vm_refcnt;
387 		if (refcnt > 1 && p->p_vmspace != &vmspace0) {
388 			/* Switch now since other proc might free vmspace */
389 			PROC_VMSPACE_LOCK(p);
390 			p->p_vmspace = &vmspace0;
391 			PROC_VMSPACE_UNLOCK(p);
392 			pmap_activate(td);
393 		}
394 	} while (!atomic_cmpset_int(&vm->vm_refcnt, refcnt, refcnt - 1));
395 	if (refcnt == 1) {
396 		if (p->p_vmspace != vm) {
397 			/* vmspace not yet freed, switch back */
398 			PROC_VMSPACE_LOCK(p);
399 			p->p_vmspace = vm;
400 			PROC_VMSPACE_UNLOCK(p);
401 			pmap_activate(td);
402 		}
403 		pmap_remove_pages(vmspace_pmap(vm));
404 		/* Switch now since this proc will free vmspace */
405 		PROC_VMSPACE_LOCK(p);
406 		p->p_vmspace = &vmspace0;
407 		PROC_VMSPACE_UNLOCK(p);
408 		pmap_activate(td);
409 		vmspace_dofree(vm);
410 	}
411 	vmspace_container_reset(p);
412 }
413 
414 /* Acquire reference to vmspace owned by another process. */
415 
416 struct vmspace *
417 vmspace_acquire_ref(struct proc *p)
418 {
419 	struct vmspace *vm;
420 	int refcnt;
421 
422 	PROC_VMSPACE_LOCK(p);
423 	vm = p->p_vmspace;
424 	if (vm == NULL) {
425 		PROC_VMSPACE_UNLOCK(p);
426 		return (NULL);
427 	}
428 	do {
429 		refcnt = vm->vm_refcnt;
430 		if (refcnt <= 0) { 	/* Avoid 0->1 transition */
431 			PROC_VMSPACE_UNLOCK(p);
432 			return (NULL);
433 		}
434 	} while (!atomic_cmpset_int(&vm->vm_refcnt, refcnt, refcnt + 1));
435 	if (vm != p->p_vmspace) {
436 		PROC_VMSPACE_UNLOCK(p);
437 		vmspace_free(vm);
438 		return (NULL);
439 	}
440 	PROC_VMSPACE_UNLOCK(p);
441 	return (vm);
442 }
443 
444 void
445 _vm_map_lock(vm_map_t map, const char *file, int line)
446 {
447 
448 	if (map->system_map)
449 		mtx_lock_flags_(&map->system_mtx, 0, file, line);
450 	else
451 		sx_xlock_(&map->lock, file, line);
452 	map->timestamp++;
453 }
454 
455 static void
456 vm_map_process_deferred(void)
457 {
458 	struct thread *td;
459 	vm_map_entry_t entry, next;
460 	vm_object_t object;
461 
462 	td = curthread;
463 	entry = td->td_map_def_user;
464 	td->td_map_def_user = NULL;
465 	while (entry != NULL) {
466 		next = entry->next;
467 		if ((entry->eflags & MAP_ENTRY_VN_WRITECNT) != 0) {
468 			/*
469 			 * Decrement the object's writemappings and
470 			 * possibly the vnode's v_writecount.
471 			 */
472 			KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
473 			    ("Submap with writecount"));
474 			object = entry->object.vm_object;
475 			KASSERT(object != NULL, ("No object for writecount"));
476 			vnode_pager_release_writecount(object, entry->start,
477 			    entry->end);
478 		}
479 		vm_map_entry_deallocate(entry, FALSE);
480 		entry = next;
481 	}
482 }
483 
484 void
485 _vm_map_unlock(vm_map_t map, const char *file, int line)
486 {
487 
488 	if (map->system_map)
489 		mtx_unlock_flags_(&map->system_mtx, 0, file, line);
490 	else {
491 		sx_xunlock_(&map->lock, file, line);
492 		vm_map_process_deferred();
493 	}
494 }
495 
496 void
497 _vm_map_lock_read(vm_map_t map, const char *file, int line)
498 {
499 
500 	if (map->system_map)
501 		mtx_lock_flags_(&map->system_mtx, 0, file, line);
502 	else
503 		sx_slock_(&map->lock, file, line);
504 }
505 
506 void
507 _vm_map_unlock_read(vm_map_t map, const char *file, int line)
508 {
509 
510 	if (map->system_map)
511 		mtx_unlock_flags_(&map->system_mtx, 0, file, line);
512 	else {
513 		sx_sunlock_(&map->lock, file, line);
514 		vm_map_process_deferred();
515 	}
516 }
517 
518 int
519 _vm_map_trylock(vm_map_t map, const char *file, int line)
520 {
521 	int error;
522 
523 	error = map->system_map ?
524 	    !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
525 	    !sx_try_xlock_(&map->lock, file, line);
526 	if (error == 0)
527 		map->timestamp++;
528 	return (error == 0);
529 }
530 
531 int
532 _vm_map_trylock_read(vm_map_t map, const char *file, int line)
533 {
534 	int error;
535 
536 	error = map->system_map ?
537 	    !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
538 	    !sx_try_slock_(&map->lock, file, line);
539 	return (error == 0);
540 }
541 
542 /*
543  *	_vm_map_lock_upgrade:	[ internal use only ]
544  *
545  *	Tries to upgrade a read (shared) lock on the specified map to a write
546  *	(exclusive) lock.  Returns the value "0" if the upgrade succeeds and a
547  *	non-zero value if the upgrade fails.  If the upgrade fails, the map is
548  *	returned without a read or write lock held.
549  *
550  *	Requires that the map be read locked.
551  */
552 int
553 _vm_map_lock_upgrade(vm_map_t map, const char *file, int line)
554 {
555 	unsigned int last_timestamp;
556 
557 	if (map->system_map) {
558 		mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
559 	} else {
560 		if (!sx_try_upgrade_(&map->lock, file, line)) {
561 			last_timestamp = map->timestamp;
562 			sx_sunlock_(&map->lock, file, line);
563 			vm_map_process_deferred();
564 			/*
565 			 * If the map's timestamp does not change while the
566 			 * map is unlocked, then the upgrade succeeds.
567 			 */
568 			sx_xlock_(&map->lock, file, line);
569 			if (last_timestamp != map->timestamp) {
570 				sx_xunlock_(&map->lock, file, line);
571 				return (1);
572 			}
573 		}
574 	}
575 	map->timestamp++;
576 	return (0);
577 }
578 
579 void
580 _vm_map_lock_downgrade(vm_map_t map, const char *file, int line)
581 {
582 
583 	if (map->system_map) {
584 		mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
585 	} else
586 		sx_downgrade_(&map->lock, file, line);
587 }
588 
589 /*
590  *	vm_map_locked:
591  *
592  *	Returns a non-zero value if the caller holds a write (exclusive) lock
593  *	on the specified map and the value "0" otherwise.
594  */
595 int
596 vm_map_locked(vm_map_t map)
597 {
598 
599 	if (map->system_map)
600 		return (mtx_owned(&map->system_mtx));
601 	else
602 		return (sx_xlocked(&map->lock));
603 }
604 
605 #ifdef INVARIANTS
606 static void
607 _vm_map_assert_locked(vm_map_t map, const char *file, int line)
608 {
609 
610 	if (map->system_map)
611 		mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
612 	else
613 		sx_assert_(&map->lock, SA_XLOCKED, file, line);
614 }
615 
616 #define	VM_MAP_ASSERT_LOCKED(map) \
617     _vm_map_assert_locked(map, LOCK_FILE, LOCK_LINE)
618 #else
619 #define	VM_MAP_ASSERT_LOCKED(map)
620 #endif
621 
622 /*
623  *	_vm_map_unlock_and_wait:
624  *
625  *	Atomically releases the lock on the specified map and puts the calling
626  *	thread to sleep.  The calling thread will remain asleep until either
627  *	vm_map_wakeup() is performed on the map or the specified timeout is
628  *	exceeded.
629  *
630  *	WARNING!  This function does not perform deferred deallocations of
631  *	objects and map	entries.  Therefore, the calling thread is expected to
632  *	reacquire the map lock after reawakening and later perform an ordinary
633  *	unlock operation, such as vm_map_unlock(), before completing its
634  *	operation on the map.
635  */
636 int
637 _vm_map_unlock_and_wait(vm_map_t map, int timo, const char *file, int line)
638 {
639 
640 	mtx_lock(&map_sleep_mtx);
641 	if (map->system_map)
642 		mtx_unlock_flags_(&map->system_mtx, 0, file, line);
643 	else
644 		sx_xunlock_(&map->lock, file, line);
645 	return (msleep(&map->root, &map_sleep_mtx, PDROP | PVM, "vmmaps",
646 	    timo));
647 }
648 
649 /*
650  *	vm_map_wakeup:
651  *
652  *	Awaken any threads that have slept on the map using
653  *	vm_map_unlock_and_wait().
654  */
655 void
656 vm_map_wakeup(vm_map_t map)
657 {
658 
659 	/*
660 	 * Acquire and release map_sleep_mtx to prevent a wakeup()
661 	 * from being performed (and lost) between the map unlock
662 	 * and the msleep() in _vm_map_unlock_and_wait().
663 	 */
664 	mtx_lock(&map_sleep_mtx);
665 	mtx_unlock(&map_sleep_mtx);
666 	wakeup(&map->root);
667 }
668 
669 void
670 vm_map_busy(vm_map_t map)
671 {
672 
673 	VM_MAP_ASSERT_LOCKED(map);
674 	map->busy++;
675 }
676 
677 void
678 vm_map_unbusy(vm_map_t map)
679 {
680 
681 	VM_MAP_ASSERT_LOCKED(map);
682 	KASSERT(map->busy, ("vm_map_unbusy: not busy"));
683 	if (--map->busy == 0 && (map->flags & MAP_BUSY_WAKEUP)) {
684 		vm_map_modflags(map, 0, MAP_BUSY_WAKEUP);
685 		wakeup(&map->busy);
686 	}
687 }
688 
689 void
690 vm_map_wait_busy(vm_map_t map)
691 {
692 
693 	VM_MAP_ASSERT_LOCKED(map);
694 	while (map->busy) {
695 		vm_map_modflags(map, MAP_BUSY_WAKEUP, 0);
696 		if (map->system_map)
697 			msleep(&map->busy, &map->system_mtx, 0, "mbusy", 0);
698 		else
699 			sx_sleep(&map->busy, &map->lock, 0, "mbusy", 0);
700 	}
701 	map->timestamp++;
702 }
703 
704 long
705 vmspace_resident_count(struct vmspace *vmspace)
706 {
707 	return pmap_resident_count(vmspace_pmap(vmspace));
708 }
709 
710 /*
711  *	vm_map_create:
712  *
713  *	Creates and returns a new empty VM map with
714  *	the given physical map structure, and having
715  *	the given lower and upper address bounds.
716  */
717 vm_map_t
718 vm_map_create(pmap_t pmap, vm_offset_t min, vm_offset_t max)
719 {
720 	vm_map_t result;
721 
722 	result = uma_zalloc(mapzone, M_WAITOK);
723 	CTR1(KTR_VM, "vm_map_create: %p", result);
724 	_vm_map_init(result, pmap, min, max);
725 	return (result);
726 }
727 
728 /*
729  * Initialize an existing vm_map structure
730  * such as that in the vmspace structure.
731  */
732 static void
733 _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
734 {
735 
736 	map->header.next = map->header.prev = &map->header;
737 	map->needs_wakeup = FALSE;
738 	map->system_map = 0;
739 	map->pmap = pmap;
740 	map->min_offset = min;
741 	map->max_offset = max;
742 	map->flags = 0;
743 	map->root = NULL;
744 	map->timestamp = 0;
745 	map->busy = 0;
746 }
747 
748 void
749 vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
750 {
751 
752 	_vm_map_init(map, pmap, min, max);
753 	mtx_init(&map->system_mtx, "system map", NULL, MTX_DEF | MTX_DUPOK);
754 	sx_init(&map->lock, "user map");
755 }
756 
757 /*
758  *	vm_map_entry_dispose:	[ internal use only ]
759  *
760  *	Inverse of vm_map_entry_create.
761  */
762 static void
763 vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry)
764 {
765 	uma_zfree(map->system_map ? kmapentzone : mapentzone, entry);
766 }
767 
768 /*
769  *	vm_map_entry_create:	[ internal use only ]
770  *
771  *	Allocates a VM map entry for insertion.
772  *	No entry fields are filled in.
773  */
774 static vm_map_entry_t
775 vm_map_entry_create(vm_map_t map)
776 {
777 	vm_map_entry_t new_entry;
778 
779 	if (map->system_map)
780 		new_entry = uma_zalloc(kmapentzone, M_NOWAIT);
781 	else
782 		new_entry = uma_zalloc(mapentzone, M_WAITOK);
783 	if (new_entry == NULL)
784 		panic("vm_map_entry_create: kernel resources exhausted");
785 	return (new_entry);
786 }
787 
788 /*
789  *	vm_map_entry_set_behavior:
790  *
791  *	Set the expected access behavior, either normal, random, or
792  *	sequential.
793  */
794 static inline void
795 vm_map_entry_set_behavior(vm_map_entry_t entry, u_char behavior)
796 {
797 	entry->eflags = (entry->eflags & ~MAP_ENTRY_BEHAV_MASK) |
798 	    (behavior & MAP_ENTRY_BEHAV_MASK);
799 }
800 
801 /*
802  *	vm_map_entry_set_max_free:
803  *
804  *	Set the max_free field in a vm_map_entry.
805  */
806 static inline void
807 vm_map_entry_set_max_free(vm_map_entry_t entry)
808 {
809 
810 	entry->max_free = entry->adj_free;
811 	if (entry->left != NULL && entry->left->max_free > entry->max_free)
812 		entry->max_free = entry->left->max_free;
813 	if (entry->right != NULL && entry->right->max_free > entry->max_free)
814 		entry->max_free = entry->right->max_free;
815 }
816 
817 /*
818  *	vm_map_entry_splay:
819  *
820  *	The Sleator and Tarjan top-down splay algorithm with the
821  *	following variation.  Max_free must be computed bottom-up, so
822  *	on the downward pass, maintain the left and right spines in
823  *	reverse order.  Then, make a second pass up each side to fix
824  *	the pointers and compute max_free.  The time bound is O(log n)
825  *	amortized.
826  *
827  *	The new root is the vm_map_entry containing "addr", or else an
828  *	adjacent entry (lower or higher) if addr is not in the tree.
829  *
830  *	The map must be locked, and leaves it so.
831  *
832  *	Returns: the new root.
833  */
834 static vm_map_entry_t
835 vm_map_entry_splay(vm_offset_t addr, vm_map_entry_t root)
836 {
837 	vm_map_entry_t llist, rlist;
838 	vm_map_entry_t ltree, rtree;
839 	vm_map_entry_t y;
840 
841 	/* Special case of empty tree. */
842 	if (root == NULL)
843 		return (root);
844 
845 	/*
846 	 * Pass One: Splay down the tree until we find addr or a NULL
847 	 * pointer where addr would go.  llist and rlist are the two
848 	 * sides in reverse order (bottom-up), with llist linked by
849 	 * the right pointer and rlist linked by the left pointer in
850 	 * the vm_map_entry.  Wait until Pass Two to set max_free on
851 	 * the two spines.
852 	 */
853 	llist = NULL;
854 	rlist = NULL;
855 	for (;;) {
856 		/* root is never NULL in here. */
857 		if (addr < root->start) {
858 			y = root->left;
859 			if (y == NULL)
860 				break;
861 			if (addr < y->start && y->left != NULL) {
862 				/* Rotate right and put y on rlist. */
863 				root->left = y->right;
864 				y->right = root;
865 				vm_map_entry_set_max_free(root);
866 				root = y->left;
867 				y->left = rlist;
868 				rlist = y;
869 			} else {
870 				/* Put root on rlist. */
871 				root->left = rlist;
872 				rlist = root;
873 				root = y;
874 			}
875 		} else if (addr >= root->end) {
876 			y = root->right;
877 			if (y == NULL)
878 				break;
879 			if (addr >= y->end && y->right != NULL) {
880 				/* Rotate left and put y on llist. */
881 				root->right = y->left;
882 				y->left = root;
883 				vm_map_entry_set_max_free(root);
884 				root = y->right;
885 				y->right = llist;
886 				llist = y;
887 			} else {
888 				/* Put root on llist. */
889 				root->right = llist;
890 				llist = root;
891 				root = y;
892 			}
893 		} else
894 			break;
895 	}
896 
897 	/*
898 	 * Pass Two: Walk back up the two spines, flip the pointers
899 	 * and set max_free.  The subtrees of the root go at the
900 	 * bottom of llist and rlist.
901 	 */
902 	ltree = root->left;
903 	while (llist != NULL) {
904 		y = llist->right;
905 		llist->right = ltree;
906 		vm_map_entry_set_max_free(llist);
907 		ltree = llist;
908 		llist = y;
909 	}
910 	rtree = root->right;
911 	while (rlist != NULL) {
912 		y = rlist->left;
913 		rlist->left = rtree;
914 		vm_map_entry_set_max_free(rlist);
915 		rtree = rlist;
916 		rlist = y;
917 	}
918 
919 	/*
920 	 * Final assembly: add ltree and rtree as subtrees of root.
921 	 */
922 	root->left = ltree;
923 	root->right = rtree;
924 	vm_map_entry_set_max_free(root);
925 
926 	return (root);
927 }
928 
929 /*
930  *	vm_map_entry_{un,}link:
931  *
932  *	Insert/remove entries from maps.
933  */
934 static void
935 vm_map_entry_link(vm_map_t map,
936 		  vm_map_entry_t after_where,
937 		  vm_map_entry_t entry)
938 {
939 
940 	CTR4(KTR_VM,
941 	    "vm_map_entry_link: map %p, nentries %d, entry %p, after %p", map,
942 	    map->nentries, entry, after_where);
943 	VM_MAP_ASSERT_LOCKED(map);
944 	KASSERT(after_where == &map->header ||
945 	    after_where->end <= entry->start,
946 	    ("vm_map_entry_link: prev end %jx new start %jx overlap",
947 	    (uintmax_t)after_where->end, (uintmax_t)entry->start));
948 	KASSERT(after_where->next == &map->header ||
949 	    entry->end <= after_where->next->start,
950 	    ("vm_map_entry_link: new end %jx next start %jx overlap",
951 	    (uintmax_t)entry->end, (uintmax_t)after_where->next->start));
952 
953 	map->nentries++;
954 	entry->prev = after_where;
955 	entry->next = after_where->next;
956 	entry->next->prev = entry;
957 	after_where->next = entry;
958 
959 	if (after_where != &map->header) {
960 		if (after_where != map->root)
961 			vm_map_entry_splay(after_where->start, map->root);
962 		entry->right = after_where->right;
963 		entry->left = after_where;
964 		after_where->right = NULL;
965 		after_where->adj_free = entry->start - after_where->end;
966 		vm_map_entry_set_max_free(after_where);
967 	} else {
968 		entry->right = map->root;
969 		entry->left = NULL;
970 	}
971 	entry->adj_free = (entry->next == &map->header ? map->max_offset :
972 	    entry->next->start) - entry->end;
973 	vm_map_entry_set_max_free(entry);
974 	map->root = entry;
975 }
976 
977 static void
978 vm_map_entry_unlink(vm_map_t map,
979 		    vm_map_entry_t entry)
980 {
981 	vm_map_entry_t next, prev, root;
982 
983 	VM_MAP_ASSERT_LOCKED(map);
984 	if (entry != map->root)
985 		vm_map_entry_splay(entry->start, map->root);
986 	if (entry->left == NULL)
987 		root = entry->right;
988 	else {
989 		root = vm_map_entry_splay(entry->start, entry->left);
990 		root->right = entry->right;
991 		root->adj_free = (entry->next == &map->header ? map->max_offset :
992 		    entry->next->start) - root->end;
993 		vm_map_entry_set_max_free(root);
994 	}
995 	map->root = root;
996 
997 	prev = entry->prev;
998 	next = entry->next;
999 	next->prev = prev;
1000 	prev->next = next;
1001 	map->nentries--;
1002 	CTR3(KTR_VM, "vm_map_entry_unlink: map %p, nentries %d, entry %p", map,
1003 	    map->nentries, entry);
1004 }
1005 
1006 /*
1007  *	vm_map_entry_resize_free:
1008  *
1009  *	Recompute the amount of free space following a vm_map_entry
1010  *	and propagate that value up the tree.  Call this function after
1011  *	resizing a map entry in-place, that is, without a call to
1012  *	vm_map_entry_link() or _unlink().
1013  *
1014  *	The map must be locked, and leaves it so.
1015  */
1016 static void
1017 vm_map_entry_resize_free(vm_map_t map, vm_map_entry_t entry)
1018 {
1019 
1020 	/*
1021 	 * Using splay trees without parent pointers, propagating
1022 	 * max_free up the tree is done by moving the entry to the
1023 	 * root and making the change there.
1024 	 */
1025 	if (entry != map->root)
1026 		map->root = vm_map_entry_splay(entry->start, map->root);
1027 
1028 	entry->adj_free = (entry->next == &map->header ? map->max_offset :
1029 	    entry->next->start) - entry->end;
1030 	vm_map_entry_set_max_free(entry);
1031 }
1032 
1033 /*
1034  *	vm_map_lookup_entry:	[ internal use only ]
1035  *
1036  *	Finds the map entry containing (or
1037  *	immediately preceding) the specified address
1038  *	in the given map; the entry is returned
1039  *	in the "entry" parameter.  The boolean
1040  *	result indicates whether the address is
1041  *	actually contained in the map.
1042  */
1043 boolean_t
1044 vm_map_lookup_entry(
1045 	vm_map_t map,
1046 	vm_offset_t address,
1047 	vm_map_entry_t *entry)	/* OUT */
1048 {
1049 	vm_map_entry_t cur;
1050 	boolean_t locked;
1051 
1052 	/*
1053 	 * If the map is empty, then the map entry immediately preceding
1054 	 * "address" is the map's header.
1055 	 */
1056 	cur = map->root;
1057 	if (cur == NULL)
1058 		*entry = &map->header;
1059 	else if (address >= cur->start && cur->end > address) {
1060 		*entry = cur;
1061 		return (TRUE);
1062 	} else if ((locked = vm_map_locked(map)) ||
1063 	    sx_try_upgrade(&map->lock)) {
1064 		/*
1065 		 * Splay requires a write lock on the map.  However, it only
1066 		 * restructures the binary search tree; it does not otherwise
1067 		 * change the map.  Thus, the map's timestamp need not change
1068 		 * on a temporary upgrade.
1069 		 */
1070 		map->root = cur = vm_map_entry_splay(address, cur);
1071 		if (!locked)
1072 			sx_downgrade(&map->lock);
1073 
1074 		/*
1075 		 * If "address" is contained within a map entry, the new root
1076 		 * is that map entry.  Otherwise, the new root is a map entry
1077 		 * immediately before or after "address".
1078 		 */
1079 		if (address >= cur->start) {
1080 			*entry = cur;
1081 			if (cur->end > address)
1082 				return (TRUE);
1083 		} else
1084 			*entry = cur->prev;
1085 	} else
1086 		/*
1087 		 * Since the map is only locked for read access, perform a
1088 		 * standard binary search tree lookup for "address".
1089 		 */
1090 		for (;;) {
1091 			if (address < cur->start) {
1092 				if (cur->left == NULL) {
1093 					*entry = cur->prev;
1094 					break;
1095 				}
1096 				cur = cur->left;
1097 			} else if (cur->end > address) {
1098 				*entry = cur;
1099 				return (TRUE);
1100 			} else {
1101 				if (cur->right == NULL) {
1102 					*entry = cur;
1103 					break;
1104 				}
1105 				cur = cur->right;
1106 			}
1107 		}
1108 	return (FALSE);
1109 }
1110 
1111 /*
1112  *	vm_map_insert:
1113  *
1114  *	Inserts the given whole VM object into the target
1115  *	map at the specified address range.  The object's
1116  *	size should match that of the address range.
1117  *
1118  *	Requires that the map be locked, and leaves it so.
1119  *
1120  *	If object is non-NULL, ref count must be bumped by caller
1121  *	prior to making call to account for the new entry.
1122  */
1123 int
1124 vm_map_insert(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1125     vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max, int cow)
1126 {
1127 	vm_map_entry_t new_entry, prev_entry, temp_entry;
1128 	vm_eflags_t protoeflags;
1129 	struct ucred *cred;
1130 	vm_inherit_t inheritance;
1131 
1132 	VM_MAP_ASSERT_LOCKED(map);
1133 	KASSERT((object != kmem_object && object != kernel_object) ||
1134 	    (cow & MAP_COPY_ON_WRITE) == 0,
1135 	    ("vm_map_insert: kmem or kernel object and COW"));
1136 	KASSERT(object == NULL || (cow & MAP_NOFAULT) == 0,
1137 	    ("vm_map_insert: paradoxical MAP_NOFAULT request"));
1138 
1139 	/*
1140 	 * Check that the start and end points are not bogus.
1141 	 */
1142 	if ((start < map->min_offset) || (end > map->max_offset) ||
1143 	    (start >= end))
1144 		return (KERN_INVALID_ADDRESS);
1145 
1146 	/*
1147 	 * Find the entry prior to the proposed starting address; if it's part
1148 	 * of an existing entry, this range is bogus.
1149 	 */
1150 	if (vm_map_lookup_entry(map, start, &temp_entry))
1151 		return (KERN_NO_SPACE);
1152 
1153 	prev_entry = temp_entry;
1154 
1155 	/*
1156 	 * Assert that the next entry doesn't overlap the end point.
1157 	 */
1158 	if ((prev_entry->next != &map->header) &&
1159 	    (prev_entry->next->start < end))
1160 		return (KERN_NO_SPACE);
1161 
1162 	protoeflags = 0;
1163 	if (cow & MAP_COPY_ON_WRITE)
1164 		protoeflags |= MAP_ENTRY_COW | MAP_ENTRY_NEEDS_COPY;
1165 	if (cow & MAP_NOFAULT)
1166 		protoeflags |= MAP_ENTRY_NOFAULT;
1167 	if (cow & MAP_DISABLE_SYNCER)
1168 		protoeflags |= MAP_ENTRY_NOSYNC;
1169 	if (cow & MAP_DISABLE_COREDUMP)
1170 		protoeflags |= MAP_ENTRY_NOCOREDUMP;
1171 	if (cow & MAP_STACK_GROWS_DOWN)
1172 		protoeflags |= MAP_ENTRY_GROWS_DOWN;
1173 	if (cow & MAP_STACK_GROWS_UP)
1174 		protoeflags |= MAP_ENTRY_GROWS_UP;
1175 	if (cow & MAP_VN_WRITECOUNT)
1176 		protoeflags |= MAP_ENTRY_VN_WRITECNT;
1177 	if (cow & MAP_INHERIT_SHARE)
1178 		inheritance = VM_INHERIT_SHARE;
1179 	else
1180 		inheritance = VM_INHERIT_DEFAULT;
1181 
1182 	cred = NULL;
1183 	if (cow & (MAP_ACC_NO_CHARGE | MAP_NOFAULT))
1184 		goto charged;
1185 	if ((cow & MAP_ACC_CHARGED) || ((prot & VM_PROT_WRITE) &&
1186 	    ((protoeflags & MAP_ENTRY_NEEDS_COPY) || object == NULL))) {
1187 		if (!(cow & MAP_ACC_CHARGED) && !swap_reserve(end - start))
1188 			return (KERN_RESOURCE_SHORTAGE);
1189 		KASSERT(object == NULL || (protoeflags & MAP_ENTRY_NEEDS_COPY) ||
1190 		    object->cred == NULL,
1191 		    ("OVERCOMMIT: vm_map_insert o %p", object));
1192 		cred = curthread->td_ucred;
1193 	}
1194 
1195 charged:
1196 	/* Expand the kernel pmap, if necessary. */
1197 	if (map == kernel_map && end > kernel_vm_end)
1198 		pmap_growkernel(end);
1199 	if (object != NULL) {
1200 		/*
1201 		 * OBJ_ONEMAPPING must be cleared unless this mapping
1202 		 * is trivially proven to be the only mapping for any
1203 		 * of the object's pages.  (Object granularity
1204 		 * reference counting is insufficient to recognize
1205 		 * aliases with precision.)
1206 		 */
1207 		VM_OBJECT_WLOCK(object);
1208 		if (object->ref_count > 1 || object->shadow_count != 0)
1209 			vm_object_clear_flag(object, OBJ_ONEMAPPING);
1210 		VM_OBJECT_WUNLOCK(object);
1211 	}
1212 	else if ((prev_entry != &map->header) &&
1213 		 (prev_entry->eflags == protoeflags) &&
1214 		 (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 &&
1215 		 (prev_entry->end == start) &&
1216 		 (prev_entry->wired_count == 0) &&
1217 		 (prev_entry->cred == cred ||
1218 		  (prev_entry->object.vm_object != NULL &&
1219 		   (prev_entry->object.vm_object->cred == cred))) &&
1220 		   vm_object_coalesce(prev_entry->object.vm_object,
1221 		       prev_entry->offset,
1222 		       (vm_size_t)(prev_entry->end - prev_entry->start),
1223 		       (vm_size_t)(end - prev_entry->end), cred != NULL &&
1224 		       (protoeflags & MAP_ENTRY_NEEDS_COPY) == 0)) {
1225 		/*
1226 		 * We were able to extend the object.  Determine if we
1227 		 * can extend the previous map entry to include the
1228 		 * new range as well.
1229 		 */
1230 		if ((prev_entry->inheritance == inheritance) &&
1231 		    (prev_entry->protection == prot) &&
1232 		    (prev_entry->max_protection == max)) {
1233 			map->size += (end - prev_entry->end);
1234 			prev_entry->end = end;
1235 			vm_map_entry_resize_free(map, prev_entry);
1236 			vm_map_simplify_entry(map, prev_entry);
1237 			return (KERN_SUCCESS);
1238 		}
1239 
1240 		/*
1241 		 * If we can extend the object but cannot extend the
1242 		 * map entry, we have to create a new map entry.  We
1243 		 * must bump the ref count on the extended object to
1244 		 * account for it.  object may be NULL.
1245 		 */
1246 		object = prev_entry->object.vm_object;
1247 		offset = prev_entry->offset +
1248 			(prev_entry->end - prev_entry->start);
1249 		vm_object_reference(object);
1250 		if (cred != NULL && object != NULL && object->cred != NULL &&
1251 		    !(prev_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
1252 			/* Object already accounts for this uid. */
1253 			cred = NULL;
1254 		}
1255 	}
1256 	if (cred != NULL)
1257 		crhold(cred);
1258 
1259 	/*
1260 	 * Create a new entry
1261 	 */
1262 	new_entry = vm_map_entry_create(map);
1263 	new_entry->start = start;
1264 	new_entry->end = end;
1265 	new_entry->cred = NULL;
1266 
1267 	new_entry->eflags = protoeflags;
1268 	new_entry->object.vm_object = object;
1269 	new_entry->offset = offset;
1270 	new_entry->avail_ssize = 0;
1271 
1272 	new_entry->inheritance = inheritance;
1273 	new_entry->protection = prot;
1274 	new_entry->max_protection = max;
1275 	new_entry->wired_count = 0;
1276 	new_entry->wiring_thread = NULL;
1277 	new_entry->read_ahead = VM_FAULT_READ_AHEAD_INIT;
1278 	new_entry->next_read = OFF_TO_IDX(offset);
1279 
1280 	KASSERT(cred == NULL || !ENTRY_CHARGED(new_entry),
1281 	    ("OVERCOMMIT: vm_map_insert leaks vm_map %p", new_entry));
1282 	new_entry->cred = cred;
1283 
1284 	/*
1285 	 * Insert the new entry into the list
1286 	 */
1287 	vm_map_entry_link(map, prev_entry, new_entry);
1288 	map->size += new_entry->end - new_entry->start;
1289 
1290 	/*
1291 	 * Try to coalesce the new entry with both the previous and next
1292 	 * entries in the list.  Previously, we only attempted to coalesce
1293 	 * with the previous entry when object is NULL.  Here, we handle the
1294 	 * other cases, which are less common.
1295 	 */
1296 	vm_map_simplify_entry(map, new_entry);
1297 
1298 	if (cow & (MAP_PREFAULT|MAP_PREFAULT_PARTIAL)) {
1299 		vm_map_pmap_enter(map, start, prot,
1300 				    object, OFF_TO_IDX(offset), end - start,
1301 				    cow & MAP_PREFAULT_PARTIAL);
1302 	}
1303 
1304 	return (KERN_SUCCESS);
1305 }
1306 
1307 /*
1308  *	vm_map_findspace:
1309  *
1310  *	Find the first fit (lowest VM address) for "length" free bytes
1311  *	beginning at address >= start in the given map.
1312  *
1313  *	In a vm_map_entry, "adj_free" is the amount of free space
1314  *	adjacent (higher address) to this entry, and "max_free" is the
1315  *	maximum amount of contiguous free space in its subtree.  This
1316  *	allows finding a free region in one path down the tree, so
1317  *	O(log n) amortized with splay trees.
1318  *
1319  *	The map must be locked, and leaves it so.
1320  *
1321  *	Returns: 0 on success, and starting address in *addr,
1322  *		 1 if insufficient space.
1323  */
1324 int
1325 vm_map_findspace(vm_map_t map, vm_offset_t start, vm_size_t length,
1326     vm_offset_t *addr)	/* OUT */
1327 {
1328 	vm_map_entry_t entry;
1329 	vm_offset_t st;
1330 
1331 	/*
1332 	 * Request must fit within min/max VM address and must avoid
1333 	 * address wrap.
1334 	 */
1335 	if (start < map->min_offset)
1336 		start = map->min_offset;
1337 	if (start + length > map->max_offset || start + length < start)
1338 		return (1);
1339 
1340 	/* Empty tree means wide open address space. */
1341 	if (map->root == NULL) {
1342 		*addr = start;
1343 		return (0);
1344 	}
1345 
1346 	/*
1347 	 * After splay, if start comes before root node, then there
1348 	 * must be a gap from start to the root.
1349 	 */
1350 	map->root = vm_map_entry_splay(start, map->root);
1351 	if (start + length <= map->root->start) {
1352 		*addr = start;
1353 		return (0);
1354 	}
1355 
1356 	/*
1357 	 * Root is the last node that might begin its gap before
1358 	 * start, and this is the last comparison where address
1359 	 * wrap might be a problem.
1360 	 */
1361 	st = (start > map->root->end) ? start : map->root->end;
1362 	if (length <= map->root->end + map->root->adj_free - st) {
1363 		*addr = st;
1364 		return (0);
1365 	}
1366 
1367 	/* With max_free, can immediately tell if no solution. */
1368 	entry = map->root->right;
1369 	if (entry == NULL || length > entry->max_free)
1370 		return (1);
1371 
1372 	/*
1373 	 * Search the right subtree in the order: left subtree, root,
1374 	 * right subtree (first fit).  The previous splay implies that
1375 	 * all regions in the right subtree have addresses > start.
1376 	 */
1377 	while (entry != NULL) {
1378 		if (entry->left != NULL && entry->left->max_free >= length)
1379 			entry = entry->left;
1380 		else if (entry->adj_free >= length) {
1381 			*addr = entry->end;
1382 			return (0);
1383 		} else
1384 			entry = entry->right;
1385 	}
1386 
1387 	/* Can't get here, so panic if we do. */
1388 	panic("vm_map_findspace: max_free corrupt");
1389 }
1390 
1391 int
1392 vm_map_fixed(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1393     vm_offset_t start, vm_size_t length, vm_prot_t prot,
1394     vm_prot_t max, int cow)
1395 {
1396 	vm_offset_t end;
1397 	int result;
1398 
1399 	end = start + length;
1400 	KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
1401 	    object == NULL,
1402 	    ("vm_map_fixed: non-NULL backing object for stack"));
1403 	vm_map_lock(map);
1404 	VM_MAP_RANGE_CHECK(map, start, end);
1405 	if ((cow & MAP_CHECK_EXCL) == 0)
1406 		vm_map_delete(map, start, end);
1407 	if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
1408 		result = vm_map_stack_locked(map, start, length, sgrowsiz,
1409 		    prot, max, cow);
1410 	} else {
1411 		result = vm_map_insert(map, object, offset, start, end,
1412 		    prot, max, cow);
1413 	}
1414 	vm_map_unlock(map);
1415 	return (result);
1416 }
1417 
1418 /*
1419  *	vm_map_find finds an unallocated region in the target address
1420  *	map with the given length.  The search is defined to be
1421  *	first-fit from the specified address; the region found is
1422  *	returned in the same parameter.
1423  *
1424  *	If object is non-NULL, ref count must be bumped by caller
1425  *	prior to making call to account for the new entry.
1426  */
1427 int
1428 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1429 	    vm_offset_t *addr,	/* IN/OUT */
1430 	    vm_size_t length, vm_offset_t max_addr, int find_space,
1431 	    vm_prot_t prot, vm_prot_t max, int cow)
1432 {
1433 	vm_offset_t alignment, initial_addr, start;
1434 	int result;
1435 
1436 	KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
1437 	    object == NULL,
1438 	    ("vm_map_find: non-NULL backing object for stack"));
1439 	if (find_space == VMFS_OPTIMAL_SPACE && (object == NULL ||
1440 	    (object->flags & OBJ_COLORED) == 0))
1441 		find_space = VMFS_ANY_SPACE;
1442 	if (find_space >> 8 != 0) {
1443 		KASSERT((find_space & 0xff) == 0, ("bad VMFS flags"));
1444 		alignment = (vm_offset_t)1 << (find_space >> 8);
1445 	} else
1446 		alignment = 0;
1447 	initial_addr = *addr;
1448 again:
1449 	start = initial_addr;
1450 	vm_map_lock(map);
1451 	do {
1452 		if (find_space != VMFS_NO_SPACE) {
1453 			if (vm_map_findspace(map, start, length, addr) ||
1454 			    (max_addr != 0 && *addr + length > max_addr)) {
1455 				vm_map_unlock(map);
1456 				if (find_space == VMFS_OPTIMAL_SPACE) {
1457 					find_space = VMFS_ANY_SPACE;
1458 					goto again;
1459 				}
1460 				return (KERN_NO_SPACE);
1461 			}
1462 			switch (find_space) {
1463 			case VMFS_SUPER_SPACE:
1464 			case VMFS_OPTIMAL_SPACE:
1465 				pmap_align_superpage(object, offset, addr,
1466 				    length);
1467 				break;
1468 			case VMFS_ANY_SPACE:
1469 				break;
1470 			default:
1471 				if ((*addr & (alignment - 1)) != 0) {
1472 					*addr &= ~(alignment - 1);
1473 					*addr += alignment;
1474 				}
1475 				break;
1476 			}
1477 
1478 			start = *addr;
1479 		}
1480 		if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
1481 			result = vm_map_stack_locked(map, start, length,
1482 			    sgrowsiz, prot, max, cow);
1483 		} else {
1484 			result = vm_map_insert(map, object, offset, start,
1485 			    start + length, prot, max, cow);
1486 		}
1487 	} while (result == KERN_NO_SPACE && find_space != VMFS_NO_SPACE &&
1488 	    find_space != VMFS_ANY_SPACE);
1489 	vm_map_unlock(map);
1490 	return (result);
1491 }
1492 
1493 /*
1494  *	vm_map_simplify_entry:
1495  *
1496  *	Simplify the given map entry by merging with either neighbor.  This
1497  *	routine also has the ability to merge with both neighbors.
1498  *
1499  *	The map must be locked.
1500  *
1501  *	This routine guarentees that the passed entry remains valid (though
1502  *	possibly extended).  When merging, this routine may delete one or
1503  *	both neighbors.
1504  */
1505 void
1506 vm_map_simplify_entry(vm_map_t map, vm_map_entry_t entry)
1507 {
1508 	vm_map_entry_t next, prev;
1509 	vm_size_t prevsize, esize;
1510 
1511 	if ((entry->eflags & (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP |
1512 	    MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_IS_SUB_MAP)) != 0)
1513 		return;
1514 
1515 	prev = entry->prev;
1516 	if (prev != &map->header) {
1517 		prevsize = prev->end - prev->start;
1518 		if ( (prev->end == entry->start) &&
1519 		     (prev->object.vm_object == entry->object.vm_object) &&
1520 		     (!prev->object.vm_object ||
1521 			(prev->offset + prevsize == entry->offset)) &&
1522 		     (prev->eflags == entry->eflags) &&
1523 		     (prev->protection == entry->protection) &&
1524 		     (prev->max_protection == entry->max_protection) &&
1525 		     (prev->inheritance == entry->inheritance) &&
1526 		     (prev->wired_count == entry->wired_count) &&
1527 		     (prev->cred == entry->cred)) {
1528 			vm_map_entry_unlink(map, prev);
1529 			entry->start = prev->start;
1530 			entry->offset = prev->offset;
1531 			if (entry->prev != &map->header)
1532 				vm_map_entry_resize_free(map, entry->prev);
1533 
1534 			/*
1535 			 * If the backing object is a vnode object,
1536 			 * vm_object_deallocate() calls vrele().
1537 			 * However, vrele() does not lock the vnode
1538 			 * because the vnode has additional
1539 			 * references.  Thus, the map lock can be kept
1540 			 * without causing a lock-order reversal with
1541 			 * the vnode lock.
1542 			 *
1543 			 * Since we count the number of virtual page
1544 			 * mappings in object->un_pager.vnp.writemappings,
1545 			 * the writemappings value should not be adjusted
1546 			 * when the entry is disposed of.
1547 			 */
1548 			if (prev->object.vm_object)
1549 				vm_object_deallocate(prev->object.vm_object);
1550 			if (prev->cred != NULL)
1551 				crfree(prev->cred);
1552 			vm_map_entry_dispose(map, prev);
1553 		}
1554 	}
1555 
1556 	next = entry->next;
1557 	if (next != &map->header) {
1558 		esize = entry->end - entry->start;
1559 		if ((entry->end == next->start) &&
1560 		    (next->object.vm_object == entry->object.vm_object) &&
1561 		     (!entry->object.vm_object ||
1562 			(entry->offset + esize == next->offset)) &&
1563 		    (next->eflags == entry->eflags) &&
1564 		    (next->protection == entry->protection) &&
1565 		    (next->max_protection == entry->max_protection) &&
1566 		    (next->inheritance == entry->inheritance) &&
1567 		    (next->wired_count == entry->wired_count) &&
1568 		    (next->cred == entry->cred)) {
1569 			vm_map_entry_unlink(map, next);
1570 			entry->end = next->end;
1571 			vm_map_entry_resize_free(map, entry);
1572 
1573 			/*
1574 			 * See comment above.
1575 			 */
1576 			if (next->object.vm_object)
1577 				vm_object_deallocate(next->object.vm_object);
1578 			if (next->cred != NULL)
1579 				crfree(next->cred);
1580 			vm_map_entry_dispose(map, next);
1581 		}
1582 	}
1583 }
1584 /*
1585  *	vm_map_clip_start:	[ internal use only ]
1586  *
1587  *	Asserts that the given entry begins at or after
1588  *	the specified address; if necessary,
1589  *	it splits the entry into two.
1590  */
1591 #define vm_map_clip_start(map, entry, startaddr) \
1592 { \
1593 	if (startaddr > entry->start) \
1594 		_vm_map_clip_start(map, entry, startaddr); \
1595 }
1596 
1597 /*
1598  *	This routine is called only when it is known that
1599  *	the entry must be split.
1600  */
1601 static void
1602 _vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t start)
1603 {
1604 	vm_map_entry_t new_entry;
1605 
1606 	VM_MAP_ASSERT_LOCKED(map);
1607 
1608 	/*
1609 	 * Split off the front portion -- note that we must insert the new
1610 	 * entry BEFORE this one, so that this entry has the specified
1611 	 * starting address.
1612 	 */
1613 	vm_map_simplify_entry(map, entry);
1614 
1615 	/*
1616 	 * If there is no object backing this entry, we might as well create
1617 	 * one now.  If we defer it, an object can get created after the map
1618 	 * is clipped, and individual objects will be created for the split-up
1619 	 * map.  This is a bit of a hack, but is also about the best place to
1620 	 * put this improvement.
1621 	 */
1622 	if (entry->object.vm_object == NULL && !map->system_map) {
1623 		vm_object_t object;
1624 		object = vm_object_allocate(OBJT_DEFAULT,
1625 				atop(entry->end - entry->start));
1626 		entry->object.vm_object = object;
1627 		entry->offset = 0;
1628 		if (entry->cred != NULL) {
1629 			object->cred = entry->cred;
1630 			object->charge = entry->end - entry->start;
1631 			entry->cred = NULL;
1632 		}
1633 	} else if (entry->object.vm_object != NULL &&
1634 		   ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
1635 		   entry->cred != NULL) {
1636 		VM_OBJECT_WLOCK(entry->object.vm_object);
1637 		KASSERT(entry->object.vm_object->cred == NULL,
1638 		    ("OVERCOMMIT: vm_entry_clip_start: both cred e %p", entry));
1639 		entry->object.vm_object->cred = entry->cred;
1640 		entry->object.vm_object->charge = entry->end - entry->start;
1641 		VM_OBJECT_WUNLOCK(entry->object.vm_object);
1642 		entry->cred = NULL;
1643 	}
1644 
1645 	new_entry = vm_map_entry_create(map);
1646 	*new_entry = *entry;
1647 
1648 	new_entry->end = start;
1649 	entry->offset += (start - entry->start);
1650 	entry->start = start;
1651 	if (new_entry->cred != NULL)
1652 		crhold(entry->cred);
1653 
1654 	vm_map_entry_link(map, entry->prev, new_entry);
1655 
1656 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1657 		vm_object_reference(new_entry->object.vm_object);
1658 		/*
1659 		 * The object->un_pager.vnp.writemappings for the
1660 		 * object of MAP_ENTRY_VN_WRITECNT type entry shall be
1661 		 * kept as is here.  The virtual pages are
1662 		 * re-distributed among the clipped entries, so the sum is
1663 		 * left the same.
1664 		 */
1665 	}
1666 }
1667 
1668 /*
1669  *	vm_map_clip_end:	[ internal use only ]
1670  *
1671  *	Asserts that the given entry ends at or before
1672  *	the specified address; if necessary,
1673  *	it splits the entry into two.
1674  */
1675 #define vm_map_clip_end(map, entry, endaddr) \
1676 { \
1677 	if ((endaddr) < (entry->end)) \
1678 		_vm_map_clip_end((map), (entry), (endaddr)); \
1679 }
1680 
1681 /*
1682  *	This routine is called only when it is known that
1683  *	the entry must be split.
1684  */
1685 static void
1686 _vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t end)
1687 {
1688 	vm_map_entry_t new_entry;
1689 
1690 	VM_MAP_ASSERT_LOCKED(map);
1691 
1692 	/*
1693 	 * If there is no object backing this entry, we might as well create
1694 	 * one now.  If we defer it, an object can get created after the map
1695 	 * is clipped, and individual objects will be created for the split-up
1696 	 * map.  This is a bit of a hack, but is also about the best place to
1697 	 * put this improvement.
1698 	 */
1699 	if (entry->object.vm_object == NULL && !map->system_map) {
1700 		vm_object_t object;
1701 		object = vm_object_allocate(OBJT_DEFAULT,
1702 				atop(entry->end - entry->start));
1703 		entry->object.vm_object = object;
1704 		entry->offset = 0;
1705 		if (entry->cred != NULL) {
1706 			object->cred = entry->cred;
1707 			object->charge = entry->end - entry->start;
1708 			entry->cred = NULL;
1709 		}
1710 	} else if (entry->object.vm_object != NULL &&
1711 		   ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
1712 		   entry->cred != NULL) {
1713 		VM_OBJECT_WLOCK(entry->object.vm_object);
1714 		KASSERT(entry->object.vm_object->cred == NULL,
1715 		    ("OVERCOMMIT: vm_entry_clip_end: both cred e %p", entry));
1716 		entry->object.vm_object->cred = entry->cred;
1717 		entry->object.vm_object->charge = entry->end - entry->start;
1718 		VM_OBJECT_WUNLOCK(entry->object.vm_object);
1719 		entry->cred = NULL;
1720 	}
1721 
1722 	/*
1723 	 * Create a new entry and insert it AFTER the specified entry
1724 	 */
1725 	new_entry = vm_map_entry_create(map);
1726 	*new_entry = *entry;
1727 
1728 	new_entry->start = entry->end = end;
1729 	new_entry->offset += (end - entry->start);
1730 	if (new_entry->cred != NULL)
1731 		crhold(entry->cred);
1732 
1733 	vm_map_entry_link(map, entry, new_entry);
1734 
1735 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1736 		vm_object_reference(new_entry->object.vm_object);
1737 	}
1738 }
1739 
1740 /*
1741  *	vm_map_submap:		[ kernel use only ]
1742  *
1743  *	Mark the given range as handled by a subordinate map.
1744  *
1745  *	This range must have been created with vm_map_find,
1746  *	and no other operations may have been performed on this
1747  *	range prior to calling vm_map_submap.
1748  *
1749  *	Only a limited number of operations can be performed
1750  *	within this rage after calling vm_map_submap:
1751  *		vm_fault
1752  *	[Don't try vm_map_copy!]
1753  *
1754  *	To remove a submapping, one must first remove the
1755  *	range from the superior map, and then destroy the
1756  *	submap (if desired).  [Better yet, don't try it.]
1757  */
1758 int
1759 vm_map_submap(
1760 	vm_map_t map,
1761 	vm_offset_t start,
1762 	vm_offset_t end,
1763 	vm_map_t submap)
1764 {
1765 	vm_map_entry_t entry;
1766 	int result = KERN_INVALID_ARGUMENT;
1767 
1768 	vm_map_lock(map);
1769 
1770 	VM_MAP_RANGE_CHECK(map, start, end);
1771 
1772 	if (vm_map_lookup_entry(map, start, &entry)) {
1773 		vm_map_clip_start(map, entry, start);
1774 	} else
1775 		entry = entry->next;
1776 
1777 	vm_map_clip_end(map, entry, end);
1778 
1779 	if ((entry->start == start) && (entry->end == end) &&
1780 	    ((entry->eflags & MAP_ENTRY_COW) == 0) &&
1781 	    (entry->object.vm_object == NULL)) {
1782 		entry->object.sub_map = submap;
1783 		entry->eflags |= MAP_ENTRY_IS_SUB_MAP;
1784 		result = KERN_SUCCESS;
1785 	}
1786 	vm_map_unlock(map);
1787 
1788 	return (result);
1789 }
1790 
1791 /*
1792  * The maximum number of pages to map if MAP_PREFAULT_PARTIAL is specified
1793  */
1794 #define	MAX_INIT_PT	96
1795 
1796 /*
1797  *	vm_map_pmap_enter:
1798  *
1799  *	Preload the specified map's pmap with mappings to the specified
1800  *	object's memory-resident pages.  No further physical pages are
1801  *	allocated, and no further virtual pages are retrieved from secondary
1802  *	storage.  If the specified flags include MAP_PREFAULT_PARTIAL, then a
1803  *	limited number of page mappings are created at the low-end of the
1804  *	specified address range.  (For this purpose, a superpage mapping
1805  *	counts as one page mapping.)  Otherwise, all resident pages within
1806  *	the specified address range are mapped.  Because these mappings are
1807  *	being created speculatively, cached pages are not reactivated and
1808  *	mapped.
1809  */
1810 void
1811 vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
1812     vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags)
1813 {
1814 	vm_offset_t start;
1815 	vm_page_t p, p_start;
1816 	vm_pindex_t mask, psize, threshold, tmpidx;
1817 
1818 	if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0 || object == NULL)
1819 		return;
1820 	VM_OBJECT_RLOCK(object);
1821 	if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
1822 		VM_OBJECT_RUNLOCK(object);
1823 		VM_OBJECT_WLOCK(object);
1824 		if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
1825 			pmap_object_init_pt(map->pmap, addr, object, pindex,
1826 			    size);
1827 			VM_OBJECT_WUNLOCK(object);
1828 			return;
1829 		}
1830 		VM_OBJECT_LOCK_DOWNGRADE(object);
1831 	}
1832 
1833 	psize = atop(size);
1834 	if (psize + pindex > object->size) {
1835 		if (object->size < pindex) {
1836 			VM_OBJECT_RUNLOCK(object);
1837 			return;
1838 		}
1839 		psize = object->size - pindex;
1840 	}
1841 
1842 	start = 0;
1843 	p_start = NULL;
1844 	threshold = MAX_INIT_PT;
1845 
1846 	p = vm_page_find_least(object, pindex);
1847 	/*
1848 	 * Assert: the variable p is either (1) the page with the
1849 	 * least pindex greater than or equal to the parameter pindex
1850 	 * or (2) NULL.
1851 	 */
1852 	for (;
1853 	     p != NULL && (tmpidx = p->pindex - pindex) < psize;
1854 	     p = TAILQ_NEXT(p, listq)) {
1855 		/*
1856 		 * don't allow an madvise to blow away our really
1857 		 * free pages allocating pv entries.
1858 		 */
1859 		if (((flags & MAP_PREFAULT_MADVISE) != 0 &&
1860 		    vm_cnt.v_free_count < vm_cnt.v_free_reserved) ||
1861 		    ((flags & MAP_PREFAULT_PARTIAL) != 0 &&
1862 		    tmpidx >= threshold)) {
1863 			psize = tmpidx;
1864 			break;
1865 		}
1866 		if (p->valid == VM_PAGE_BITS_ALL) {
1867 			if (p_start == NULL) {
1868 				start = addr + ptoa(tmpidx);
1869 				p_start = p;
1870 			}
1871 			/* Jump ahead if a superpage mapping is possible. */
1872 			if (p->psind > 0 && ((addr + ptoa(tmpidx)) &
1873 			    (pagesizes[p->psind] - 1)) == 0) {
1874 				mask = atop(pagesizes[p->psind]) - 1;
1875 				if (tmpidx + mask < psize &&
1876 				    vm_page_ps_is_valid(p)) {
1877 					p += mask;
1878 					threshold += mask;
1879 				}
1880 			}
1881 		} else if (p_start != NULL) {
1882 			pmap_enter_object(map->pmap, start, addr +
1883 			    ptoa(tmpidx), p_start, prot);
1884 			p_start = NULL;
1885 		}
1886 	}
1887 	if (p_start != NULL)
1888 		pmap_enter_object(map->pmap, start, addr + ptoa(psize),
1889 		    p_start, prot);
1890 	VM_OBJECT_RUNLOCK(object);
1891 }
1892 
1893 /*
1894  *	vm_map_protect:
1895  *
1896  *	Sets the protection of the specified address
1897  *	region in the target map.  If "set_max" is
1898  *	specified, the maximum protection is to be set;
1899  *	otherwise, only the current protection is affected.
1900  */
1901 int
1902 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
1903 	       vm_prot_t new_prot, boolean_t set_max)
1904 {
1905 	vm_map_entry_t current, entry;
1906 	vm_object_t obj;
1907 	struct ucred *cred;
1908 	vm_prot_t old_prot;
1909 
1910 	if (start == end)
1911 		return (KERN_SUCCESS);
1912 
1913 	vm_map_lock(map);
1914 
1915 	VM_MAP_RANGE_CHECK(map, start, end);
1916 
1917 	if (vm_map_lookup_entry(map, start, &entry)) {
1918 		vm_map_clip_start(map, entry, start);
1919 	} else {
1920 		entry = entry->next;
1921 	}
1922 
1923 	/*
1924 	 * Make a first pass to check for protection violations.
1925 	 */
1926 	current = entry;
1927 	while ((current != &map->header) && (current->start < end)) {
1928 		if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
1929 			vm_map_unlock(map);
1930 			return (KERN_INVALID_ARGUMENT);
1931 		}
1932 		if ((new_prot & current->max_protection) != new_prot) {
1933 			vm_map_unlock(map);
1934 			return (KERN_PROTECTION_FAILURE);
1935 		}
1936 		current = current->next;
1937 	}
1938 
1939 
1940 	/*
1941 	 * Do an accounting pass for private read-only mappings that
1942 	 * now will do cow due to allowed write (e.g. debugger sets
1943 	 * breakpoint on text segment)
1944 	 */
1945 	for (current = entry; (current != &map->header) &&
1946 	     (current->start < end); current = current->next) {
1947 
1948 		vm_map_clip_end(map, current, end);
1949 
1950 		if (set_max ||
1951 		    ((new_prot & ~(current->protection)) & VM_PROT_WRITE) == 0 ||
1952 		    ENTRY_CHARGED(current)) {
1953 			continue;
1954 		}
1955 
1956 		cred = curthread->td_ucred;
1957 		obj = current->object.vm_object;
1958 
1959 		if (obj == NULL || (current->eflags & MAP_ENTRY_NEEDS_COPY)) {
1960 			if (!swap_reserve(current->end - current->start)) {
1961 				vm_map_unlock(map);
1962 				return (KERN_RESOURCE_SHORTAGE);
1963 			}
1964 			crhold(cred);
1965 			current->cred = cred;
1966 			continue;
1967 		}
1968 
1969 		VM_OBJECT_WLOCK(obj);
1970 		if (obj->type != OBJT_DEFAULT && obj->type != OBJT_SWAP) {
1971 			VM_OBJECT_WUNLOCK(obj);
1972 			continue;
1973 		}
1974 
1975 		/*
1976 		 * Charge for the whole object allocation now, since
1977 		 * we cannot distinguish between non-charged and
1978 		 * charged clipped mapping of the same object later.
1979 		 */
1980 		KASSERT(obj->charge == 0,
1981 		    ("vm_map_protect: object %p overcharged (entry %p)",
1982 		    obj, current));
1983 		if (!swap_reserve(ptoa(obj->size))) {
1984 			VM_OBJECT_WUNLOCK(obj);
1985 			vm_map_unlock(map);
1986 			return (KERN_RESOURCE_SHORTAGE);
1987 		}
1988 
1989 		crhold(cred);
1990 		obj->cred = cred;
1991 		obj->charge = ptoa(obj->size);
1992 		VM_OBJECT_WUNLOCK(obj);
1993 	}
1994 
1995 	/*
1996 	 * Go back and fix up protections. [Note that clipping is not
1997 	 * necessary the second time.]
1998 	 */
1999 	current = entry;
2000 	while ((current != &map->header) && (current->start < end)) {
2001 		old_prot = current->protection;
2002 
2003 		if (set_max)
2004 			current->protection =
2005 			    (current->max_protection = new_prot) &
2006 			    old_prot;
2007 		else
2008 			current->protection = new_prot;
2009 
2010 		/*
2011 		 * For user wired map entries, the normal lazy evaluation of
2012 		 * write access upgrades through soft page faults is
2013 		 * undesirable.  Instead, immediately copy any pages that are
2014 		 * copy-on-write and enable write access in the physical map.
2015 		 */
2016 		if ((current->eflags & MAP_ENTRY_USER_WIRED) != 0 &&
2017 		    (current->protection & VM_PROT_WRITE) != 0 &&
2018 		    (old_prot & VM_PROT_WRITE) == 0)
2019 			vm_fault_copy_entry(map, map, current, current, NULL);
2020 
2021 		/*
2022 		 * When restricting access, update the physical map.  Worry
2023 		 * about copy-on-write here.
2024 		 */
2025 		if ((old_prot & ~current->protection) != 0) {
2026 #define MASK(entry)	(((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
2027 							VM_PROT_ALL)
2028 			pmap_protect(map->pmap, current->start,
2029 			    current->end,
2030 			    current->protection & MASK(current));
2031 #undef	MASK
2032 		}
2033 		vm_map_simplify_entry(map, current);
2034 		current = current->next;
2035 	}
2036 	vm_map_unlock(map);
2037 	return (KERN_SUCCESS);
2038 }
2039 
2040 /*
2041  *	vm_map_madvise:
2042  *
2043  *	This routine traverses a processes map handling the madvise
2044  *	system call.  Advisories are classified as either those effecting
2045  *	the vm_map_entry structure, or those effecting the underlying
2046  *	objects.
2047  */
2048 int
2049 vm_map_madvise(
2050 	vm_map_t map,
2051 	vm_offset_t start,
2052 	vm_offset_t end,
2053 	int behav)
2054 {
2055 	vm_map_entry_t current, entry;
2056 	int modify_map = 0;
2057 
2058 	/*
2059 	 * Some madvise calls directly modify the vm_map_entry, in which case
2060 	 * we need to use an exclusive lock on the map and we need to perform
2061 	 * various clipping operations.  Otherwise we only need a read-lock
2062 	 * on the map.
2063 	 */
2064 	switch(behav) {
2065 	case MADV_NORMAL:
2066 	case MADV_SEQUENTIAL:
2067 	case MADV_RANDOM:
2068 	case MADV_NOSYNC:
2069 	case MADV_AUTOSYNC:
2070 	case MADV_NOCORE:
2071 	case MADV_CORE:
2072 		if (start == end)
2073 			return (KERN_SUCCESS);
2074 		modify_map = 1;
2075 		vm_map_lock(map);
2076 		break;
2077 	case MADV_WILLNEED:
2078 	case MADV_DONTNEED:
2079 	case MADV_FREE:
2080 		if (start == end)
2081 			return (KERN_SUCCESS);
2082 		vm_map_lock_read(map);
2083 		break;
2084 	default:
2085 		return (KERN_INVALID_ARGUMENT);
2086 	}
2087 
2088 	/*
2089 	 * Locate starting entry and clip if necessary.
2090 	 */
2091 	VM_MAP_RANGE_CHECK(map, start, end);
2092 
2093 	if (vm_map_lookup_entry(map, start, &entry)) {
2094 		if (modify_map)
2095 			vm_map_clip_start(map, entry, start);
2096 	} else {
2097 		entry = entry->next;
2098 	}
2099 
2100 	if (modify_map) {
2101 		/*
2102 		 * madvise behaviors that are implemented in the vm_map_entry.
2103 		 *
2104 		 * We clip the vm_map_entry so that behavioral changes are
2105 		 * limited to the specified address range.
2106 		 */
2107 		for (current = entry;
2108 		     (current != &map->header) && (current->start < end);
2109 		     current = current->next
2110 		) {
2111 			if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
2112 				continue;
2113 
2114 			vm_map_clip_end(map, current, end);
2115 
2116 			switch (behav) {
2117 			case MADV_NORMAL:
2118 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_NORMAL);
2119 				break;
2120 			case MADV_SEQUENTIAL:
2121 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_SEQUENTIAL);
2122 				break;
2123 			case MADV_RANDOM:
2124 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_RANDOM);
2125 				break;
2126 			case MADV_NOSYNC:
2127 				current->eflags |= MAP_ENTRY_NOSYNC;
2128 				break;
2129 			case MADV_AUTOSYNC:
2130 				current->eflags &= ~MAP_ENTRY_NOSYNC;
2131 				break;
2132 			case MADV_NOCORE:
2133 				current->eflags |= MAP_ENTRY_NOCOREDUMP;
2134 				break;
2135 			case MADV_CORE:
2136 				current->eflags &= ~MAP_ENTRY_NOCOREDUMP;
2137 				break;
2138 			default:
2139 				break;
2140 			}
2141 			vm_map_simplify_entry(map, current);
2142 		}
2143 		vm_map_unlock(map);
2144 	} else {
2145 		vm_pindex_t pstart, pend;
2146 
2147 		/*
2148 		 * madvise behaviors that are implemented in the underlying
2149 		 * vm_object.
2150 		 *
2151 		 * Since we don't clip the vm_map_entry, we have to clip
2152 		 * the vm_object pindex and count.
2153 		 */
2154 		for (current = entry;
2155 		     (current != &map->header) && (current->start < end);
2156 		     current = current->next
2157 		) {
2158 			vm_offset_t useEnd, useStart;
2159 
2160 			if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
2161 				continue;
2162 
2163 			pstart = OFF_TO_IDX(current->offset);
2164 			pend = pstart + atop(current->end - current->start);
2165 			useStart = current->start;
2166 			useEnd = current->end;
2167 
2168 			if (current->start < start) {
2169 				pstart += atop(start - current->start);
2170 				useStart = start;
2171 			}
2172 			if (current->end > end) {
2173 				pend -= atop(current->end - end);
2174 				useEnd = end;
2175 			}
2176 
2177 			if (pstart >= pend)
2178 				continue;
2179 
2180 			/*
2181 			 * Perform the pmap_advise() before clearing
2182 			 * PGA_REFERENCED in vm_page_advise().  Otherwise, a
2183 			 * concurrent pmap operation, such as pmap_remove(),
2184 			 * could clear a reference in the pmap and set
2185 			 * PGA_REFERENCED on the page before the pmap_advise()
2186 			 * had completed.  Consequently, the page would appear
2187 			 * referenced based upon an old reference that
2188 			 * occurred before this pmap_advise() ran.
2189 			 */
2190 			if (behav == MADV_DONTNEED || behav == MADV_FREE)
2191 				pmap_advise(map->pmap, useStart, useEnd,
2192 				    behav);
2193 
2194 			vm_object_madvise(current->object.vm_object, pstart,
2195 			    pend, behav);
2196 			if (behav == MADV_WILLNEED) {
2197 				vm_map_pmap_enter(map,
2198 				    useStart,
2199 				    current->protection,
2200 				    current->object.vm_object,
2201 				    pstart,
2202 				    ptoa(pend - pstart),
2203 				    MAP_PREFAULT_MADVISE
2204 				);
2205 			}
2206 		}
2207 		vm_map_unlock_read(map);
2208 	}
2209 	return (0);
2210 }
2211 
2212 
2213 /*
2214  *	vm_map_inherit:
2215  *
2216  *	Sets the inheritance of the specified address
2217  *	range in the target map.  Inheritance
2218  *	affects how the map will be shared with
2219  *	child maps at the time of vmspace_fork.
2220  */
2221 int
2222 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
2223 	       vm_inherit_t new_inheritance)
2224 {
2225 	vm_map_entry_t entry;
2226 	vm_map_entry_t temp_entry;
2227 
2228 	switch (new_inheritance) {
2229 	case VM_INHERIT_NONE:
2230 	case VM_INHERIT_COPY:
2231 	case VM_INHERIT_SHARE:
2232 		break;
2233 	default:
2234 		return (KERN_INVALID_ARGUMENT);
2235 	}
2236 	if (start == end)
2237 		return (KERN_SUCCESS);
2238 	vm_map_lock(map);
2239 	VM_MAP_RANGE_CHECK(map, start, end);
2240 	if (vm_map_lookup_entry(map, start, &temp_entry)) {
2241 		entry = temp_entry;
2242 		vm_map_clip_start(map, entry, start);
2243 	} else
2244 		entry = temp_entry->next;
2245 	while ((entry != &map->header) && (entry->start < end)) {
2246 		vm_map_clip_end(map, entry, end);
2247 		entry->inheritance = new_inheritance;
2248 		vm_map_simplify_entry(map, entry);
2249 		entry = entry->next;
2250 	}
2251 	vm_map_unlock(map);
2252 	return (KERN_SUCCESS);
2253 }
2254 
2255 /*
2256  *	vm_map_unwire:
2257  *
2258  *	Implements both kernel and user unwiring.
2259  */
2260 int
2261 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t end,
2262     int flags)
2263 {
2264 	vm_map_entry_t entry, first_entry, tmp_entry;
2265 	vm_offset_t saved_start;
2266 	unsigned int last_timestamp;
2267 	int rv;
2268 	boolean_t need_wakeup, result, user_unwire;
2269 
2270 	if (start == end)
2271 		return (KERN_SUCCESS);
2272 	user_unwire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
2273 	vm_map_lock(map);
2274 	VM_MAP_RANGE_CHECK(map, start, end);
2275 	if (!vm_map_lookup_entry(map, start, &first_entry)) {
2276 		if (flags & VM_MAP_WIRE_HOLESOK)
2277 			first_entry = first_entry->next;
2278 		else {
2279 			vm_map_unlock(map);
2280 			return (KERN_INVALID_ADDRESS);
2281 		}
2282 	}
2283 	last_timestamp = map->timestamp;
2284 	entry = first_entry;
2285 	while (entry != &map->header && entry->start < end) {
2286 		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
2287 			/*
2288 			 * We have not yet clipped the entry.
2289 			 */
2290 			saved_start = (start >= entry->start) ? start :
2291 			    entry->start;
2292 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2293 			if (vm_map_unlock_and_wait(map, 0)) {
2294 				/*
2295 				 * Allow interruption of user unwiring?
2296 				 */
2297 			}
2298 			vm_map_lock(map);
2299 			if (last_timestamp+1 != map->timestamp) {
2300 				/*
2301 				 * Look again for the entry because the map was
2302 				 * modified while it was unlocked.
2303 				 * Specifically, the entry may have been
2304 				 * clipped, merged, or deleted.
2305 				 */
2306 				if (!vm_map_lookup_entry(map, saved_start,
2307 				    &tmp_entry)) {
2308 					if (flags & VM_MAP_WIRE_HOLESOK)
2309 						tmp_entry = tmp_entry->next;
2310 					else {
2311 						if (saved_start == start) {
2312 							/*
2313 							 * First_entry has been deleted.
2314 							 */
2315 							vm_map_unlock(map);
2316 							return (KERN_INVALID_ADDRESS);
2317 						}
2318 						end = saved_start;
2319 						rv = KERN_INVALID_ADDRESS;
2320 						goto done;
2321 					}
2322 				}
2323 				if (entry == first_entry)
2324 					first_entry = tmp_entry;
2325 				else
2326 					first_entry = NULL;
2327 				entry = tmp_entry;
2328 			}
2329 			last_timestamp = map->timestamp;
2330 			continue;
2331 		}
2332 		vm_map_clip_start(map, entry, start);
2333 		vm_map_clip_end(map, entry, end);
2334 		/*
2335 		 * Mark the entry in case the map lock is released.  (See
2336 		 * above.)
2337 		 */
2338 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
2339 		    entry->wiring_thread == NULL,
2340 		    ("owned map entry %p", entry));
2341 		entry->eflags |= MAP_ENTRY_IN_TRANSITION;
2342 		entry->wiring_thread = curthread;
2343 		/*
2344 		 * Check the map for holes in the specified region.
2345 		 * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
2346 		 */
2347 		if (((flags & VM_MAP_WIRE_HOLESOK) == 0) &&
2348 		    (entry->end < end && (entry->next == &map->header ||
2349 		    entry->next->start > entry->end))) {
2350 			end = entry->end;
2351 			rv = KERN_INVALID_ADDRESS;
2352 			goto done;
2353 		}
2354 		/*
2355 		 * If system unwiring, require that the entry is system wired.
2356 		 */
2357 		if (!user_unwire &&
2358 		    vm_map_entry_system_wired_count(entry) == 0) {
2359 			end = entry->end;
2360 			rv = KERN_INVALID_ARGUMENT;
2361 			goto done;
2362 		}
2363 		entry = entry->next;
2364 	}
2365 	rv = KERN_SUCCESS;
2366 done:
2367 	need_wakeup = FALSE;
2368 	if (first_entry == NULL) {
2369 		result = vm_map_lookup_entry(map, start, &first_entry);
2370 		if (!result && (flags & VM_MAP_WIRE_HOLESOK))
2371 			first_entry = first_entry->next;
2372 		else
2373 			KASSERT(result, ("vm_map_unwire: lookup failed"));
2374 	}
2375 	for (entry = first_entry; entry != &map->header && entry->start < end;
2376 	    entry = entry->next) {
2377 		/*
2378 		 * If VM_MAP_WIRE_HOLESOK was specified, an empty
2379 		 * space in the unwired region could have been mapped
2380 		 * while the map lock was dropped for draining
2381 		 * MAP_ENTRY_IN_TRANSITION.  Moreover, another thread
2382 		 * could be simultaneously wiring this new mapping
2383 		 * entry.  Detect these cases and skip any entries
2384 		 * marked as in transition by us.
2385 		 */
2386 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
2387 		    entry->wiring_thread != curthread) {
2388 			KASSERT((flags & VM_MAP_WIRE_HOLESOK) != 0,
2389 			    ("vm_map_unwire: !HOLESOK and new/changed entry"));
2390 			continue;
2391 		}
2392 
2393 		if (rv == KERN_SUCCESS && (!user_unwire ||
2394 		    (entry->eflags & MAP_ENTRY_USER_WIRED))) {
2395 			if (user_unwire)
2396 				entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2397 			if (entry->wired_count == 1)
2398 				vm_map_entry_unwire(map, entry);
2399 			else
2400 				entry->wired_count--;
2401 		}
2402 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
2403 		    ("vm_map_unwire: in-transition flag missing %p", entry));
2404 		KASSERT(entry->wiring_thread == curthread,
2405 		    ("vm_map_unwire: alien wire %p", entry));
2406 		entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
2407 		entry->wiring_thread = NULL;
2408 		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
2409 			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
2410 			need_wakeup = TRUE;
2411 		}
2412 		vm_map_simplify_entry(map, entry);
2413 	}
2414 	vm_map_unlock(map);
2415 	if (need_wakeup)
2416 		vm_map_wakeup(map);
2417 	return (rv);
2418 }
2419 
2420 /*
2421  *	vm_map_wire:
2422  *
2423  *	Implements both kernel and user wiring.
2424  */
2425 int
2426 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t end,
2427     int flags)
2428 {
2429 	vm_map_entry_t entry, first_entry, tmp_entry;
2430 	vm_offset_t saved_end, saved_start;
2431 	unsigned int last_timestamp;
2432 	int rv;
2433 	boolean_t fictitious, need_wakeup, result, user_wire;
2434 	vm_prot_t prot;
2435 
2436 	if (start == end)
2437 		return (KERN_SUCCESS);
2438 	prot = 0;
2439 	if (flags & VM_MAP_WIRE_WRITE)
2440 		prot |= VM_PROT_WRITE;
2441 	user_wire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
2442 	vm_map_lock(map);
2443 	VM_MAP_RANGE_CHECK(map, start, end);
2444 	if (!vm_map_lookup_entry(map, start, &first_entry)) {
2445 		if (flags & VM_MAP_WIRE_HOLESOK)
2446 			first_entry = first_entry->next;
2447 		else {
2448 			vm_map_unlock(map);
2449 			return (KERN_INVALID_ADDRESS);
2450 		}
2451 	}
2452 	last_timestamp = map->timestamp;
2453 	entry = first_entry;
2454 	while (entry != &map->header && entry->start < end) {
2455 		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
2456 			/*
2457 			 * We have not yet clipped the entry.
2458 			 */
2459 			saved_start = (start >= entry->start) ? start :
2460 			    entry->start;
2461 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2462 			if (vm_map_unlock_and_wait(map, 0)) {
2463 				/*
2464 				 * Allow interruption of user wiring?
2465 				 */
2466 			}
2467 			vm_map_lock(map);
2468 			if (last_timestamp + 1 != map->timestamp) {
2469 				/*
2470 				 * Look again for the entry because the map was
2471 				 * modified while it was unlocked.
2472 				 * Specifically, the entry may have been
2473 				 * clipped, merged, or deleted.
2474 				 */
2475 				if (!vm_map_lookup_entry(map, saved_start,
2476 				    &tmp_entry)) {
2477 					if (flags & VM_MAP_WIRE_HOLESOK)
2478 						tmp_entry = tmp_entry->next;
2479 					else {
2480 						if (saved_start == start) {
2481 							/*
2482 							 * first_entry has been deleted.
2483 							 */
2484 							vm_map_unlock(map);
2485 							return (KERN_INVALID_ADDRESS);
2486 						}
2487 						end = saved_start;
2488 						rv = KERN_INVALID_ADDRESS;
2489 						goto done;
2490 					}
2491 				}
2492 				if (entry == first_entry)
2493 					first_entry = tmp_entry;
2494 				else
2495 					first_entry = NULL;
2496 				entry = tmp_entry;
2497 			}
2498 			last_timestamp = map->timestamp;
2499 			continue;
2500 		}
2501 		vm_map_clip_start(map, entry, start);
2502 		vm_map_clip_end(map, entry, end);
2503 		/*
2504 		 * Mark the entry in case the map lock is released.  (See
2505 		 * above.)
2506 		 */
2507 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
2508 		    entry->wiring_thread == NULL,
2509 		    ("owned map entry %p", entry));
2510 		entry->eflags |= MAP_ENTRY_IN_TRANSITION;
2511 		entry->wiring_thread = curthread;
2512 		if ((entry->protection & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0
2513 		    || (entry->protection & prot) != prot) {
2514 			entry->eflags |= MAP_ENTRY_WIRE_SKIPPED;
2515 			if ((flags & VM_MAP_WIRE_HOLESOK) == 0) {
2516 				end = entry->end;
2517 				rv = KERN_INVALID_ADDRESS;
2518 				goto done;
2519 			}
2520 			goto next_entry;
2521 		}
2522 		if (entry->wired_count == 0) {
2523 			entry->wired_count++;
2524 			saved_start = entry->start;
2525 			saved_end = entry->end;
2526 			fictitious = entry->object.vm_object != NULL &&
2527 			    (entry->object.vm_object->flags &
2528 			    OBJ_FICTITIOUS) != 0;
2529 			/*
2530 			 * Release the map lock, relying on the in-transition
2531 			 * mark.  Mark the map busy for fork.
2532 			 */
2533 			vm_map_busy(map);
2534 			vm_map_unlock(map);
2535 			rv = vm_fault_wire(map, saved_start, saved_end,
2536 			    fictitious);
2537 			vm_map_lock(map);
2538 			vm_map_unbusy(map);
2539 			if (last_timestamp + 1 != map->timestamp) {
2540 				/*
2541 				 * Look again for the entry because the map was
2542 				 * modified while it was unlocked.  The entry
2543 				 * may have been clipped, but NOT merged or
2544 				 * deleted.
2545 				 */
2546 				result = vm_map_lookup_entry(map, saved_start,
2547 				    &tmp_entry);
2548 				KASSERT(result, ("vm_map_wire: lookup failed"));
2549 				if (entry == first_entry)
2550 					first_entry = tmp_entry;
2551 				else
2552 					first_entry = NULL;
2553 				entry = tmp_entry;
2554 				while (entry->end < saved_end) {
2555 					if (rv != KERN_SUCCESS) {
2556 						KASSERT(entry->wired_count == 1,
2557 						    ("vm_map_wire: bad count"));
2558 						entry->wired_count = -1;
2559 					}
2560 					entry = entry->next;
2561 				}
2562 			}
2563 			last_timestamp = map->timestamp;
2564 			if (rv != KERN_SUCCESS) {
2565 				KASSERT(entry->wired_count == 1,
2566 				    ("vm_map_wire: bad count"));
2567 				/*
2568 				 * Assign an out-of-range value to represent
2569 				 * the failure to wire this entry.
2570 				 */
2571 				entry->wired_count = -1;
2572 				end = entry->end;
2573 				goto done;
2574 			}
2575 		} else if (!user_wire ||
2576 			   (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
2577 			entry->wired_count++;
2578 		}
2579 		/*
2580 		 * Check the map for holes in the specified region.
2581 		 * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
2582 		 */
2583 	next_entry:
2584 		if (((flags & VM_MAP_WIRE_HOLESOK) == 0) &&
2585 		    (entry->end < end && (entry->next == &map->header ||
2586 		    entry->next->start > entry->end))) {
2587 			end = entry->end;
2588 			rv = KERN_INVALID_ADDRESS;
2589 			goto done;
2590 		}
2591 		entry = entry->next;
2592 	}
2593 	rv = KERN_SUCCESS;
2594 done:
2595 	need_wakeup = FALSE;
2596 	if (first_entry == NULL) {
2597 		result = vm_map_lookup_entry(map, start, &first_entry);
2598 		if (!result && (flags & VM_MAP_WIRE_HOLESOK))
2599 			first_entry = first_entry->next;
2600 		else
2601 			KASSERT(result, ("vm_map_wire: lookup failed"));
2602 	}
2603 	for (entry = first_entry; entry != &map->header && entry->start < end;
2604 	    entry = entry->next) {
2605 		if ((entry->eflags & MAP_ENTRY_WIRE_SKIPPED) != 0)
2606 			goto next_entry_done;
2607 
2608 		/*
2609 		 * If VM_MAP_WIRE_HOLESOK was specified, an empty
2610 		 * space in the unwired region could have been mapped
2611 		 * while the map lock was dropped for faulting in the
2612 		 * pages or draining MAP_ENTRY_IN_TRANSITION.
2613 		 * Moreover, another thread could be simultaneously
2614 		 * wiring this new mapping entry.  Detect these cases
2615 		 * and skip any entries marked as in transition by us.
2616 		 */
2617 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
2618 		    entry->wiring_thread != curthread) {
2619 			KASSERT((flags & VM_MAP_WIRE_HOLESOK) != 0,
2620 			    ("vm_map_wire: !HOLESOK and new/changed entry"));
2621 			continue;
2622 		}
2623 
2624 		if (rv == KERN_SUCCESS) {
2625 			if (user_wire)
2626 				entry->eflags |= MAP_ENTRY_USER_WIRED;
2627 		} else if (entry->wired_count == -1) {
2628 			/*
2629 			 * Wiring failed on this entry.  Thus, unwiring is
2630 			 * unnecessary.
2631 			 */
2632 			entry->wired_count = 0;
2633 		} else if (!user_wire ||
2634 		    (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
2635 			if (entry->wired_count == 1)
2636 				vm_map_entry_unwire(map, entry);
2637 			else
2638 				entry->wired_count--;
2639 		}
2640 	next_entry_done:
2641 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
2642 		    ("vm_map_wire: in-transition flag missing %p", entry));
2643 		KASSERT(entry->wiring_thread == curthread,
2644 		    ("vm_map_wire: alien wire %p", entry));
2645 		entry->eflags &= ~(MAP_ENTRY_IN_TRANSITION |
2646 		    MAP_ENTRY_WIRE_SKIPPED);
2647 		entry->wiring_thread = NULL;
2648 		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
2649 			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
2650 			need_wakeup = TRUE;
2651 		}
2652 		vm_map_simplify_entry(map, entry);
2653 	}
2654 	vm_map_unlock(map);
2655 	if (need_wakeup)
2656 		vm_map_wakeup(map);
2657 	return (rv);
2658 }
2659 
2660 /*
2661  * vm_map_sync
2662  *
2663  * Push any dirty cached pages in the address range to their pager.
2664  * If syncio is TRUE, dirty pages are written synchronously.
2665  * If invalidate is TRUE, any cached pages are freed as well.
2666  *
2667  * If the size of the region from start to end is zero, we are
2668  * supposed to flush all modified pages within the region containing
2669  * start.  Unfortunately, a region can be split or coalesced with
2670  * neighboring regions, making it difficult to determine what the
2671  * original region was.  Therefore, we approximate this requirement by
2672  * flushing the current region containing start.
2673  *
2674  * Returns an error if any part of the specified range is not mapped.
2675  */
2676 int
2677 vm_map_sync(
2678 	vm_map_t map,
2679 	vm_offset_t start,
2680 	vm_offset_t end,
2681 	boolean_t syncio,
2682 	boolean_t invalidate)
2683 {
2684 	vm_map_entry_t current;
2685 	vm_map_entry_t entry;
2686 	vm_size_t size;
2687 	vm_object_t object;
2688 	vm_ooffset_t offset;
2689 	unsigned int last_timestamp;
2690 	boolean_t failed;
2691 
2692 	vm_map_lock_read(map);
2693 	VM_MAP_RANGE_CHECK(map, start, end);
2694 	if (!vm_map_lookup_entry(map, start, &entry)) {
2695 		vm_map_unlock_read(map);
2696 		return (KERN_INVALID_ADDRESS);
2697 	} else if (start == end) {
2698 		start = entry->start;
2699 		end = entry->end;
2700 	}
2701 	/*
2702 	 * Make a first pass to check for user-wired memory and holes.
2703 	 */
2704 	for (current = entry; current != &map->header && current->start < end;
2705 	    current = current->next) {
2706 		if (invalidate && (current->eflags & MAP_ENTRY_USER_WIRED)) {
2707 			vm_map_unlock_read(map);
2708 			return (KERN_INVALID_ARGUMENT);
2709 		}
2710 		if (end > current->end &&
2711 		    (current->next == &map->header ||
2712 			current->end != current->next->start)) {
2713 			vm_map_unlock_read(map);
2714 			return (KERN_INVALID_ADDRESS);
2715 		}
2716 	}
2717 
2718 	if (invalidate)
2719 		pmap_remove(map->pmap, start, end);
2720 	failed = FALSE;
2721 
2722 	/*
2723 	 * Make a second pass, cleaning/uncaching pages from the indicated
2724 	 * objects as we go.
2725 	 */
2726 	for (current = entry; current != &map->header && current->start < end;) {
2727 		offset = current->offset + (start - current->start);
2728 		size = (end <= current->end ? end : current->end) - start;
2729 		if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
2730 			vm_map_t smap;
2731 			vm_map_entry_t tentry;
2732 			vm_size_t tsize;
2733 
2734 			smap = current->object.sub_map;
2735 			vm_map_lock_read(smap);
2736 			(void) vm_map_lookup_entry(smap, offset, &tentry);
2737 			tsize = tentry->end - offset;
2738 			if (tsize < size)
2739 				size = tsize;
2740 			object = tentry->object.vm_object;
2741 			offset = tentry->offset + (offset - tentry->start);
2742 			vm_map_unlock_read(smap);
2743 		} else {
2744 			object = current->object.vm_object;
2745 		}
2746 		vm_object_reference(object);
2747 		last_timestamp = map->timestamp;
2748 		vm_map_unlock_read(map);
2749 		if (!vm_object_sync(object, offset, size, syncio, invalidate))
2750 			failed = TRUE;
2751 		start += size;
2752 		vm_object_deallocate(object);
2753 		vm_map_lock_read(map);
2754 		if (last_timestamp == map->timestamp ||
2755 		    !vm_map_lookup_entry(map, start, &current))
2756 			current = current->next;
2757 	}
2758 
2759 	vm_map_unlock_read(map);
2760 	return (failed ? KERN_FAILURE : KERN_SUCCESS);
2761 }
2762 
2763 /*
2764  *	vm_map_entry_unwire:	[ internal use only ]
2765  *
2766  *	Make the region specified by this entry pageable.
2767  *
2768  *	The map in question should be locked.
2769  *	[This is the reason for this routine's existence.]
2770  */
2771 static void
2772 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
2773 {
2774 
2775 	VM_MAP_ASSERT_LOCKED(map);
2776 	KASSERT(entry->wired_count > 0,
2777 	    ("vm_map_entry_unwire: entry %p isn't wired", entry));
2778 	pmap_unwire(map->pmap, entry->start, entry->end);
2779 	vm_object_unwire(entry->object.vm_object, entry->offset, entry->end -
2780 	    entry->start, PQ_ACTIVE);
2781 	entry->wired_count = 0;
2782 }
2783 
2784 static void
2785 vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map)
2786 {
2787 
2788 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0)
2789 		vm_object_deallocate(entry->object.vm_object);
2790 	uma_zfree(system_map ? kmapentzone : mapentzone, entry);
2791 }
2792 
2793 /*
2794  *	vm_map_entry_delete:	[ internal use only ]
2795  *
2796  *	Deallocate the given entry from the target map.
2797  */
2798 static void
2799 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry)
2800 {
2801 	vm_object_t object;
2802 	vm_pindex_t offidxstart, offidxend, count, size1;
2803 	vm_ooffset_t size;
2804 
2805 	vm_map_entry_unlink(map, entry);
2806 	object = entry->object.vm_object;
2807 	size = entry->end - entry->start;
2808 	map->size -= size;
2809 
2810 	if (entry->cred != NULL) {
2811 		swap_release_by_cred(size, entry->cred);
2812 		crfree(entry->cred);
2813 	}
2814 
2815 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0 &&
2816 	    (object != NULL)) {
2817 		KASSERT(entry->cred == NULL || object->cred == NULL ||
2818 		    (entry->eflags & MAP_ENTRY_NEEDS_COPY),
2819 		    ("OVERCOMMIT vm_map_entry_delete: both cred %p", entry));
2820 		count = OFF_TO_IDX(size);
2821 		offidxstart = OFF_TO_IDX(entry->offset);
2822 		offidxend = offidxstart + count;
2823 		VM_OBJECT_WLOCK(object);
2824 		if (object->ref_count != 1 &&
2825 		    ((object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING ||
2826 		    object == kernel_object || object == kmem_object)) {
2827 			vm_object_collapse(object);
2828 
2829 			/*
2830 			 * The option OBJPR_NOTMAPPED can be passed here
2831 			 * because vm_map_delete() already performed
2832 			 * pmap_remove() on the only mapping to this range
2833 			 * of pages.
2834 			 */
2835 			vm_object_page_remove(object, offidxstart, offidxend,
2836 			    OBJPR_NOTMAPPED);
2837 			if (object->type == OBJT_SWAP)
2838 				swap_pager_freespace(object, offidxstart, count);
2839 			if (offidxend >= object->size &&
2840 			    offidxstart < object->size) {
2841 				size1 = object->size;
2842 				object->size = offidxstart;
2843 				if (object->cred != NULL) {
2844 					size1 -= object->size;
2845 					KASSERT(object->charge >= ptoa(size1),
2846 					    ("vm_map_entry_delete: object->charge < 0"));
2847 					swap_release_by_cred(ptoa(size1), object->cred);
2848 					object->charge -= ptoa(size1);
2849 				}
2850 			}
2851 		}
2852 		VM_OBJECT_WUNLOCK(object);
2853 	} else
2854 		entry->object.vm_object = NULL;
2855 	if (map->system_map)
2856 		vm_map_entry_deallocate(entry, TRUE);
2857 	else {
2858 		entry->next = curthread->td_map_def_user;
2859 		curthread->td_map_def_user = entry;
2860 	}
2861 }
2862 
2863 /*
2864  *	vm_map_delete:	[ internal use only ]
2865  *
2866  *	Deallocates the given address range from the target
2867  *	map.
2868  */
2869 int
2870 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
2871 {
2872 	vm_map_entry_t entry;
2873 	vm_map_entry_t first_entry;
2874 
2875 	VM_MAP_ASSERT_LOCKED(map);
2876 	if (start == end)
2877 		return (KERN_SUCCESS);
2878 
2879 	/*
2880 	 * Find the start of the region, and clip it
2881 	 */
2882 	if (!vm_map_lookup_entry(map, start, &first_entry))
2883 		entry = first_entry->next;
2884 	else {
2885 		entry = first_entry;
2886 		vm_map_clip_start(map, entry, start);
2887 	}
2888 
2889 	/*
2890 	 * Step through all entries in this region
2891 	 */
2892 	while ((entry != &map->header) && (entry->start < end)) {
2893 		vm_map_entry_t next;
2894 
2895 		/*
2896 		 * Wait for wiring or unwiring of an entry to complete.
2897 		 * Also wait for any system wirings to disappear on
2898 		 * user maps.
2899 		 */
2900 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 ||
2901 		    (vm_map_pmap(map) != kernel_pmap &&
2902 		    vm_map_entry_system_wired_count(entry) != 0)) {
2903 			unsigned int last_timestamp;
2904 			vm_offset_t saved_start;
2905 			vm_map_entry_t tmp_entry;
2906 
2907 			saved_start = entry->start;
2908 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2909 			last_timestamp = map->timestamp;
2910 			(void) vm_map_unlock_and_wait(map, 0);
2911 			vm_map_lock(map);
2912 			if (last_timestamp + 1 != map->timestamp) {
2913 				/*
2914 				 * Look again for the entry because the map was
2915 				 * modified while it was unlocked.
2916 				 * Specifically, the entry may have been
2917 				 * clipped, merged, or deleted.
2918 				 */
2919 				if (!vm_map_lookup_entry(map, saved_start,
2920 							 &tmp_entry))
2921 					entry = tmp_entry->next;
2922 				else {
2923 					entry = tmp_entry;
2924 					vm_map_clip_start(map, entry,
2925 							  saved_start);
2926 				}
2927 			}
2928 			continue;
2929 		}
2930 		vm_map_clip_end(map, entry, end);
2931 
2932 		next = entry->next;
2933 
2934 		/*
2935 		 * Unwire before removing addresses from the pmap; otherwise,
2936 		 * unwiring will put the entries back in the pmap.
2937 		 */
2938 		if (entry->wired_count != 0) {
2939 			vm_map_entry_unwire(map, entry);
2940 		}
2941 
2942 		pmap_remove(map->pmap, entry->start, entry->end);
2943 
2944 		/*
2945 		 * Delete the entry only after removing all pmap
2946 		 * entries pointing to its pages.  (Otherwise, its
2947 		 * page frames may be reallocated, and any modify bits
2948 		 * will be set in the wrong object!)
2949 		 */
2950 		vm_map_entry_delete(map, entry);
2951 		entry = next;
2952 	}
2953 	return (KERN_SUCCESS);
2954 }
2955 
2956 /*
2957  *	vm_map_remove:
2958  *
2959  *	Remove the given address range from the target map.
2960  *	This is the exported form of vm_map_delete.
2961  */
2962 int
2963 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
2964 {
2965 	int result;
2966 
2967 	vm_map_lock(map);
2968 	VM_MAP_RANGE_CHECK(map, start, end);
2969 	result = vm_map_delete(map, start, end);
2970 	vm_map_unlock(map);
2971 	return (result);
2972 }
2973 
2974 /*
2975  *	vm_map_check_protection:
2976  *
2977  *	Assert that the target map allows the specified privilege on the
2978  *	entire address region given.  The entire region must be allocated.
2979  *
2980  *	WARNING!  This code does not and should not check whether the
2981  *	contents of the region is accessible.  For example a smaller file
2982  *	might be mapped into a larger address space.
2983  *
2984  *	NOTE!  This code is also called by munmap().
2985  *
2986  *	The map must be locked.  A read lock is sufficient.
2987  */
2988 boolean_t
2989 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
2990 			vm_prot_t protection)
2991 {
2992 	vm_map_entry_t entry;
2993 	vm_map_entry_t tmp_entry;
2994 
2995 	if (!vm_map_lookup_entry(map, start, &tmp_entry))
2996 		return (FALSE);
2997 	entry = tmp_entry;
2998 
2999 	while (start < end) {
3000 		if (entry == &map->header)
3001 			return (FALSE);
3002 		/*
3003 		 * No holes allowed!
3004 		 */
3005 		if (start < entry->start)
3006 			return (FALSE);
3007 		/*
3008 		 * Check protection associated with entry.
3009 		 */
3010 		if ((entry->protection & protection) != protection)
3011 			return (FALSE);
3012 		/* go to next entry */
3013 		start = entry->end;
3014 		entry = entry->next;
3015 	}
3016 	return (TRUE);
3017 }
3018 
3019 /*
3020  *	vm_map_copy_entry:
3021  *
3022  *	Copies the contents of the source entry to the destination
3023  *	entry.  The entries *must* be aligned properly.
3024  */
3025 static void
3026 vm_map_copy_entry(
3027 	vm_map_t src_map,
3028 	vm_map_t dst_map,
3029 	vm_map_entry_t src_entry,
3030 	vm_map_entry_t dst_entry,
3031 	vm_ooffset_t *fork_charge)
3032 {
3033 	vm_object_t src_object;
3034 	vm_map_entry_t fake_entry;
3035 	vm_offset_t size;
3036 	struct ucred *cred;
3037 	int charged;
3038 
3039 	VM_MAP_ASSERT_LOCKED(dst_map);
3040 
3041 	if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
3042 		return;
3043 
3044 	if (src_entry->wired_count == 0 ||
3045 	    (src_entry->protection & VM_PROT_WRITE) == 0) {
3046 		/*
3047 		 * If the source entry is marked needs_copy, it is already
3048 		 * write-protected.
3049 		 */
3050 		if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0 &&
3051 		    (src_entry->protection & VM_PROT_WRITE) != 0) {
3052 			pmap_protect(src_map->pmap,
3053 			    src_entry->start,
3054 			    src_entry->end,
3055 			    src_entry->protection & ~VM_PROT_WRITE);
3056 		}
3057 
3058 		/*
3059 		 * Make a copy of the object.
3060 		 */
3061 		size = src_entry->end - src_entry->start;
3062 		if ((src_object = src_entry->object.vm_object) != NULL) {
3063 			VM_OBJECT_WLOCK(src_object);
3064 			charged = ENTRY_CHARGED(src_entry);
3065 			if ((src_object->handle == NULL) &&
3066 				(src_object->type == OBJT_DEFAULT ||
3067 				 src_object->type == OBJT_SWAP)) {
3068 				vm_object_collapse(src_object);
3069 				if ((src_object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING) {
3070 					vm_object_split(src_entry);
3071 					src_object = src_entry->object.vm_object;
3072 				}
3073 			}
3074 			vm_object_reference_locked(src_object);
3075 			vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
3076 			if (src_entry->cred != NULL &&
3077 			    !(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
3078 				KASSERT(src_object->cred == NULL,
3079 				    ("OVERCOMMIT: vm_map_copy_entry: cred %p",
3080 				     src_object));
3081 				src_object->cred = src_entry->cred;
3082 				src_object->charge = size;
3083 			}
3084 			VM_OBJECT_WUNLOCK(src_object);
3085 			dst_entry->object.vm_object = src_object;
3086 			if (charged) {
3087 				cred = curthread->td_ucred;
3088 				crhold(cred);
3089 				dst_entry->cred = cred;
3090 				*fork_charge += size;
3091 				if (!(src_entry->eflags &
3092 				      MAP_ENTRY_NEEDS_COPY)) {
3093 					crhold(cred);
3094 					src_entry->cred = cred;
3095 					*fork_charge += size;
3096 				}
3097 			}
3098 			src_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
3099 			dst_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
3100 			dst_entry->offset = src_entry->offset;
3101 			if (src_entry->eflags & MAP_ENTRY_VN_WRITECNT) {
3102 				/*
3103 				 * MAP_ENTRY_VN_WRITECNT cannot
3104 				 * indicate write reference from
3105 				 * src_entry, since the entry is
3106 				 * marked as needs copy.  Allocate a
3107 				 * fake entry that is used to
3108 				 * decrement object->un_pager.vnp.writecount
3109 				 * at the appropriate time.  Attach
3110 				 * fake_entry to the deferred list.
3111 				 */
3112 				fake_entry = vm_map_entry_create(dst_map);
3113 				fake_entry->eflags = MAP_ENTRY_VN_WRITECNT;
3114 				src_entry->eflags &= ~MAP_ENTRY_VN_WRITECNT;
3115 				vm_object_reference(src_object);
3116 				fake_entry->object.vm_object = src_object;
3117 				fake_entry->start = src_entry->start;
3118 				fake_entry->end = src_entry->end;
3119 				fake_entry->next = curthread->td_map_def_user;
3120 				curthread->td_map_def_user = fake_entry;
3121 			}
3122 		} else {
3123 			dst_entry->object.vm_object = NULL;
3124 			dst_entry->offset = 0;
3125 			if (src_entry->cred != NULL) {
3126 				dst_entry->cred = curthread->td_ucred;
3127 				crhold(dst_entry->cred);
3128 				*fork_charge += size;
3129 			}
3130 		}
3131 
3132 		pmap_copy(dst_map->pmap, src_map->pmap, dst_entry->start,
3133 		    dst_entry->end - dst_entry->start, src_entry->start);
3134 	} else {
3135 		/*
3136 		 * We don't want to make writeable wired pages copy-on-write.
3137 		 * Immediately copy these pages into the new map by simulating
3138 		 * page faults.  The new pages are pageable.
3139 		 */
3140 		vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry,
3141 		    fork_charge);
3142 	}
3143 }
3144 
3145 /*
3146  * vmspace_map_entry_forked:
3147  * Update the newly-forked vmspace each time a map entry is inherited
3148  * or copied.  The values for vm_dsize and vm_tsize are approximate
3149  * (and mostly-obsolete ideas in the face of mmap(2) et al.)
3150  */
3151 static void
3152 vmspace_map_entry_forked(const struct vmspace *vm1, struct vmspace *vm2,
3153     vm_map_entry_t entry)
3154 {
3155 	vm_size_t entrysize;
3156 	vm_offset_t newend;
3157 
3158 	entrysize = entry->end - entry->start;
3159 	vm2->vm_map.size += entrysize;
3160 	if (entry->eflags & (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP)) {
3161 		vm2->vm_ssize += btoc(entrysize);
3162 	} else if (entry->start >= (vm_offset_t)vm1->vm_daddr &&
3163 	    entry->start < (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize)) {
3164 		newend = MIN(entry->end,
3165 		    (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize));
3166 		vm2->vm_dsize += btoc(newend - entry->start);
3167 	} else if (entry->start >= (vm_offset_t)vm1->vm_taddr &&
3168 	    entry->start < (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize)) {
3169 		newend = MIN(entry->end,
3170 		    (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize));
3171 		vm2->vm_tsize += btoc(newend - entry->start);
3172 	}
3173 }
3174 
3175 /*
3176  * vmspace_fork:
3177  * Create a new process vmspace structure and vm_map
3178  * based on those of an existing process.  The new map
3179  * is based on the old map, according to the inheritance
3180  * values on the regions in that map.
3181  *
3182  * XXX It might be worth coalescing the entries added to the new vmspace.
3183  *
3184  * The source map must not be locked.
3185  */
3186 struct vmspace *
3187 vmspace_fork(struct vmspace *vm1, vm_ooffset_t *fork_charge)
3188 {
3189 	struct vmspace *vm2;
3190 	vm_map_t new_map, old_map;
3191 	vm_map_entry_t new_entry, old_entry;
3192 	vm_object_t object;
3193 	int locked;
3194 
3195 	old_map = &vm1->vm_map;
3196 	/* Copy immutable fields of vm1 to vm2. */
3197 	vm2 = vmspace_alloc(old_map->min_offset, old_map->max_offset, NULL);
3198 	if (vm2 == NULL)
3199 		return (NULL);
3200 	vm2->vm_taddr = vm1->vm_taddr;
3201 	vm2->vm_daddr = vm1->vm_daddr;
3202 	vm2->vm_maxsaddr = vm1->vm_maxsaddr;
3203 	vm_map_lock(old_map);
3204 	if (old_map->busy)
3205 		vm_map_wait_busy(old_map);
3206 	new_map = &vm2->vm_map;
3207 	locked = vm_map_trylock(new_map); /* trylock to silence WITNESS */
3208 	KASSERT(locked, ("vmspace_fork: lock failed"));
3209 
3210 	old_entry = old_map->header.next;
3211 
3212 	while (old_entry != &old_map->header) {
3213 		if (old_entry->eflags & MAP_ENTRY_IS_SUB_MAP)
3214 			panic("vm_map_fork: encountered a submap");
3215 
3216 		switch (old_entry->inheritance) {
3217 		case VM_INHERIT_NONE:
3218 			break;
3219 
3220 		case VM_INHERIT_SHARE:
3221 			/*
3222 			 * Clone the entry, creating the shared object if necessary.
3223 			 */
3224 			object = old_entry->object.vm_object;
3225 			if (object == NULL) {
3226 				object = vm_object_allocate(OBJT_DEFAULT,
3227 					atop(old_entry->end - old_entry->start));
3228 				old_entry->object.vm_object = object;
3229 				old_entry->offset = 0;
3230 				if (old_entry->cred != NULL) {
3231 					object->cred = old_entry->cred;
3232 					object->charge = old_entry->end -
3233 					    old_entry->start;
3234 					old_entry->cred = NULL;
3235 				}
3236 			}
3237 
3238 			/*
3239 			 * Add the reference before calling vm_object_shadow
3240 			 * to insure that a shadow object is created.
3241 			 */
3242 			vm_object_reference(object);
3243 			if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3244 				vm_object_shadow(&old_entry->object.vm_object,
3245 				    &old_entry->offset,
3246 				    old_entry->end - old_entry->start);
3247 				old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
3248 				/* Transfer the second reference too. */
3249 				vm_object_reference(
3250 				    old_entry->object.vm_object);
3251 
3252 				/*
3253 				 * As in vm_map_simplify_entry(), the
3254 				 * vnode lock will not be acquired in
3255 				 * this call to vm_object_deallocate().
3256 				 */
3257 				vm_object_deallocate(object);
3258 				object = old_entry->object.vm_object;
3259 			}
3260 			VM_OBJECT_WLOCK(object);
3261 			vm_object_clear_flag(object, OBJ_ONEMAPPING);
3262 			if (old_entry->cred != NULL) {
3263 				KASSERT(object->cred == NULL, ("vmspace_fork both cred"));
3264 				object->cred = old_entry->cred;
3265 				object->charge = old_entry->end - old_entry->start;
3266 				old_entry->cred = NULL;
3267 			}
3268 
3269 			/*
3270 			 * Assert the correct state of the vnode
3271 			 * v_writecount while the object is locked, to
3272 			 * not relock it later for the assertion
3273 			 * correctness.
3274 			 */
3275 			if (old_entry->eflags & MAP_ENTRY_VN_WRITECNT &&
3276 			    object->type == OBJT_VNODE) {
3277 				KASSERT(((struct vnode *)object->handle)->
3278 				    v_writecount > 0,
3279 				    ("vmspace_fork: v_writecount %p", object));
3280 				KASSERT(object->un_pager.vnp.writemappings > 0,
3281 				    ("vmspace_fork: vnp.writecount %p",
3282 				    object));
3283 			}
3284 			VM_OBJECT_WUNLOCK(object);
3285 
3286 			/*
3287 			 * Clone the entry, referencing the shared object.
3288 			 */
3289 			new_entry = vm_map_entry_create(new_map);
3290 			*new_entry = *old_entry;
3291 			new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
3292 			    MAP_ENTRY_IN_TRANSITION);
3293 			new_entry->wiring_thread = NULL;
3294 			new_entry->wired_count = 0;
3295 			if (new_entry->eflags & MAP_ENTRY_VN_WRITECNT) {
3296 				vnode_pager_update_writecount(object,
3297 				    new_entry->start, new_entry->end);
3298 			}
3299 
3300 			/*
3301 			 * Insert the entry into the new map -- we know we're
3302 			 * inserting at the end of the new map.
3303 			 */
3304 			vm_map_entry_link(new_map, new_map->header.prev,
3305 			    new_entry);
3306 			vmspace_map_entry_forked(vm1, vm2, new_entry);
3307 
3308 			/*
3309 			 * Update the physical map
3310 			 */
3311 			pmap_copy(new_map->pmap, old_map->pmap,
3312 			    new_entry->start,
3313 			    (old_entry->end - old_entry->start),
3314 			    old_entry->start);
3315 			break;
3316 
3317 		case VM_INHERIT_COPY:
3318 			/*
3319 			 * Clone the entry and link into the map.
3320 			 */
3321 			new_entry = vm_map_entry_create(new_map);
3322 			*new_entry = *old_entry;
3323 			/*
3324 			 * Copied entry is COW over the old object.
3325 			 */
3326 			new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
3327 			    MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_VN_WRITECNT);
3328 			new_entry->wiring_thread = NULL;
3329 			new_entry->wired_count = 0;
3330 			new_entry->object.vm_object = NULL;
3331 			new_entry->cred = NULL;
3332 			vm_map_entry_link(new_map, new_map->header.prev,
3333 			    new_entry);
3334 			vmspace_map_entry_forked(vm1, vm2, new_entry);
3335 			vm_map_copy_entry(old_map, new_map, old_entry,
3336 			    new_entry, fork_charge);
3337 			break;
3338 		}
3339 		old_entry = old_entry->next;
3340 	}
3341 	/*
3342 	 * Use inlined vm_map_unlock() to postpone handling the deferred
3343 	 * map entries, which cannot be done until both old_map and
3344 	 * new_map locks are released.
3345 	 */
3346 	sx_xunlock(&old_map->lock);
3347 	sx_xunlock(&new_map->lock);
3348 	vm_map_process_deferred();
3349 
3350 	return (vm2);
3351 }
3352 
3353 int
3354 vm_map_stack(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
3355     vm_prot_t prot, vm_prot_t max, int cow)
3356 {
3357 	vm_size_t growsize, init_ssize;
3358 	rlim_t lmemlim, vmemlim;
3359 	int rv;
3360 
3361 	growsize = sgrowsiz;
3362 	init_ssize = (max_ssize < growsize) ? max_ssize : growsize;
3363 	vm_map_lock(map);
3364 	PROC_LOCK(curproc);
3365 	lmemlim = lim_cur(curproc, RLIMIT_MEMLOCK);
3366 	vmemlim = lim_cur(curproc, RLIMIT_VMEM);
3367 	PROC_UNLOCK(curproc);
3368 	if (!old_mlock && map->flags & MAP_WIREFUTURE) {
3369 		if (ptoa(pmap_wired_count(map->pmap)) + init_ssize > lmemlim) {
3370 			rv = KERN_NO_SPACE;
3371 			goto out;
3372 		}
3373 	}
3374 	/* If we would blow our VMEM resource limit, no go */
3375 	if (map->size + init_ssize > vmemlim) {
3376 		rv = KERN_NO_SPACE;
3377 		goto out;
3378 	}
3379 	rv = vm_map_stack_locked(map, addrbos, max_ssize, growsize, prot,
3380 	    max, cow);
3381 out:
3382 	vm_map_unlock(map);
3383 	return (rv);
3384 }
3385 
3386 static int
3387 vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
3388     vm_size_t growsize, vm_prot_t prot, vm_prot_t max, int cow)
3389 {
3390 	vm_map_entry_t new_entry, prev_entry;
3391 	vm_offset_t bot, top;
3392 	vm_size_t init_ssize;
3393 	int orient, rv;
3394 
3395 	/*
3396 	 * The stack orientation is piggybacked with the cow argument.
3397 	 * Extract it into orient and mask the cow argument so that we
3398 	 * don't pass it around further.
3399 	 * NOTE: We explicitly allow bi-directional stacks.
3400 	 */
3401 	orient = cow & (MAP_STACK_GROWS_DOWN|MAP_STACK_GROWS_UP);
3402 	KASSERT(orient != 0, ("No stack grow direction"));
3403 
3404 	if (addrbos < vm_map_min(map) ||
3405 	    addrbos > vm_map_max(map) ||
3406 	    addrbos + max_ssize < addrbos)
3407 		return (KERN_NO_SPACE);
3408 
3409 	init_ssize = (max_ssize < growsize) ? max_ssize : growsize;
3410 
3411 	/* If addr is already mapped, no go */
3412 	if (vm_map_lookup_entry(map, addrbos, &prev_entry))
3413 		return (KERN_NO_SPACE);
3414 
3415 	/*
3416 	 * If we can't accomodate max_ssize in the current mapping, no go.
3417 	 * However, we need to be aware that subsequent user mappings might
3418 	 * map into the space we have reserved for stack, and currently this
3419 	 * space is not protected.
3420 	 *
3421 	 * Hopefully we will at least detect this condition when we try to
3422 	 * grow the stack.
3423 	 */
3424 	if ((prev_entry->next != &map->header) &&
3425 	    (prev_entry->next->start < addrbos + max_ssize))
3426 		return (KERN_NO_SPACE);
3427 
3428 	/*
3429 	 * We initially map a stack of only init_ssize.  We will grow as
3430 	 * needed later.  Depending on the orientation of the stack (i.e.
3431 	 * the grow direction) we either map at the top of the range, the
3432 	 * bottom of the range or in the middle.
3433 	 *
3434 	 * Note: we would normally expect prot and max to be VM_PROT_ALL,
3435 	 * and cow to be 0.  Possibly we should eliminate these as input
3436 	 * parameters, and just pass these values here in the insert call.
3437 	 */
3438 	if (orient == MAP_STACK_GROWS_DOWN)
3439 		bot = addrbos + max_ssize - init_ssize;
3440 	else if (orient == MAP_STACK_GROWS_UP)
3441 		bot = addrbos;
3442 	else
3443 		bot = round_page(addrbos + max_ssize/2 - init_ssize/2);
3444 	top = bot + init_ssize;
3445 	rv = vm_map_insert(map, NULL, 0, bot, top, prot, max, cow);
3446 
3447 	/* Now set the avail_ssize amount. */
3448 	if (rv == KERN_SUCCESS) {
3449 		new_entry = prev_entry->next;
3450 		if (new_entry->end != top || new_entry->start != bot)
3451 			panic("Bad entry start/end for new stack entry");
3452 
3453 		new_entry->avail_ssize = max_ssize - init_ssize;
3454 		KASSERT((orient & MAP_STACK_GROWS_DOWN) == 0 ||
3455 		    (new_entry->eflags & MAP_ENTRY_GROWS_DOWN) != 0,
3456 		    ("new entry lacks MAP_ENTRY_GROWS_DOWN"));
3457 		KASSERT((orient & MAP_STACK_GROWS_UP) == 0 ||
3458 		    (new_entry->eflags & MAP_ENTRY_GROWS_UP) != 0,
3459 		    ("new entry lacks MAP_ENTRY_GROWS_UP"));
3460 	}
3461 
3462 	return (rv);
3463 }
3464 
3465 static int stack_guard_page = 0;
3466 SYSCTL_INT(_security_bsd, OID_AUTO, stack_guard_page, CTLFLAG_RWTUN,
3467     &stack_guard_page, 0,
3468     "Insert stack guard page ahead of the growable segments.");
3469 
3470 /* Attempts to grow a vm stack entry.  Returns KERN_SUCCESS if the
3471  * desired address is already mapped, or if we successfully grow
3472  * the stack.  Also returns KERN_SUCCESS if addr is outside the
3473  * stack range (this is strange, but preserves compatibility with
3474  * the grow function in vm_machdep.c).
3475  */
3476 int
3477 vm_map_growstack(struct proc *p, vm_offset_t addr)
3478 {
3479 	vm_map_entry_t next_entry, prev_entry;
3480 	vm_map_entry_t new_entry, stack_entry;
3481 	struct vmspace *vm = p->p_vmspace;
3482 	vm_map_t map = &vm->vm_map;
3483 	vm_offset_t end;
3484 	vm_size_t growsize;
3485 	size_t grow_amount, max_grow;
3486 	rlim_t lmemlim, stacklim, vmemlim;
3487 	int is_procstack, rv;
3488 	struct ucred *cred;
3489 #ifdef notyet
3490 	uint64_t limit;
3491 #endif
3492 #ifdef RACCT
3493 	int error;
3494 #endif
3495 
3496 Retry:
3497 	PROC_LOCK(p);
3498 	lmemlim = lim_cur(p, RLIMIT_MEMLOCK);
3499 	stacklim = lim_cur(p, RLIMIT_STACK);
3500 	vmemlim = lim_cur(p, RLIMIT_VMEM);
3501 	PROC_UNLOCK(p);
3502 
3503 	vm_map_lock_read(map);
3504 
3505 	/* If addr is already in the entry range, no need to grow.*/
3506 	if (vm_map_lookup_entry(map, addr, &prev_entry)) {
3507 		vm_map_unlock_read(map);
3508 		return (KERN_SUCCESS);
3509 	}
3510 
3511 	next_entry = prev_entry->next;
3512 	if (!(prev_entry->eflags & MAP_ENTRY_GROWS_UP)) {
3513 		/*
3514 		 * This entry does not grow upwards. Since the address lies
3515 		 * beyond this entry, the next entry (if one exists) has to
3516 		 * be a downward growable entry. The entry list header is
3517 		 * never a growable entry, so it suffices to check the flags.
3518 		 */
3519 		if (!(next_entry->eflags & MAP_ENTRY_GROWS_DOWN)) {
3520 			vm_map_unlock_read(map);
3521 			return (KERN_SUCCESS);
3522 		}
3523 		stack_entry = next_entry;
3524 	} else {
3525 		/*
3526 		 * This entry grows upward. If the next entry does not at
3527 		 * least grow downwards, this is the entry we need to grow.
3528 		 * otherwise we have two possible choices and we have to
3529 		 * select one.
3530 		 */
3531 		if (next_entry->eflags & MAP_ENTRY_GROWS_DOWN) {
3532 			/*
3533 			 * We have two choices; grow the entry closest to
3534 			 * the address to minimize the amount of growth.
3535 			 */
3536 			if (addr - prev_entry->end <= next_entry->start - addr)
3537 				stack_entry = prev_entry;
3538 			else
3539 				stack_entry = next_entry;
3540 		} else
3541 			stack_entry = prev_entry;
3542 	}
3543 
3544 	if (stack_entry == next_entry) {
3545 		KASSERT(stack_entry->eflags & MAP_ENTRY_GROWS_DOWN, ("foo"));
3546 		KASSERT(addr < stack_entry->start, ("foo"));
3547 		end = (prev_entry != &map->header) ? prev_entry->end :
3548 		    stack_entry->start - stack_entry->avail_ssize;
3549 		grow_amount = roundup(stack_entry->start - addr, PAGE_SIZE);
3550 		max_grow = stack_entry->start - end;
3551 	} else {
3552 		KASSERT(stack_entry->eflags & MAP_ENTRY_GROWS_UP, ("foo"));
3553 		KASSERT(addr >= stack_entry->end, ("foo"));
3554 		end = (next_entry != &map->header) ? next_entry->start :
3555 		    stack_entry->end + stack_entry->avail_ssize;
3556 		grow_amount = roundup(addr + 1 - stack_entry->end, PAGE_SIZE);
3557 		max_grow = end - stack_entry->end;
3558 	}
3559 
3560 	if (grow_amount > stack_entry->avail_ssize) {
3561 		vm_map_unlock_read(map);
3562 		return (KERN_NO_SPACE);
3563 	}
3564 
3565 	/*
3566 	 * If there is no longer enough space between the entries nogo, and
3567 	 * adjust the available space.  Note: this  should only happen if the
3568 	 * user has mapped into the stack area after the stack was created,
3569 	 * and is probably an error.
3570 	 *
3571 	 * This also effectively destroys any guard page the user might have
3572 	 * intended by limiting the stack size.
3573 	 */
3574 	if (grow_amount + (stack_guard_page ? PAGE_SIZE : 0) > max_grow) {
3575 		if (vm_map_lock_upgrade(map))
3576 			goto Retry;
3577 
3578 		stack_entry->avail_ssize = max_grow;
3579 
3580 		vm_map_unlock(map);
3581 		return (KERN_NO_SPACE);
3582 	}
3583 
3584 	is_procstack = (addr >= (vm_offset_t)vm->vm_maxsaddr) ? 1 : 0;
3585 
3586 	/*
3587 	 * If this is the main process stack, see if we're over the stack
3588 	 * limit.
3589 	 */
3590 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
3591 		vm_map_unlock_read(map);
3592 		return (KERN_NO_SPACE);
3593 	}
3594 #ifdef RACCT
3595 	PROC_LOCK(p);
3596 	if (is_procstack &&
3597 	    racct_set(p, RACCT_STACK, ctob(vm->vm_ssize) + grow_amount)) {
3598 		PROC_UNLOCK(p);
3599 		vm_map_unlock_read(map);
3600 		return (KERN_NO_SPACE);
3601 	}
3602 	PROC_UNLOCK(p);
3603 #endif
3604 
3605 	/* Round up the grow amount modulo sgrowsiz */
3606 	growsize = sgrowsiz;
3607 	grow_amount = roundup(grow_amount, growsize);
3608 	if (grow_amount > stack_entry->avail_ssize)
3609 		grow_amount = stack_entry->avail_ssize;
3610 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
3611 		grow_amount = trunc_page((vm_size_t)stacklim) -
3612 		    ctob(vm->vm_ssize);
3613 	}
3614 #ifdef notyet
3615 	PROC_LOCK(p);
3616 	limit = racct_get_available(p, RACCT_STACK);
3617 	PROC_UNLOCK(p);
3618 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > limit))
3619 		grow_amount = limit - ctob(vm->vm_ssize);
3620 #endif
3621 	if (!old_mlock && map->flags & MAP_WIREFUTURE) {
3622 		if (ptoa(pmap_wired_count(map->pmap)) + grow_amount > lmemlim) {
3623 			vm_map_unlock_read(map);
3624 			rv = KERN_NO_SPACE;
3625 			goto out;
3626 		}
3627 #ifdef RACCT
3628 		PROC_LOCK(p);
3629 		if (racct_set(p, RACCT_MEMLOCK,
3630 		    ptoa(pmap_wired_count(map->pmap)) + grow_amount)) {
3631 			PROC_UNLOCK(p);
3632 			vm_map_unlock_read(map);
3633 			rv = KERN_NO_SPACE;
3634 			goto out;
3635 		}
3636 		PROC_UNLOCK(p);
3637 #endif
3638 	}
3639 	/* If we would blow our VMEM resource limit, no go */
3640 	if (map->size + grow_amount > vmemlim) {
3641 		vm_map_unlock_read(map);
3642 		rv = KERN_NO_SPACE;
3643 		goto out;
3644 	}
3645 #ifdef RACCT
3646 	PROC_LOCK(p);
3647 	if (racct_set(p, RACCT_VMEM, map->size + grow_amount)) {
3648 		PROC_UNLOCK(p);
3649 		vm_map_unlock_read(map);
3650 		rv = KERN_NO_SPACE;
3651 		goto out;
3652 	}
3653 	PROC_UNLOCK(p);
3654 #endif
3655 
3656 	if (vm_map_lock_upgrade(map))
3657 		goto Retry;
3658 
3659 	if (stack_entry == next_entry) {
3660 		/*
3661 		 * Growing downward.
3662 		 */
3663 		/* Get the preliminary new entry start value */
3664 		addr = stack_entry->start - grow_amount;
3665 
3666 		/*
3667 		 * If this puts us into the previous entry, cut back our
3668 		 * growth to the available space. Also, see the note above.
3669 		 */
3670 		if (addr < end) {
3671 			stack_entry->avail_ssize = max_grow;
3672 			addr = end;
3673 			if (stack_guard_page)
3674 				addr += PAGE_SIZE;
3675 		}
3676 
3677 		rv = vm_map_insert(map, NULL, 0, addr, stack_entry->start,
3678 		    next_entry->protection, next_entry->max_protection,
3679 		    MAP_STACK_GROWS_DOWN);
3680 
3681 		/* Adjust the available stack space by the amount we grew. */
3682 		if (rv == KERN_SUCCESS) {
3683 			new_entry = prev_entry->next;
3684 			KASSERT(new_entry == stack_entry->prev, ("foo"));
3685 			KASSERT(new_entry->end == stack_entry->start, ("foo"));
3686 			KASSERT(new_entry->start == addr, ("foo"));
3687 			KASSERT((new_entry->eflags & MAP_ENTRY_GROWS_DOWN) !=
3688 			    0, ("new entry lacks MAP_ENTRY_GROWS_DOWN"));
3689 			grow_amount = new_entry->end - new_entry->start;
3690 			new_entry->avail_ssize = stack_entry->avail_ssize -
3691 			    grow_amount;
3692 			stack_entry->eflags &= ~MAP_ENTRY_GROWS_DOWN;
3693 		}
3694 	} else {
3695 		/*
3696 		 * Growing upward.
3697 		 */
3698 		addr = stack_entry->end + grow_amount;
3699 
3700 		/*
3701 		 * If this puts us into the next entry, cut back our growth
3702 		 * to the available space. Also, see the note above.
3703 		 */
3704 		if (addr > end) {
3705 			stack_entry->avail_ssize = end - stack_entry->end;
3706 			addr = end;
3707 			if (stack_guard_page)
3708 				addr -= PAGE_SIZE;
3709 		}
3710 
3711 		grow_amount = addr - stack_entry->end;
3712 		cred = stack_entry->cred;
3713 		if (cred == NULL && stack_entry->object.vm_object != NULL)
3714 			cred = stack_entry->object.vm_object->cred;
3715 		if (cred != NULL && !swap_reserve_by_cred(grow_amount, cred))
3716 			rv = KERN_NO_SPACE;
3717 		/* Grow the underlying object if applicable. */
3718 		else if (stack_entry->object.vm_object == NULL ||
3719 			 vm_object_coalesce(stack_entry->object.vm_object,
3720 			 stack_entry->offset,
3721 			 (vm_size_t)(stack_entry->end - stack_entry->start),
3722 			 (vm_size_t)grow_amount, cred != NULL)) {
3723 			map->size += (addr - stack_entry->end);
3724 			/* Update the current entry. */
3725 			stack_entry->end = addr;
3726 			stack_entry->avail_ssize -= grow_amount;
3727 			vm_map_entry_resize_free(map, stack_entry);
3728 			rv = KERN_SUCCESS;
3729 		} else
3730 			rv = KERN_FAILURE;
3731 	}
3732 
3733 	if (rv == KERN_SUCCESS && is_procstack)
3734 		vm->vm_ssize += btoc(grow_amount);
3735 
3736 	vm_map_unlock(map);
3737 
3738 	/*
3739 	 * Heed the MAP_WIREFUTURE flag if it was set for this process.
3740 	 */
3741 	if (rv == KERN_SUCCESS && (map->flags & MAP_WIREFUTURE)) {
3742 		vm_map_wire(map,
3743 		    (stack_entry == next_entry) ? addr : addr - grow_amount,
3744 		    (stack_entry == next_entry) ? stack_entry->start : addr,
3745 		    (p->p_flag & P_SYSTEM)
3746 		    ? VM_MAP_WIRE_SYSTEM|VM_MAP_WIRE_NOHOLES
3747 		    : VM_MAP_WIRE_USER|VM_MAP_WIRE_NOHOLES);
3748 	}
3749 
3750 out:
3751 #ifdef RACCT
3752 	if (rv != KERN_SUCCESS) {
3753 		PROC_LOCK(p);
3754 		error = racct_set(p, RACCT_VMEM, map->size);
3755 		KASSERT(error == 0, ("decreasing RACCT_VMEM failed"));
3756 		if (!old_mlock) {
3757 			error = racct_set(p, RACCT_MEMLOCK,
3758 			    ptoa(pmap_wired_count(map->pmap)));
3759 			KASSERT(error == 0, ("decreasing RACCT_MEMLOCK failed"));
3760 		}
3761 	    	error = racct_set(p, RACCT_STACK, ctob(vm->vm_ssize));
3762 		KASSERT(error == 0, ("decreasing RACCT_STACK failed"));
3763 		PROC_UNLOCK(p);
3764 	}
3765 #endif
3766 
3767 	return (rv);
3768 }
3769 
3770 /*
3771  * Unshare the specified VM space for exec.  If other processes are
3772  * mapped to it, then create a new one.  The new vmspace is null.
3773  */
3774 int
3775 vmspace_exec(struct proc *p, vm_offset_t minuser, vm_offset_t maxuser)
3776 {
3777 	struct vmspace *oldvmspace = p->p_vmspace;
3778 	struct vmspace *newvmspace;
3779 
3780 	KASSERT((curthread->td_pflags & TDP_EXECVMSPC) == 0,
3781 	    ("vmspace_exec recursed"));
3782 	newvmspace = vmspace_alloc(minuser, maxuser, NULL);
3783 	if (newvmspace == NULL)
3784 		return (ENOMEM);
3785 	newvmspace->vm_swrss = oldvmspace->vm_swrss;
3786 	/*
3787 	 * This code is written like this for prototype purposes.  The
3788 	 * goal is to avoid running down the vmspace here, but let the
3789 	 * other process's that are still using the vmspace to finally
3790 	 * run it down.  Even though there is little or no chance of blocking
3791 	 * here, it is a good idea to keep this form for future mods.
3792 	 */
3793 	PROC_VMSPACE_LOCK(p);
3794 	p->p_vmspace = newvmspace;
3795 	PROC_VMSPACE_UNLOCK(p);
3796 	if (p == curthread->td_proc)
3797 		pmap_activate(curthread);
3798 	curthread->td_pflags |= TDP_EXECVMSPC;
3799 	return (0);
3800 }
3801 
3802 /*
3803  * Unshare the specified VM space for forcing COW.  This
3804  * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
3805  */
3806 int
3807 vmspace_unshare(struct proc *p)
3808 {
3809 	struct vmspace *oldvmspace = p->p_vmspace;
3810 	struct vmspace *newvmspace;
3811 	vm_ooffset_t fork_charge;
3812 
3813 	if (oldvmspace->vm_refcnt == 1)
3814 		return (0);
3815 	fork_charge = 0;
3816 	newvmspace = vmspace_fork(oldvmspace, &fork_charge);
3817 	if (newvmspace == NULL)
3818 		return (ENOMEM);
3819 	if (!swap_reserve_by_cred(fork_charge, p->p_ucred)) {
3820 		vmspace_free(newvmspace);
3821 		return (ENOMEM);
3822 	}
3823 	PROC_VMSPACE_LOCK(p);
3824 	p->p_vmspace = newvmspace;
3825 	PROC_VMSPACE_UNLOCK(p);
3826 	if (p == curthread->td_proc)
3827 		pmap_activate(curthread);
3828 	vmspace_free(oldvmspace);
3829 	return (0);
3830 }
3831 
3832 /*
3833  *	vm_map_lookup:
3834  *
3835  *	Finds the VM object, offset, and
3836  *	protection for a given virtual address in the
3837  *	specified map, assuming a page fault of the
3838  *	type specified.
3839  *
3840  *	Leaves the map in question locked for read; return
3841  *	values are guaranteed until a vm_map_lookup_done
3842  *	call is performed.  Note that the map argument
3843  *	is in/out; the returned map must be used in
3844  *	the call to vm_map_lookup_done.
3845  *
3846  *	A handle (out_entry) is returned for use in
3847  *	vm_map_lookup_done, to make that fast.
3848  *
3849  *	If a lookup is requested with "write protection"
3850  *	specified, the map may be changed to perform virtual
3851  *	copying operations, although the data referenced will
3852  *	remain the same.
3853  */
3854 int
3855 vm_map_lookup(vm_map_t *var_map,		/* IN/OUT */
3856 	      vm_offset_t vaddr,
3857 	      vm_prot_t fault_typea,
3858 	      vm_map_entry_t *out_entry,	/* OUT */
3859 	      vm_object_t *object,		/* OUT */
3860 	      vm_pindex_t *pindex,		/* OUT */
3861 	      vm_prot_t *out_prot,		/* OUT */
3862 	      boolean_t *wired)			/* OUT */
3863 {
3864 	vm_map_entry_t entry;
3865 	vm_map_t map = *var_map;
3866 	vm_prot_t prot;
3867 	vm_prot_t fault_type = fault_typea;
3868 	vm_object_t eobject;
3869 	vm_size_t size;
3870 	struct ucred *cred;
3871 
3872 RetryLookup:;
3873 
3874 	vm_map_lock_read(map);
3875 
3876 	/*
3877 	 * Lookup the faulting address.
3878 	 */
3879 	if (!vm_map_lookup_entry(map, vaddr, out_entry)) {
3880 		vm_map_unlock_read(map);
3881 		return (KERN_INVALID_ADDRESS);
3882 	}
3883 
3884 	entry = *out_entry;
3885 
3886 	/*
3887 	 * Handle submaps.
3888 	 */
3889 	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
3890 		vm_map_t old_map = map;
3891 
3892 		*var_map = map = entry->object.sub_map;
3893 		vm_map_unlock_read(old_map);
3894 		goto RetryLookup;
3895 	}
3896 
3897 	/*
3898 	 * Check whether this task is allowed to have this page.
3899 	 */
3900 	prot = entry->protection;
3901 	fault_type &= (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE);
3902 	if ((fault_type & prot) != fault_type || prot == VM_PROT_NONE) {
3903 		vm_map_unlock_read(map);
3904 		return (KERN_PROTECTION_FAILURE);
3905 	}
3906 	if ((entry->eflags & MAP_ENTRY_USER_WIRED) &&
3907 	    (entry->eflags & MAP_ENTRY_COW) &&
3908 	    (fault_type & VM_PROT_WRITE)) {
3909 		vm_map_unlock_read(map);
3910 		return (KERN_PROTECTION_FAILURE);
3911 	}
3912 	if ((fault_typea & VM_PROT_COPY) != 0 &&
3913 	    (entry->max_protection & VM_PROT_WRITE) == 0 &&
3914 	    (entry->eflags & MAP_ENTRY_COW) == 0) {
3915 		vm_map_unlock_read(map);
3916 		return (KERN_PROTECTION_FAILURE);
3917 	}
3918 
3919 	/*
3920 	 * If this page is not pageable, we have to get it for all possible
3921 	 * accesses.
3922 	 */
3923 	*wired = (entry->wired_count != 0);
3924 	if (*wired)
3925 		fault_type = entry->protection;
3926 	size = entry->end - entry->start;
3927 	/*
3928 	 * If the entry was copy-on-write, we either ...
3929 	 */
3930 	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3931 		/*
3932 		 * If we want to write the page, we may as well handle that
3933 		 * now since we've got the map locked.
3934 		 *
3935 		 * If we don't need to write the page, we just demote the
3936 		 * permissions allowed.
3937 		 */
3938 		if ((fault_type & VM_PROT_WRITE) != 0 ||
3939 		    (fault_typea & VM_PROT_COPY) != 0) {
3940 			/*
3941 			 * Make a new object, and place it in the object
3942 			 * chain.  Note that no new references have appeared
3943 			 * -- one just moved from the map to the new
3944 			 * object.
3945 			 */
3946 			if (vm_map_lock_upgrade(map))
3947 				goto RetryLookup;
3948 
3949 			if (entry->cred == NULL) {
3950 				/*
3951 				 * The debugger owner is charged for
3952 				 * the memory.
3953 				 */
3954 				cred = curthread->td_ucred;
3955 				crhold(cred);
3956 				if (!swap_reserve_by_cred(size, cred)) {
3957 					crfree(cred);
3958 					vm_map_unlock(map);
3959 					return (KERN_RESOURCE_SHORTAGE);
3960 				}
3961 				entry->cred = cred;
3962 			}
3963 			vm_object_shadow(&entry->object.vm_object,
3964 			    &entry->offset, size);
3965 			entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
3966 			eobject = entry->object.vm_object;
3967 			if (eobject->cred != NULL) {
3968 				/*
3969 				 * The object was not shadowed.
3970 				 */
3971 				swap_release_by_cred(size, entry->cred);
3972 				crfree(entry->cred);
3973 				entry->cred = NULL;
3974 			} else if (entry->cred != NULL) {
3975 				VM_OBJECT_WLOCK(eobject);
3976 				eobject->cred = entry->cred;
3977 				eobject->charge = size;
3978 				VM_OBJECT_WUNLOCK(eobject);
3979 				entry->cred = NULL;
3980 			}
3981 
3982 			vm_map_lock_downgrade(map);
3983 		} else {
3984 			/*
3985 			 * We're attempting to read a copy-on-write page --
3986 			 * don't allow writes.
3987 			 */
3988 			prot &= ~VM_PROT_WRITE;
3989 		}
3990 	}
3991 
3992 	/*
3993 	 * Create an object if necessary.
3994 	 */
3995 	if (entry->object.vm_object == NULL &&
3996 	    !map->system_map) {
3997 		if (vm_map_lock_upgrade(map))
3998 			goto RetryLookup;
3999 		entry->object.vm_object = vm_object_allocate(OBJT_DEFAULT,
4000 		    atop(size));
4001 		entry->offset = 0;
4002 		if (entry->cred != NULL) {
4003 			VM_OBJECT_WLOCK(entry->object.vm_object);
4004 			entry->object.vm_object->cred = entry->cred;
4005 			entry->object.vm_object->charge = size;
4006 			VM_OBJECT_WUNLOCK(entry->object.vm_object);
4007 			entry->cred = NULL;
4008 		}
4009 		vm_map_lock_downgrade(map);
4010 	}
4011 
4012 	/*
4013 	 * Return the object/offset from this entry.  If the entry was
4014 	 * copy-on-write or empty, it has been fixed up.
4015 	 */
4016 	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4017 	*object = entry->object.vm_object;
4018 
4019 	*out_prot = prot;
4020 	return (KERN_SUCCESS);
4021 }
4022 
4023 /*
4024  *	vm_map_lookup_locked:
4025  *
4026  *	Lookup the faulting address.  A version of vm_map_lookup that returns
4027  *      KERN_FAILURE instead of blocking on map lock or memory allocation.
4028  */
4029 int
4030 vm_map_lookup_locked(vm_map_t *var_map,		/* IN/OUT */
4031 		     vm_offset_t vaddr,
4032 		     vm_prot_t fault_typea,
4033 		     vm_map_entry_t *out_entry,	/* OUT */
4034 		     vm_object_t *object,	/* OUT */
4035 		     vm_pindex_t *pindex,	/* OUT */
4036 		     vm_prot_t *out_prot,	/* OUT */
4037 		     boolean_t *wired)		/* OUT */
4038 {
4039 	vm_map_entry_t entry;
4040 	vm_map_t map = *var_map;
4041 	vm_prot_t prot;
4042 	vm_prot_t fault_type = fault_typea;
4043 
4044 	/*
4045 	 * Lookup the faulting address.
4046 	 */
4047 	if (!vm_map_lookup_entry(map, vaddr, out_entry))
4048 		return (KERN_INVALID_ADDRESS);
4049 
4050 	entry = *out_entry;
4051 
4052 	/*
4053 	 * Fail if the entry refers to a submap.
4054 	 */
4055 	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
4056 		return (KERN_FAILURE);
4057 
4058 	/*
4059 	 * Check whether this task is allowed to have this page.
4060 	 */
4061 	prot = entry->protection;
4062 	fault_type &= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
4063 	if ((fault_type & prot) != fault_type)
4064 		return (KERN_PROTECTION_FAILURE);
4065 	if ((entry->eflags & MAP_ENTRY_USER_WIRED) &&
4066 	    (entry->eflags & MAP_ENTRY_COW) &&
4067 	    (fault_type & VM_PROT_WRITE))
4068 		return (KERN_PROTECTION_FAILURE);
4069 
4070 	/*
4071 	 * If this page is not pageable, we have to get it for all possible
4072 	 * accesses.
4073 	 */
4074 	*wired = (entry->wired_count != 0);
4075 	if (*wired)
4076 		fault_type = entry->protection;
4077 
4078 	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4079 		/*
4080 		 * Fail if the entry was copy-on-write for a write fault.
4081 		 */
4082 		if (fault_type & VM_PROT_WRITE)
4083 			return (KERN_FAILURE);
4084 		/*
4085 		 * We're attempting to read a copy-on-write page --
4086 		 * don't allow writes.
4087 		 */
4088 		prot &= ~VM_PROT_WRITE;
4089 	}
4090 
4091 	/*
4092 	 * Fail if an object should be created.
4093 	 */
4094 	if (entry->object.vm_object == NULL && !map->system_map)
4095 		return (KERN_FAILURE);
4096 
4097 	/*
4098 	 * Return the object/offset from this entry.  If the entry was
4099 	 * copy-on-write or empty, it has been fixed up.
4100 	 */
4101 	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4102 	*object = entry->object.vm_object;
4103 
4104 	*out_prot = prot;
4105 	return (KERN_SUCCESS);
4106 }
4107 
4108 /*
4109  *	vm_map_lookup_done:
4110  *
4111  *	Releases locks acquired by a vm_map_lookup
4112  *	(according to the handle returned by that lookup).
4113  */
4114 void
4115 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry)
4116 {
4117 	/*
4118 	 * Unlock the main-level map
4119 	 */
4120 	vm_map_unlock_read(map);
4121 }
4122 
4123 #include "opt_ddb.h"
4124 #ifdef DDB
4125 #include <sys/kernel.h>
4126 
4127 #include <ddb/ddb.h>
4128 
4129 static void
4130 vm_map_print(vm_map_t map)
4131 {
4132 	vm_map_entry_t entry;
4133 
4134 	db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
4135 	    (void *)map,
4136 	    (void *)map->pmap, map->nentries, map->timestamp);
4137 
4138 	db_indent += 2;
4139 	for (entry = map->header.next; entry != &map->header;
4140 	    entry = entry->next) {
4141 		db_iprintf("map entry %p: start=%p, end=%p\n",
4142 		    (void *)entry, (void *)entry->start, (void *)entry->end);
4143 		{
4144 			static char *inheritance_name[4] =
4145 			{"share", "copy", "none", "donate_copy"};
4146 
4147 			db_iprintf(" prot=%x/%x/%s",
4148 			    entry->protection,
4149 			    entry->max_protection,
4150 			    inheritance_name[(int)(unsigned char)entry->inheritance]);
4151 			if (entry->wired_count != 0)
4152 				db_printf(", wired");
4153 		}
4154 		if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
4155 			db_printf(", share=%p, offset=0x%jx\n",
4156 			    (void *)entry->object.sub_map,
4157 			    (uintmax_t)entry->offset);
4158 			if ((entry->prev == &map->header) ||
4159 			    (entry->prev->object.sub_map !=
4160 				entry->object.sub_map)) {
4161 				db_indent += 2;
4162 				vm_map_print((vm_map_t)entry->object.sub_map);
4163 				db_indent -= 2;
4164 			}
4165 		} else {
4166 			if (entry->cred != NULL)
4167 				db_printf(", ruid %d", entry->cred->cr_ruid);
4168 			db_printf(", object=%p, offset=0x%jx",
4169 			    (void *)entry->object.vm_object,
4170 			    (uintmax_t)entry->offset);
4171 			if (entry->object.vm_object && entry->object.vm_object->cred)
4172 				db_printf(", obj ruid %d charge %jx",
4173 				    entry->object.vm_object->cred->cr_ruid,
4174 				    (uintmax_t)entry->object.vm_object->charge);
4175 			if (entry->eflags & MAP_ENTRY_COW)
4176 				db_printf(", copy (%s)",
4177 				    (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
4178 			db_printf("\n");
4179 
4180 			if ((entry->prev == &map->header) ||
4181 			    (entry->prev->object.vm_object !=
4182 				entry->object.vm_object)) {
4183 				db_indent += 2;
4184 				vm_object_print((db_expr_t)(intptr_t)
4185 						entry->object.vm_object,
4186 						0, 0, (char *)0);
4187 				db_indent -= 2;
4188 			}
4189 		}
4190 	}
4191 	db_indent -= 2;
4192 }
4193 
4194 DB_SHOW_COMMAND(map, map)
4195 {
4196 
4197 	if (!have_addr) {
4198 		db_printf("usage: show map <addr>\n");
4199 		return;
4200 	}
4201 	vm_map_print((vm_map_t)addr);
4202 }
4203 
4204 DB_SHOW_COMMAND(procvm, procvm)
4205 {
4206 	struct proc *p;
4207 
4208 	if (have_addr) {
4209 		p = (struct proc *) addr;
4210 	} else {
4211 		p = curproc;
4212 	}
4213 
4214 	db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
4215 	    (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
4216 	    (void *)vmspace_pmap(p->p_vmspace));
4217 
4218 	vm_map_print((vm_map_t)&p->p_vmspace->vm_map);
4219 }
4220 
4221 #endif /* DDB */
4222