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