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