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