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