vm_map.c revision 267956
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 267956 2014-06-27 11:42:51Z 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
1806 */
1807#define	MAX_INIT_PT	96
1808
1809/*
1810 *	vm_map_pmap_enter:
1811 *
1812 *	Preload read-only mappings for the specified object's resident pages
1813 *	into the target map.  If "flags" is MAP_PREFAULT_PARTIAL, then only
1814 *	the resident pages within the address range [addr, addr + ulmin(size,
1815 *	ptoa(MAX_INIT_PT))) are mapped.  Otherwise, all resident pages within
1816 *	the specified address range are mapped.  This eliminates many soft
1817 *	faults on process startup and immediately after an mmap(2).  Because
1818 *	these are speculative mappings, cached pages are not reactivated and
1819 *	mapped.
1820 */
1821void
1822vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
1823    vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags)
1824{
1825	vm_offset_t start;
1826	vm_page_t p, p_start;
1827	vm_pindex_t psize, tmpidx;
1828
1829	if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0 || object == NULL)
1830		return;
1831	VM_OBJECT_RLOCK(object);
1832	if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
1833		VM_OBJECT_RUNLOCK(object);
1834		VM_OBJECT_WLOCK(object);
1835		if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
1836			pmap_object_init_pt(map->pmap, addr, object, pindex,
1837			    size);
1838			VM_OBJECT_WUNLOCK(object);
1839			return;
1840		}
1841		VM_OBJECT_LOCK_DOWNGRADE(object);
1842	}
1843
1844	psize = atop(size);
1845	if (psize > MAX_INIT_PT && (flags & MAP_PREFAULT_PARTIAL) != 0)
1846		psize = MAX_INIT_PT;
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
1858	p = vm_page_find_least(object, pindex);
1859	/*
1860	 * Assert: the variable p is either (1) the page with the
1861	 * least pindex greater than or equal to the parameter pindex
1862	 * or (2) NULL.
1863	 */
1864	for (;
1865	     p != NULL && (tmpidx = p->pindex - pindex) < psize;
1866	     p = TAILQ_NEXT(p, listq)) {
1867		/*
1868		 * don't allow an madvise to blow away our really
1869		 * free pages allocating pv entries.
1870		 */
1871		if ((flags & MAP_PREFAULT_MADVISE) &&
1872		    cnt.v_free_count < cnt.v_free_reserved) {
1873			psize = tmpidx;
1874			break;
1875		}
1876		if (p->valid == VM_PAGE_BITS_ALL) {
1877			if (p_start == NULL) {
1878				start = addr + ptoa(tmpidx);
1879				p_start = p;
1880			}
1881		} else if (p_start != NULL) {
1882			pmap_enter_object(map->pmap, start, addr +
1883			    ptoa(tmpidx), p_start, prot);
1884			p_start = NULL;
1885		}
1886	}
1887	if (p_start != NULL)
1888		pmap_enter_object(map->pmap, start, addr + ptoa(psize),
1889		    p_start, prot);
1890	VM_OBJECT_RUNLOCK(object);
1891}
1892
1893/*
1894 *	vm_map_protect:
1895 *
1896 *	Sets the protection of the specified address
1897 *	region in the target map.  If "set_max" is
1898 *	specified, the maximum protection is to be set;
1899 *	otherwise, only the current protection is affected.
1900 */
1901int
1902vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
1903	       vm_prot_t new_prot, boolean_t set_max)
1904{
1905	vm_map_entry_t current, entry;
1906	vm_object_t obj;
1907	struct ucred *cred;
1908	vm_prot_t old_prot;
1909
1910	if (start == end)
1911		return (KERN_SUCCESS);
1912
1913	vm_map_lock(map);
1914
1915	VM_MAP_RANGE_CHECK(map, start, end);
1916
1917	if (vm_map_lookup_entry(map, start, &entry)) {
1918		vm_map_clip_start(map, entry, start);
1919	} else {
1920		entry = entry->next;
1921	}
1922
1923	/*
1924	 * Make a first pass to check for protection violations.
1925	 */
1926	current = entry;
1927	while ((current != &map->header) && (current->start < end)) {
1928		if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
1929			vm_map_unlock(map);
1930			return (KERN_INVALID_ARGUMENT);
1931		}
1932		if ((new_prot & current->max_protection) != new_prot) {
1933			vm_map_unlock(map);
1934			return (KERN_PROTECTION_FAILURE);
1935		}
1936		current = current->next;
1937	}
1938
1939
1940	/*
1941	 * Do an accounting pass for private read-only mappings that
1942	 * now will do cow due to allowed write (e.g. debugger sets
1943	 * breakpoint on text segment)
1944	 */
1945	for (current = entry; (current != &map->header) &&
1946	     (current->start < end); current = current->next) {
1947
1948		vm_map_clip_end(map, current, end);
1949
1950		if (set_max ||
1951		    ((new_prot & ~(current->protection)) & VM_PROT_WRITE) == 0 ||
1952		    ENTRY_CHARGED(current)) {
1953			continue;
1954		}
1955
1956		cred = curthread->td_ucred;
1957		obj = current->object.vm_object;
1958
1959		if (obj == NULL || (current->eflags & MAP_ENTRY_NEEDS_COPY)) {
1960			if (!swap_reserve(current->end - current->start)) {
1961				vm_map_unlock(map);
1962				return (KERN_RESOURCE_SHORTAGE);
1963			}
1964			crhold(cred);
1965			current->cred = cred;
1966			continue;
1967		}
1968
1969		VM_OBJECT_WLOCK(obj);
1970		if (obj->type != OBJT_DEFAULT && obj->type != OBJT_SWAP) {
1971			VM_OBJECT_WUNLOCK(obj);
1972			continue;
1973		}
1974
1975		/*
1976		 * Charge for the whole object allocation now, since
1977		 * we cannot distinguish between non-charged and
1978		 * charged clipped mapping of the same object later.
1979		 */
1980		KASSERT(obj->charge == 0,
1981		    ("vm_map_protect: object %p overcharged (entry %p)",
1982		    obj, current));
1983		if (!swap_reserve(ptoa(obj->size))) {
1984			VM_OBJECT_WUNLOCK(obj);
1985			vm_map_unlock(map);
1986			return (KERN_RESOURCE_SHORTAGE);
1987		}
1988
1989		crhold(cred);
1990		obj->cred = cred;
1991		obj->charge = ptoa(obj->size);
1992		VM_OBJECT_WUNLOCK(obj);
1993	}
1994
1995	/*
1996	 * Go back and fix up protections. [Note that clipping is not
1997	 * necessary the second time.]
1998	 */
1999	current = entry;
2000	while ((current != &map->header) && (current->start < end)) {
2001		old_prot = current->protection;
2002
2003		if (set_max)
2004			current->protection =
2005			    (current->max_protection = new_prot) &
2006			    old_prot;
2007		else
2008			current->protection = new_prot;
2009
2010		/*
2011		 * For user wired map entries, the normal lazy evaluation of
2012		 * write access upgrades through soft page faults is
2013		 * undesirable.  Instead, immediately copy any pages that are
2014		 * copy-on-write and enable write access in the physical map.
2015		 */
2016		if ((current->eflags & MAP_ENTRY_USER_WIRED) != 0 &&
2017		    (current->protection & VM_PROT_WRITE) != 0 &&
2018		    (old_prot & VM_PROT_WRITE) == 0)
2019			vm_fault_copy_entry(map, map, current, current, NULL);
2020
2021		/*
2022		 * When restricting access, update the physical map.  Worry
2023		 * about copy-on-write here.
2024		 */
2025		if ((old_prot & ~current->protection) != 0) {
2026#define MASK(entry)	(((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
2027							VM_PROT_ALL)
2028			pmap_protect(map->pmap, current->start,
2029			    current->end,
2030			    current->protection & MASK(current));
2031#undef	MASK
2032		}
2033		vm_map_simplify_entry(map, current);
2034		current = current->next;
2035	}
2036	vm_map_unlock(map);
2037	return (KERN_SUCCESS);
2038}
2039
2040/*
2041 *	vm_map_madvise:
2042 *
2043 *	This routine traverses a processes map handling the madvise
2044 *	system call.  Advisories are classified as either those effecting
2045 *	the vm_map_entry structure, or those effecting the underlying
2046 *	objects.
2047 */
2048int
2049vm_map_madvise(
2050	vm_map_t map,
2051	vm_offset_t start,
2052	vm_offset_t end,
2053	int behav)
2054{
2055	vm_map_entry_t current, entry;
2056	int modify_map = 0;
2057
2058	/*
2059	 * Some madvise calls directly modify the vm_map_entry, in which case
2060	 * we need to use an exclusive lock on the map and we need to perform
2061	 * various clipping operations.  Otherwise we only need a read-lock
2062	 * on the map.
2063	 */
2064	switch(behav) {
2065	case MADV_NORMAL:
2066	case MADV_SEQUENTIAL:
2067	case MADV_RANDOM:
2068	case MADV_NOSYNC:
2069	case MADV_AUTOSYNC:
2070	case MADV_NOCORE:
2071	case MADV_CORE:
2072		if (start == end)
2073			return (KERN_SUCCESS);
2074		modify_map = 1;
2075		vm_map_lock(map);
2076		break;
2077	case MADV_WILLNEED:
2078	case MADV_DONTNEED:
2079	case MADV_FREE:
2080		if (start == end)
2081			return (KERN_SUCCESS);
2082		vm_map_lock_read(map);
2083		break;
2084	default:
2085		return (KERN_INVALID_ARGUMENT);
2086	}
2087
2088	/*
2089	 * Locate starting entry and clip if necessary.
2090	 */
2091	VM_MAP_RANGE_CHECK(map, start, end);
2092
2093	if (vm_map_lookup_entry(map, start, &entry)) {
2094		if (modify_map)
2095			vm_map_clip_start(map, entry, start);
2096	} else {
2097		entry = entry->next;
2098	}
2099
2100	if (modify_map) {
2101		/*
2102		 * madvise behaviors that are implemented in the vm_map_entry.
2103		 *
2104		 * We clip the vm_map_entry so that behavioral changes are
2105		 * limited to the specified address range.
2106		 */
2107		for (current = entry;
2108		     (current != &map->header) && (current->start < end);
2109		     current = current->next
2110		) {
2111			if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
2112				continue;
2113
2114			vm_map_clip_end(map, current, end);
2115
2116			switch (behav) {
2117			case MADV_NORMAL:
2118				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_NORMAL);
2119				break;
2120			case MADV_SEQUENTIAL:
2121				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_SEQUENTIAL);
2122				break;
2123			case MADV_RANDOM:
2124				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_RANDOM);
2125				break;
2126			case MADV_NOSYNC:
2127				current->eflags |= MAP_ENTRY_NOSYNC;
2128				break;
2129			case MADV_AUTOSYNC:
2130				current->eflags &= ~MAP_ENTRY_NOSYNC;
2131				break;
2132			case MADV_NOCORE:
2133				current->eflags |= MAP_ENTRY_NOCOREDUMP;
2134				break;
2135			case MADV_CORE:
2136				current->eflags &= ~MAP_ENTRY_NOCOREDUMP;
2137				break;
2138			default:
2139				break;
2140			}
2141			vm_map_simplify_entry(map, current);
2142		}
2143		vm_map_unlock(map);
2144	} else {
2145		vm_pindex_t pstart, pend;
2146
2147		/*
2148		 * madvise behaviors that are implemented in the underlying
2149		 * vm_object.
2150		 *
2151		 * Since we don't clip the vm_map_entry, we have to clip
2152		 * the vm_object pindex and count.
2153		 */
2154		for (current = entry;
2155		     (current != &map->header) && (current->start < end);
2156		     current = current->next
2157		) {
2158			vm_offset_t useEnd, useStart;
2159
2160			if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
2161				continue;
2162
2163			pstart = OFF_TO_IDX(current->offset);
2164			pend = pstart + atop(current->end - current->start);
2165			useStart = current->start;
2166			useEnd = current->end;
2167
2168			if (current->start < start) {
2169				pstart += atop(start - current->start);
2170				useStart = start;
2171			}
2172			if (current->end > end) {
2173				pend -= atop(current->end - end);
2174				useEnd = end;
2175			}
2176
2177			if (pstart >= pend)
2178				continue;
2179
2180			/*
2181			 * Perform the pmap_advise() before clearing
2182			 * PGA_REFERENCED in vm_page_advise().  Otherwise, a
2183			 * concurrent pmap operation, such as pmap_remove(),
2184			 * could clear a reference in the pmap and set
2185			 * PGA_REFERENCED on the page before the pmap_advise()
2186			 * had completed.  Consequently, the page would appear
2187			 * referenced based upon an old reference that
2188			 * occurred before this pmap_advise() ran.
2189			 */
2190			if (behav == MADV_DONTNEED || behav == MADV_FREE)
2191				pmap_advise(map->pmap, useStart, useEnd,
2192				    behav);
2193
2194			vm_object_madvise(current->object.vm_object, pstart,
2195			    pend, behav);
2196			if (behav == MADV_WILLNEED) {
2197				vm_map_pmap_enter(map,
2198				    useStart,
2199				    current->protection,
2200				    current->object.vm_object,
2201				    pstart,
2202				    ptoa(pend - pstart),
2203				    MAP_PREFAULT_MADVISE
2204				);
2205			}
2206		}
2207		vm_map_unlock_read(map);
2208	}
2209	return (0);
2210}
2211
2212
2213/*
2214 *	vm_map_inherit:
2215 *
2216 *	Sets the inheritance of the specified address
2217 *	range in the target map.  Inheritance
2218 *	affects how the map will be shared with
2219 *	child maps at the time of vmspace_fork.
2220 */
2221int
2222vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
2223	       vm_inherit_t new_inheritance)
2224{
2225	vm_map_entry_t entry;
2226	vm_map_entry_t temp_entry;
2227
2228	switch (new_inheritance) {
2229	case VM_INHERIT_NONE:
2230	case VM_INHERIT_COPY:
2231	case VM_INHERIT_SHARE:
2232		break;
2233	default:
2234		return (KERN_INVALID_ARGUMENT);
2235	}
2236	if (start == end)
2237		return (KERN_SUCCESS);
2238	vm_map_lock(map);
2239	VM_MAP_RANGE_CHECK(map, start, end);
2240	if (vm_map_lookup_entry(map, start, &temp_entry)) {
2241		entry = temp_entry;
2242		vm_map_clip_start(map, entry, start);
2243	} else
2244		entry = temp_entry->next;
2245	while ((entry != &map->header) && (entry->start < end)) {
2246		vm_map_clip_end(map, entry, end);
2247		entry->inheritance = new_inheritance;
2248		vm_map_simplify_entry(map, entry);
2249		entry = entry->next;
2250	}
2251	vm_map_unlock(map);
2252	return (KERN_SUCCESS);
2253}
2254
2255/*
2256 *	vm_map_unwire:
2257 *
2258 *	Implements both kernel and user unwiring.
2259 */
2260int
2261vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t end,
2262    int flags)
2263{
2264	vm_map_entry_t entry, first_entry, tmp_entry;
2265	vm_offset_t saved_start;
2266	unsigned int last_timestamp;
2267	int rv;
2268	boolean_t need_wakeup, result, user_unwire;
2269
2270	if (start == end)
2271		return (KERN_SUCCESS);
2272	user_unwire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
2273	vm_map_lock(map);
2274	VM_MAP_RANGE_CHECK(map, start, end);
2275	if (!vm_map_lookup_entry(map, start, &first_entry)) {
2276		if (flags & VM_MAP_WIRE_HOLESOK)
2277			first_entry = first_entry->next;
2278		else {
2279			vm_map_unlock(map);
2280			return (KERN_INVALID_ADDRESS);
2281		}
2282	}
2283	last_timestamp = map->timestamp;
2284	entry = first_entry;
2285	while (entry != &map->header && entry->start < end) {
2286		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
2287			/*
2288			 * We have not yet clipped the entry.
2289			 */
2290			saved_start = (start >= entry->start) ? start :
2291			    entry->start;
2292			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2293			if (vm_map_unlock_and_wait(map, 0)) {
2294				/*
2295				 * Allow interruption of user unwiring?
2296				 */
2297			}
2298			vm_map_lock(map);
2299			if (last_timestamp+1 != map->timestamp) {
2300				/*
2301				 * Look again for the entry because the map was
2302				 * modified while it was unlocked.
2303				 * Specifically, the entry may have been
2304				 * clipped, merged, or deleted.
2305				 */
2306				if (!vm_map_lookup_entry(map, saved_start,
2307				    &tmp_entry)) {
2308					if (flags & VM_MAP_WIRE_HOLESOK)
2309						tmp_entry = tmp_entry->next;
2310					else {
2311						if (saved_start == start) {
2312							/*
2313							 * First_entry has been deleted.
2314							 */
2315							vm_map_unlock(map);
2316							return (KERN_INVALID_ADDRESS);
2317						}
2318						end = saved_start;
2319						rv = KERN_INVALID_ADDRESS;
2320						goto done;
2321					}
2322				}
2323				if (entry == first_entry)
2324					first_entry = tmp_entry;
2325				else
2326					first_entry = NULL;
2327				entry = tmp_entry;
2328			}
2329			last_timestamp = map->timestamp;
2330			continue;
2331		}
2332		vm_map_clip_start(map, entry, start);
2333		vm_map_clip_end(map, entry, end);
2334		/*
2335		 * Mark the entry in case the map lock is released.  (See
2336		 * above.)
2337		 */
2338		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
2339		    entry->wiring_thread == NULL,
2340		    ("owned map entry %p", entry));
2341		entry->eflags |= MAP_ENTRY_IN_TRANSITION;
2342		entry->wiring_thread = curthread;
2343		/*
2344		 * Check the map for holes in the specified region.
2345		 * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
2346		 */
2347		if (((flags & VM_MAP_WIRE_HOLESOK) == 0) &&
2348		    (entry->end < end && (entry->next == &map->header ||
2349		    entry->next->start > entry->end))) {
2350			end = entry->end;
2351			rv = KERN_INVALID_ADDRESS;
2352			goto done;
2353		}
2354		/*
2355		 * If system unwiring, require that the entry is system wired.
2356		 */
2357		if (!user_unwire &&
2358		    vm_map_entry_system_wired_count(entry) == 0) {
2359			end = entry->end;
2360			rv = KERN_INVALID_ARGUMENT;
2361			goto done;
2362		}
2363		entry = entry->next;
2364	}
2365	rv = KERN_SUCCESS;
2366done:
2367	need_wakeup = FALSE;
2368	if (first_entry == NULL) {
2369		result = vm_map_lookup_entry(map, start, &first_entry);
2370		if (!result && (flags & VM_MAP_WIRE_HOLESOK))
2371			first_entry = first_entry->next;
2372		else
2373			KASSERT(result, ("vm_map_unwire: lookup failed"));
2374	}
2375	for (entry = first_entry; entry != &map->header && entry->start < end;
2376	    entry = entry->next) {
2377		/*
2378		 * If VM_MAP_WIRE_HOLESOK was specified, an empty
2379		 * space in the unwired region could have been mapped
2380		 * while the map lock was dropped for draining
2381		 * MAP_ENTRY_IN_TRANSITION.  Moreover, another thread
2382		 * could be simultaneously wiring this new mapping
2383		 * entry.  Detect these cases and skip any entries
2384		 * marked as in transition by us.
2385		 */
2386		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
2387		    entry->wiring_thread != curthread) {
2388			KASSERT((flags & VM_MAP_WIRE_HOLESOK) != 0,
2389			    ("vm_map_unwire: !HOLESOK and new/changed entry"));
2390			continue;
2391		}
2392
2393		if (rv == KERN_SUCCESS && (!user_unwire ||
2394		    (entry->eflags & MAP_ENTRY_USER_WIRED))) {
2395			if (user_unwire)
2396				entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2397			entry->wired_count--;
2398			if (entry->wired_count == 0) {
2399				/*
2400				 * Retain the map lock.
2401				 */
2402				vm_fault_unwire(map, entry->start, entry->end,
2403				    entry->object.vm_object != NULL &&
2404				    (entry->object.vm_object->flags &
2405				    OBJ_FICTITIOUS) != 0);
2406			}
2407		}
2408		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
2409		    ("vm_map_unwire: in-transition flag missing %p", entry));
2410		KASSERT(entry->wiring_thread == curthread,
2411		    ("vm_map_unwire: alien wire %p", entry));
2412		entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
2413		entry->wiring_thread = NULL;
2414		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
2415			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
2416			need_wakeup = TRUE;
2417		}
2418		vm_map_simplify_entry(map, entry);
2419	}
2420	vm_map_unlock(map);
2421	if (need_wakeup)
2422		vm_map_wakeup(map);
2423	return (rv);
2424}
2425
2426/*
2427 *	vm_map_wire:
2428 *
2429 *	Implements both kernel and user wiring.
2430 */
2431int
2432vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t end,
2433    int flags)
2434{
2435	vm_map_entry_t entry, first_entry, tmp_entry;
2436	vm_offset_t saved_end, saved_start;
2437	unsigned int last_timestamp;
2438	int rv;
2439	boolean_t fictitious, need_wakeup, result, user_wire;
2440	vm_prot_t prot;
2441
2442	if (start == end)
2443		return (KERN_SUCCESS);
2444	prot = 0;
2445	if (flags & VM_MAP_WIRE_WRITE)
2446		prot |= VM_PROT_WRITE;
2447	user_wire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
2448	vm_map_lock(map);
2449	VM_MAP_RANGE_CHECK(map, start, end);
2450	if (!vm_map_lookup_entry(map, start, &first_entry)) {
2451		if (flags & VM_MAP_WIRE_HOLESOK)
2452			first_entry = first_entry->next;
2453		else {
2454			vm_map_unlock(map);
2455			return (KERN_INVALID_ADDRESS);
2456		}
2457	}
2458	last_timestamp = map->timestamp;
2459	entry = first_entry;
2460	while (entry != &map->header && entry->start < end) {
2461		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
2462			/*
2463			 * We have not yet clipped the entry.
2464			 */
2465			saved_start = (start >= entry->start) ? start :
2466			    entry->start;
2467			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2468			if (vm_map_unlock_and_wait(map, 0)) {
2469				/*
2470				 * Allow interruption of user wiring?
2471				 */
2472			}
2473			vm_map_lock(map);
2474			if (last_timestamp + 1 != map->timestamp) {
2475				/*
2476				 * Look again for the entry because the map was
2477				 * modified while it was unlocked.
2478				 * Specifically, the entry may have been
2479				 * clipped, merged, or deleted.
2480				 */
2481				if (!vm_map_lookup_entry(map, saved_start,
2482				    &tmp_entry)) {
2483					if (flags & VM_MAP_WIRE_HOLESOK)
2484						tmp_entry = tmp_entry->next;
2485					else {
2486						if (saved_start == start) {
2487							/*
2488							 * first_entry has been deleted.
2489							 */
2490							vm_map_unlock(map);
2491							return (KERN_INVALID_ADDRESS);
2492						}
2493						end = saved_start;
2494						rv = KERN_INVALID_ADDRESS;
2495						goto done;
2496					}
2497				}
2498				if (entry == first_entry)
2499					first_entry = tmp_entry;
2500				else
2501					first_entry = NULL;
2502				entry = tmp_entry;
2503			}
2504			last_timestamp = map->timestamp;
2505			continue;
2506		}
2507		vm_map_clip_start(map, entry, start);
2508		vm_map_clip_end(map, entry, end);
2509		/*
2510		 * Mark the entry in case the map lock is released.  (See
2511		 * above.)
2512		 */
2513		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
2514		    entry->wiring_thread == NULL,
2515		    ("owned map entry %p", entry));
2516		entry->eflags |= MAP_ENTRY_IN_TRANSITION;
2517		entry->wiring_thread = curthread;
2518		if ((entry->protection & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0
2519		    || (entry->protection & prot) != prot) {
2520			entry->eflags |= MAP_ENTRY_WIRE_SKIPPED;
2521			if ((flags & VM_MAP_WIRE_HOLESOK) == 0) {
2522				end = entry->end;
2523				rv = KERN_INVALID_ADDRESS;
2524				goto done;
2525			}
2526			goto next_entry;
2527		}
2528		if (entry->wired_count == 0) {
2529			entry->wired_count++;
2530			saved_start = entry->start;
2531			saved_end = entry->end;
2532			fictitious = entry->object.vm_object != NULL &&
2533			    (entry->object.vm_object->flags &
2534			    OBJ_FICTITIOUS) != 0;
2535			/*
2536			 * Release the map lock, relying on the in-transition
2537			 * mark.  Mark the map busy for fork.
2538			 */
2539			vm_map_busy(map);
2540			vm_map_unlock(map);
2541			rv = vm_fault_wire(map, saved_start, saved_end,
2542			    fictitious);
2543			vm_map_lock(map);
2544			vm_map_unbusy(map);
2545			if (last_timestamp + 1 != map->timestamp) {
2546				/*
2547				 * Look again for the entry because the map was
2548				 * modified while it was unlocked.  The entry
2549				 * may have been clipped, but NOT merged or
2550				 * deleted.
2551				 */
2552				result = vm_map_lookup_entry(map, saved_start,
2553				    &tmp_entry);
2554				KASSERT(result, ("vm_map_wire: lookup failed"));
2555				if (entry == first_entry)
2556					first_entry = tmp_entry;
2557				else
2558					first_entry = NULL;
2559				entry = tmp_entry;
2560				while (entry->end < saved_end) {
2561					if (rv != KERN_SUCCESS) {
2562						KASSERT(entry->wired_count == 1,
2563						    ("vm_map_wire: bad count"));
2564						entry->wired_count = -1;
2565					}
2566					entry = entry->next;
2567				}
2568			}
2569			last_timestamp = map->timestamp;
2570			if (rv != KERN_SUCCESS) {
2571				KASSERT(entry->wired_count == 1,
2572				    ("vm_map_wire: bad count"));
2573				/*
2574				 * Assign an out-of-range value to represent
2575				 * the failure to wire this entry.
2576				 */
2577				entry->wired_count = -1;
2578				end = entry->end;
2579				goto done;
2580			}
2581		} else if (!user_wire ||
2582			   (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
2583			entry->wired_count++;
2584		}
2585		/*
2586		 * Check the map for holes in the specified region.
2587		 * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
2588		 */
2589	next_entry:
2590		if (((flags & VM_MAP_WIRE_HOLESOK) == 0) &&
2591		    (entry->end < end && (entry->next == &map->header ||
2592		    entry->next->start > entry->end))) {
2593			end = entry->end;
2594			rv = KERN_INVALID_ADDRESS;
2595			goto done;
2596		}
2597		entry = entry->next;
2598	}
2599	rv = KERN_SUCCESS;
2600done:
2601	need_wakeup = FALSE;
2602	if (first_entry == NULL) {
2603		result = vm_map_lookup_entry(map, start, &first_entry);
2604		if (!result && (flags & VM_MAP_WIRE_HOLESOK))
2605			first_entry = first_entry->next;
2606		else
2607			KASSERT(result, ("vm_map_wire: lookup failed"));
2608	}
2609	for (entry = first_entry; entry != &map->header && entry->start < end;
2610	    entry = entry->next) {
2611		if ((entry->eflags & MAP_ENTRY_WIRE_SKIPPED) != 0)
2612			goto next_entry_done;
2613
2614		/*
2615		 * If VM_MAP_WIRE_HOLESOK was specified, an empty
2616		 * space in the unwired region could have been mapped
2617		 * while the map lock was dropped for faulting in the
2618		 * pages or draining MAP_ENTRY_IN_TRANSITION.
2619		 * Moreover, another thread could be simultaneously
2620		 * wiring this new mapping entry.  Detect these cases
2621		 * and skip any entries marked as in transition by us.
2622		 */
2623		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
2624		    entry->wiring_thread != curthread) {
2625			KASSERT((flags & VM_MAP_WIRE_HOLESOK) != 0,
2626			    ("vm_map_wire: !HOLESOK and new/changed entry"));
2627			continue;
2628		}
2629
2630		if (rv == KERN_SUCCESS) {
2631			if (user_wire)
2632				entry->eflags |= MAP_ENTRY_USER_WIRED;
2633		} else if (entry->wired_count == -1) {
2634			/*
2635			 * Wiring failed on this entry.  Thus, unwiring is
2636			 * unnecessary.
2637			 */
2638			entry->wired_count = 0;
2639		} else {
2640			if (!user_wire ||
2641			    (entry->eflags & MAP_ENTRY_USER_WIRED) == 0)
2642				entry->wired_count--;
2643			if (entry->wired_count == 0) {
2644				/*
2645				 * Retain the map lock.
2646				 */
2647				vm_fault_unwire(map, entry->start, entry->end,
2648				    entry->object.vm_object != NULL &&
2649				    (entry->object.vm_object->flags &
2650				    OBJ_FICTITIOUS) != 0);
2651			}
2652		}
2653	next_entry_done:
2654		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
2655		    ("vm_map_wire: in-transition flag missing %p", entry));
2656		KASSERT(entry->wiring_thread == curthread,
2657		    ("vm_map_wire: alien wire %p", entry));
2658		entry->eflags &= ~(MAP_ENTRY_IN_TRANSITION |
2659		    MAP_ENTRY_WIRE_SKIPPED);
2660		entry->wiring_thread = NULL;
2661		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
2662			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
2663			need_wakeup = TRUE;
2664		}
2665		vm_map_simplify_entry(map, entry);
2666	}
2667	vm_map_unlock(map);
2668	if (need_wakeup)
2669		vm_map_wakeup(map);
2670	return (rv);
2671}
2672
2673/*
2674 * vm_map_sync
2675 *
2676 * Push any dirty cached pages in the address range to their pager.
2677 * If syncio is TRUE, dirty pages are written synchronously.
2678 * If invalidate is TRUE, any cached pages are freed as well.
2679 *
2680 * If the size of the region from start to end is zero, we are
2681 * supposed to flush all modified pages within the region containing
2682 * start.  Unfortunately, a region can be split or coalesced with
2683 * neighboring regions, making it difficult to determine what the
2684 * original region was.  Therefore, we approximate this requirement by
2685 * flushing the current region containing start.
2686 *
2687 * Returns an error if any part of the specified range is not mapped.
2688 */
2689int
2690vm_map_sync(
2691	vm_map_t map,
2692	vm_offset_t start,
2693	vm_offset_t end,
2694	boolean_t syncio,
2695	boolean_t invalidate)
2696{
2697	vm_map_entry_t current;
2698	vm_map_entry_t entry;
2699	vm_size_t size;
2700	vm_object_t object;
2701	vm_ooffset_t offset;
2702	unsigned int last_timestamp;
2703	boolean_t failed;
2704
2705	vm_map_lock_read(map);
2706	VM_MAP_RANGE_CHECK(map, start, end);
2707	if (!vm_map_lookup_entry(map, start, &entry)) {
2708		vm_map_unlock_read(map);
2709		return (KERN_INVALID_ADDRESS);
2710	} else if (start == end) {
2711		start = entry->start;
2712		end = entry->end;
2713	}
2714	/*
2715	 * Make a first pass to check for user-wired memory and holes.
2716	 */
2717	for (current = entry; current != &map->header && current->start < end;
2718	    current = current->next) {
2719		if (invalidate && (current->eflags & MAP_ENTRY_USER_WIRED)) {
2720			vm_map_unlock_read(map);
2721			return (KERN_INVALID_ARGUMENT);
2722		}
2723		if (end > current->end &&
2724		    (current->next == &map->header ||
2725			current->end != current->next->start)) {
2726			vm_map_unlock_read(map);
2727			return (KERN_INVALID_ADDRESS);
2728		}
2729	}
2730
2731	if (invalidate)
2732		pmap_remove(map->pmap, start, end);
2733	failed = FALSE;
2734
2735	/*
2736	 * Make a second pass, cleaning/uncaching pages from the indicated
2737	 * objects as we go.
2738	 */
2739	for (current = entry; current != &map->header && current->start < end;) {
2740		offset = current->offset + (start - current->start);
2741		size = (end <= current->end ? end : current->end) - start;
2742		if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
2743			vm_map_t smap;
2744			vm_map_entry_t tentry;
2745			vm_size_t tsize;
2746
2747			smap = current->object.sub_map;
2748			vm_map_lock_read(smap);
2749			(void) vm_map_lookup_entry(smap, offset, &tentry);
2750			tsize = tentry->end - offset;
2751			if (tsize < size)
2752				size = tsize;
2753			object = tentry->object.vm_object;
2754			offset = tentry->offset + (offset - tentry->start);
2755			vm_map_unlock_read(smap);
2756		} else {
2757			object = current->object.vm_object;
2758		}
2759		vm_object_reference(object);
2760		last_timestamp = map->timestamp;
2761		vm_map_unlock_read(map);
2762		if (!vm_object_sync(object, offset, size, syncio, invalidate))
2763			failed = TRUE;
2764		start += size;
2765		vm_object_deallocate(object);
2766		vm_map_lock_read(map);
2767		if (last_timestamp == map->timestamp ||
2768		    !vm_map_lookup_entry(map, start, &current))
2769			current = current->next;
2770	}
2771
2772	vm_map_unlock_read(map);
2773	return (failed ? KERN_FAILURE : KERN_SUCCESS);
2774}
2775
2776/*
2777 *	vm_map_entry_unwire:	[ internal use only ]
2778 *
2779 *	Make the region specified by this entry pageable.
2780 *
2781 *	The map in question should be locked.
2782 *	[This is the reason for this routine's existence.]
2783 */
2784static void
2785vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
2786{
2787	vm_fault_unwire(map, entry->start, entry->end,
2788	    entry->object.vm_object != NULL &&
2789	    (entry->object.vm_object->flags & OBJ_FICTITIOUS) != 0);
2790	entry->wired_count = 0;
2791}
2792
2793static void
2794vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map)
2795{
2796
2797	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0)
2798		vm_object_deallocate(entry->object.vm_object);
2799	uma_zfree(system_map ? kmapentzone : mapentzone, entry);
2800}
2801
2802/*
2803 *	vm_map_entry_delete:	[ internal use only ]
2804 *
2805 *	Deallocate the given entry from the target map.
2806 */
2807static void
2808vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry)
2809{
2810	vm_object_t object;
2811	vm_pindex_t offidxstart, offidxend, count, size1;
2812	vm_ooffset_t size;
2813
2814	vm_map_entry_unlink(map, entry);
2815	object = entry->object.vm_object;
2816	size = entry->end - entry->start;
2817	map->size -= size;
2818
2819	if (entry->cred != NULL) {
2820		swap_release_by_cred(size, entry->cred);
2821		crfree(entry->cred);
2822	}
2823
2824	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0 &&
2825	    (object != NULL)) {
2826		KASSERT(entry->cred == NULL || object->cred == NULL ||
2827		    (entry->eflags & MAP_ENTRY_NEEDS_COPY),
2828		    ("OVERCOMMIT vm_map_entry_delete: both cred %p", entry));
2829		count = OFF_TO_IDX(size);
2830		offidxstart = OFF_TO_IDX(entry->offset);
2831		offidxend = offidxstart + count;
2832		VM_OBJECT_WLOCK(object);
2833		if (object->ref_count != 1 &&
2834		    ((object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING ||
2835		    object == kernel_object || object == kmem_object)) {
2836			vm_object_collapse(object);
2837
2838			/*
2839			 * The option OBJPR_NOTMAPPED can be passed here
2840			 * because vm_map_delete() already performed
2841			 * pmap_remove() on the only mapping to this range
2842			 * of pages.
2843			 */
2844			vm_object_page_remove(object, offidxstart, offidxend,
2845			    OBJPR_NOTMAPPED);
2846			if (object->type == OBJT_SWAP)
2847				swap_pager_freespace(object, offidxstart, count);
2848			if (offidxend >= object->size &&
2849			    offidxstart < object->size) {
2850				size1 = object->size;
2851				object->size = offidxstart;
2852				if (object->cred != NULL) {
2853					size1 -= object->size;
2854					KASSERT(object->charge >= ptoa(size1),
2855					    ("vm_map_entry_delete: object->charge < 0"));
2856					swap_release_by_cred(ptoa(size1), object->cred);
2857					object->charge -= ptoa(size1);
2858				}
2859			}
2860		}
2861		VM_OBJECT_WUNLOCK(object);
2862	} else
2863		entry->object.vm_object = NULL;
2864	if (map->system_map)
2865		vm_map_entry_deallocate(entry, TRUE);
2866	else {
2867		entry->next = curthread->td_map_def_user;
2868		curthread->td_map_def_user = entry;
2869	}
2870}
2871
2872/*
2873 *	vm_map_delete:	[ internal use only ]
2874 *
2875 *	Deallocates the given address range from the target
2876 *	map.
2877 */
2878int
2879vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
2880{
2881	vm_map_entry_t entry;
2882	vm_map_entry_t first_entry;
2883
2884	VM_MAP_ASSERT_LOCKED(map);
2885	if (start == end)
2886		return (KERN_SUCCESS);
2887
2888	/*
2889	 * Find the start of the region, and clip it
2890	 */
2891	if (!vm_map_lookup_entry(map, start, &first_entry))
2892		entry = first_entry->next;
2893	else {
2894		entry = first_entry;
2895		vm_map_clip_start(map, entry, start);
2896	}
2897
2898	/*
2899	 * Step through all entries in this region
2900	 */
2901	while ((entry != &map->header) && (entry->start < end)) {
2902		vm_map_entry_t next;
2903
2904		/*
2905		 * Wait for wiring or unwiring of an entry to complete.
2906		 * Also wait for any system wirings to disappear on
2907		 * user maps.
2908		 */
2909		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 ||
2910		    (vm_map_pmap(map) != kernel_pmap &&
2911		    vm_map_entry_system_wired_count(entry) != 0)) {
2912			unsigned int last_timestamp;
2913			vm_offset_t saved_start;
2914			vm_map_entry_t tmp_entry;
2915
2916			saved_start = entry->start;
2917			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2918			last_timestamp = map->timestamp;
2919			(void) vm_map_unlock_and_wait(map, 0);
2920			vm_map_lock(map);
2921			if (last_timestamp + 1 != map->timestamp) {
2922				/*
2923				 * Look again for the entry because the map was
2924				 * modified while it was unlocked.
2925				 * Specifically, the entry may have been
2926				 * clipped, merged, or deleted.
2927				 */
2928				if (!vm_map_lookup_entry(map, saved_start,
2929							 &tmp_entry))
2930					entry = tmp_entry->next;
2931				else {
2932					entry = tmp_entry;
2933					vm_map_clip_start(map, entry,
2934							  saved_start);
2935				}
2936			}
2937			continue;
2938		}
2939		vm_map_clip_end(map, entry, end);
2940
2941		next = entry->next;
2942
2943		/*
2944		 * Unwire before removing addresses from the pmap; otherwise,
2945		 * unwiring will put the entries back in the pmap.
2946		 */
2947		if (entry->wired_count != 0) {
2948			vm_map_entry_unwire(map, entry);
2949		}
2950
2951		pmap_remove(map->pmap, entry->start, entry->end);
2952
2953		/*
2954		 * Delete the entry only after removing all pmap
2955		 * entries pointing to its pages.  (Otherwise, its
2956		 * page frames may be reallocated, and any modify bits
2957		 * will be set in the wrong object!)
2958		 */
2959		vm_map_entry_delete(map, entry);
2960		entry = next;
2961	}
2962	return (KERN_SUCCESS);
2963}
2964
2965/*
2966 *	vm_map_remove:
2967 *
2968 *	Remove the given address range from the target map.
2969 *	This is the exported form of vm_map_delete.
2970 */
2971int
2972vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
2973{
2974	int result;
2975
2976	vm_map_lock(map);
2977	VM_MAP_RANGE_CHECK(map, start, end);
2978	result = vm_map_delete(map, start, end);
2979	vm_map_unlock(map);
2980	return (result);
2981}
2982
2983/*
2984 *	vm_map_check_protection:
2985 *
2986 *	Assert that the target map allows the specified privilege on the
2987 *	entire address region given.  The entire region must be allocated.
2988 *
2989 *	WARNING!  This code does not and should not check whether the
2990 *	contents of the region is accessible.  For example a smaller file
2991 *	might be mapped into a larger address space.
2992 *
2993 *	NOTE!  This code is also called by munmap().
2994 *
2995 *	The map must be locked.  A read lock is sufficient.
2996 */
2997boolean_t
2998vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
2999			vm_prot_t protection)
3000{
3001	vm_map_entry_t entry;
3002	vm_map_entry_t tmp_entry;
3003
3004	if (!vm_map_lookup_entry(map, start, &tmp_entry))
3005		return (FALSE);
3006	entry = tmp_entry;
3007
3008	while (start < end) {
3009		if (entry == &map->header)
3010			return (FALSE);
3011		/*
3012		 * No holes allowed!
3013		 */
3014		if (start < entry->start)
3015			return (FALSE);
3016		/*
3017		 * Check protection associated with entry.
3018		 */
3019		if ((entry->protection & protection) != protection)
3020			return (FALSE);
3021		/* go to next entry */
3022		start = entry->end;
3023		entry = entry->next;
3024	}
3025	return (TRUE);
3026}
3027
3028/*
3029 *	vm_map_copy_entry:
3030 *
3031 *	Copies the contents of the source entry to the destination
3032 *	entry.  The entries *must* be aligned properly.
3033 */
3034static void
3035vm_map_copy_entry(
3036	vm_map_t src_map,
3037	vm_map_t dst_map,
3038	vm_map_entry_t src_entry,
3039	vm_map_entry_t dst_entry,
3040	vm_ooffset_t *fork_charge)
3041{
3042	vm_object_t src_object;
3043	vm_map_entry_t fake_entry;
3044	vm_offset_t size;
3045	struct ucred *cred;
3046	int charged;
3047
3048	VM_MAP_ASSERT_LOCKED(dst_map);
3049
3050	if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
3051		return;
3052
3053	if (src_entry->wired_count == 0 ||
3054	    (src_entry->protection & VM_PROT_WRITE) == 0) {
3055		/*
3056		 * If the source entry is marked needs_copy, it is already
3057		 * write-protected.
3058		 */
3059		if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0 &&
3060		    (src_entry->protection & VM_PROT_WRITE) != 0) {
3061			pmap_protect(src_map->pmap,
3062			    src_entry->start,
3063			    src_entry->end,
3064			    src_entry->protection & ~VM_PROT_WRITE);
3065		}
3066
3067		/*
3068		 * Make a copy of the object.
3069		 */
3070		size = src_entry->end - src_entry->start;
3071		if ((src_object = src_entry->object.vm_object) != NULL) {
3072			VM_OBJECT_WLOCK(src_object);
3073			charged = ENTRY_CHARGED(src_entry);
3074			if ((src_object->handle == NULL) &&
3075				(src_object->type == OBJT_DEFAULT ||
3076				 src_object->type == OBJT_SWAP)) {
3077				vm_object_collapse(src_object);
3078				if ((src_object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING) {
3079					vm_object_split(src_entry);
3080					src_object = src_entry->object.vm_object;
3081				}
3082			}
3083			vm_object_reference_locked(src_object);
3084			vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
3085			if (src_entry->cred != NULL &&
3086			    !(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
3087				KASSERT(src_object->cred == NULL,
3088				    ("OVERCOMMIT: vm_map_copy_entry: cred %p",
3089				     src_object));
3090				src_object->cred = src_entry->cred;
3091				src_object->charge = size;
3092			}
3093			VM_OBJECT_WUNLOCK(src_object);
3094			dst_entry->object.vm_object = src_object;
3095			if (charged) {
3096				cred = curthread->td_ucred;
3097				crhold(cred);
3098				dst_entry->cred = cred;
3099				*fork_charge += size;
3100				if (!(src_entry->eflags &
3101				      MAP_ENTRY_NEEDS_COPY)) {
3102					crhold(cred);
3103					src_entry->cred = cred;
3104					*fork_charge += size;
3105				}
3106			}
3107			src_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
3108			dst_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
3109			dst_entry->offset = src_entry->offset;
3110			if (src_entry->eflags & MAP_ENTRY_VN_WRITECNT) {
3111				/*
3112				 * MAP_ENTRY_VN_WRITECNT cannot
3113				 * indicate write reference from
3114				 * src_entry, since the entry is
3115				 * marked as needs copy.  Allocate a
3116				 * fake entry that is used to
3117				 * decrement object->un_pager.vnp.writecount
3118				 * at the appropriate time.  Attach
3119				 * fake_entry to the deferred list.
3120				 */
3121				fake_entry = vm_map_entry_create(dst_map);
3122				fake_entry->eflags = MAP_ENTRY_VN_WRITECNT;
3123				src_entry->eflags &= ~MAP_ENTRY_VN_WRITECNT;
3124				vm_object_reference(src_object);
3125				fake_entry->object.vm_object = src_object;
3126				fake_entry->start = src_entry->start;
3127				fake_entry->end = src_entry->end;
3128				fake_entry->next = curthread->td_map_def_user;
3129				curthread->td_map_def_user = fake_entry;
3130			}
3131		} else {
3132			dst_entry->object.vm_object = NULL;
3133			dst_entry->offset = 0;
3134			if (src_entry->cred != NULL) {
3135				dst_entry->cred = curthread->td_ucred;
3136				crhold(dst_entry->cred);
3137				*fork_charge += size;
3138			}
3139		}
3140
3141		pmap_copy(dst_map->pmap, src_map->pmap, dst_entry->start,
3142		    dst_entry->end - dst_entry->start, src_entry->start);
3143	} else {
3144		/*
3145		 * We don't want to make writeable wired pages copy-on-write.
3146		 * Immediately copy these pages into the new map by simulating
3147		 * page faults.  The new pages are pageable.
3148		 */
3149		vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry,
3150		    fork_charge);
3151	}
3152}
3153
3154/*
3155 * vmspace_map_entry_forked:
3156 * Update the newly-forked vmspace each time a map entry is inherited
3157 * or copied.  The values for vm_dsize and vm_tsize are approximate
3158 * (and mostly-obsolete ideas in the face of mmap(2) et al.)
3159 */
3160static void
3161vmspace_map_entry_forked(const struct vmspace *vm1, struct vmspace *vm2,
3162    vm_map_entry_t entry)
3163{
3164	vm_size_t entrysize;
3165	vm_offset_t newend;
3166
3167	entrysize = entry->end - entry->start;
3168	vm2->vm_map.size += entrysize;
3169	if (entry->eflags & (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP)) {
3170		vm2->vm_ssize += btoc(entrysize);
3171	} else if (entry->start >= (vm_offset_t)vm1->vm_daddr &&
3172	    entry->start < (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize)) {
3173		newend = MIN(entry->end,
3174		    (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize));
3175		vm2->vm_dsize += btoc(newend - entry->start);
3176	} else if (entry->start >= (vm_offset_t)vm1->vm_taddr &&
3177	    entry->start < (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize)) {
3178		newend = MIN(entry->end,
3179		    (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize));
3180		vm2->vm_tsize += btoc(newend - entry->start);
3181	}
3182}
3183
3184/*
3185 * vmspace_fork:
3186 * Create a new process vmspace structure and vm_map
3187 * based on those of an existing process.  The new map
3188 * is based on the old map, according to the inheritance
3189 * values on the regions in that map.
3190 *
3191 * XXX It might be worth coalescing the entries added to the new vmspace.
3192 *
3193 * The source map must not be locked.
3194 */
3195struct vmspace *
3196vmspace_fork(struct vmspace *vm1, vm_ooffset_t *fork_charge)
3197{
3198	struct vmspace *vm2;
3199	vm_map_t new_map, old_map;
3200	vm_map_entry_t new_entry, old_entry;
3201	vm_object_t object;
3202	int locked;
3203
3204	old_map = &vm1->vm_map;
3205	/* Copy immutable fields of vm1 to vm2. */
3206	vm2 = vmspace_alloc(old_map->min_offset, old_map->max_offset, NULL);
3207	if (vm2 == NULL)
3208		return (NULL);
3209	vm2->vm_taddr = vm1->vm_taddr;
3210	vm2->vm_daddr = vm1->vm_daddr;
3211	vm2->vm_maxsaddr = vm1->vm_maxsaddr;
3212	vm_map_lock(old_map);
3213	if (old_map->busy)
3214		vm_map_wait_busy(old_map);
3215	new_map = &vm2->vm_map;
3216	locked = vm_map_trylock(new_map); /* trylock to silence WITNESS */
3217	KASSERT(locked, ("vmspace_fork: lock failed"));
3218
3219	old_entry = old_map->header.next;
3220
3221	while (old_entry != &old_map->header) {
3222		if (old_entry->eflags & MAP_ENTRY_IS_SUB_MAP)
3223			panic("vm_map_fork: encountered a submap");
3224
3225		switch (old_entry->inheritance) {
3226		case VM_INHERIT_NONE:
3227			break;
3228
3229		case VM_INHERIT_SHARE:
3230			/*
3231			 * Clone the entry, creating the shared object if necessary.
3232			 */
3233			object = old_entry->object.vm_object;
3234			if (object == NULL) {
3235				object = vm_object_allocate(OBJT_DEFAULT,
3236					atop(old_entry->end - old_entry->start));
3237				old_entry->object.vm_object = object;
3238				old_entry->offset = 0;
3239				if (old_entry->cred != NULL) {
3240					object->cred = old_entry->cred;
3241					object->charge = old_entry->end -
3242					    old_entry->start;
3243					old_entry->cred = NULL;
3244				}
3245			}
3246
3247			/*
3248			 * Add the reference before calling vm_object_shadow
3249			 * to insure that a shadow object is created.
3250			 */
3251			vm_object_reference(object);
3252			if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3253				vm_object_shadow(&old_entry->object.vm_object,
3254				    &old_entry->offset,
3255				    old_entry->end - old_entry->start);
3256				old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
3257				/* Transfer the second reference too. */
3258				vm_object_reference(
3259				    old_entry->object.vm_object);
3260
3261				/*
3262				 * As in vm_map_simplify_entry(), the
3263				 * vnode lock will not be acquired in
3264				 * this call to vm_object_deallocate().
3265				 */
3266				vm_object_deallocate(object);
3267				object = old_entry->object.vm_object;
3268			}
3269			VM_OBJECT_WLOCK(object);
3270			vm_object_clear_flag(object, OBJ_ONEMAPPING);
3271			if (old_entry->cred != NULL) {
3272				KASSERT(object->cred == NULL, ("vmspace_fork both cred"));
3273				object->cred = old_entry->cred;
3274				object->charge = old_entry->end - old_entry->start;
3275				old_entry->cred = NULL;
3276			}
3277
3278			/*
3279			 * Assert the correct state of the vnode
3280			 * v_writecount while the object is locked, to
3281			 * not relock it later for the assertion
3282			 * correctness.
3283			 */
3284			if (old_entry->eflags & MAP_ENTRY_VN_WRITECNT &&
3285			    object->type == OBJT_VNODE) {
3286				KASSERT(((struct vnode *)object->handle)->
3287				    v_writecount > 0,
3288				    ("vmspace_fork: v_writecount %p", object));
3289				KASSERT(object->un_pager.vnp.writemappings > 0,
3290				    ("vmspace_fork: vnp.writecount %p",
3291				    object));
3292			}
3293			VM_OBJECT_WUNLOCK(object);
3294
3295			/*
3296			 * Clone the entry, referencing the shared object.
3297			 */
3298			new_entry = vm_map_entry_create(new_map);
3299			*new_entry = *old_entry;
3300			new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
3301			    MAP_ENTRY_IN_TRANSITION);
3302			new_entry->wiring_thread = NULL;
3303			new_entry->wired_count = 0;
3304			if (new_entry->eflags & MAP_ENTRY_VN_WRITECNT) {
3305				vnode_pager_update_writecount(object,
3306				    new_entry->start, new_entry->end);
3307			}
3308
3309			/*
3310			 * Insert the entry into the new map -- we know we're
3311			 * inserting at the end of the new map.
3312			 */
3313			vm_map_entry_link(new_map, new_map->header.prev,
3314			    new_entry);
3315			vmspace_map_entry_forked(vm1, vm2, new_entry);
3316
3317			/*
3318			 * Update the physical map
3319			 */
3320			pmap_copy(new_map->pmap, old_map->pmap,
3321			    new_entry->start,
3322			    (old_entry->end - old_entry->start),
3323			    old_entry->start);
3324			break;
3325
3326		case VM_INHERIT_COPY:
3327			/*
3328			 * Clone the entry and link into the map.
3329			 */
3330			new_entry = vm_map_entry_create(new_map);
3331			*new_entry = *old_entry;
3332			/*
3333			 * Copied entry is COW over the old object.
3334			 */
3335			new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
3336			    MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_VN_WRITECNT);
3337			new_entry->wiring_thread = NULL;
3338			new_entry->wired_count = 0;
3339			new_entry->object.vm_object = NULL;
3340			new_entry->cred = NULL;
3341			vm_map_entry_link(new_map, new_map->header.prev,
3342			    new_entry);
3343			vmspace_map_entry_forked(vm1, vm2, new_entry);
3344			vm_map_copy_entry(old_map, new_map, old_entry,
3345			    new_entry, fork_charge);
3346			break;
3347		}
3348		old_entry = old_entry->next;
3349	}
3350	/*
3351	 * Use inlined vm_map_unlock() to postpone handling the deferred
3352	 * map entries, which cannot be done until both old_map and
3353	 * new_map locks are released.
3354	 */
3355	sx_xunlock(&old_map->lock);
3356	sx_xunlock(&new_map->lock);
3357	vm_map_process_deferred();
3358
3359	return (vm2);
3360}
3361
3362int
3363vm_map_stack(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
3364    vm_prot_t prot, vm_prot_t max, int cow)
3365{
3366	vm_size_t growsize, init_ssize;
3367	rlim_t lmemlim, vmemlim;
3368	int rv;
3369
3370	growsize = sgrowsiz;
3371	init_ssize = (max_ssize < growsize) ? max_ssize : growsize;
3372	vm_map_lock(map);
3373	PROC_LOCK(curproc);
3374	lmemlim = lim_cur(curproc, RLIMIT_MEMLOCK);
3375	vmemlim = lim_cur(curproc, RLIMIT_VMEM);
3376	PROC_UNLOCK(curproc);
3377	if (!old_mlock && map->flags & MAP_WIREFUTURE) {
3378		if (ptoa(pmap_wired_count(map->pmap)) + init_ssize > lmemlim) {
3379			rv = KERN_NO_SPACE;
3380			goto out;
3381		}
3382	}
3383	/* If we would blow our VMEM resource limit, no go */
3384	if (map->size + init_ssize > vmemlim) {
3385		rv = KERN_NO_SPACE;
3386		goto out;
3387	}
3388	rv = vm_map_stack_locked(map, addrbos, max_ssize, growsize, prot,
3389	    max, cow);
3390out:
3391	vm_map_unlock(map);
3392	return (rv);
3393}
3394
3395static int
3396vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
3397    vm_size_t growsize, vm_prot_t prot, vm_prot_t max, int cow)
3398{
3399	vm_map_entry_t new_entry, prev_entry;
3400	vm_offset_t bot, top;
3401	vm_size_t init_ssize;
3402	int orient, rv;
3403
3404	/*
3405	 * The stack orientation is piggybacked with the cow argument.
3406	 * Extract it into orient and mask the cow argument so that we
3407	 * don't pass it around further.
3408	 * NOTE: We explicitly allow bi-directional stacks.
3409	 */
3410	orient = cow & (MAP_STACK_GROWS_DOWN|MAP_STACK_GROWS_UP);
3411	KASSERT(orient != 0, ("No stack grow direction"));
3412
3413	if (addrbos < vm_map_min(map) ||
3414	    addrbos > vm_map_max(map) ||
3415	    addrbos + max_ssize < addrbos)
3416		return (KERN_NO_SPACE);
3417
3418	init_ssize = (max_ssize < growsize) ? max_ssize : growsize;
3419
3420	/* If addr is already mapped, no go */
3421	if (vm_map_lookup_entry(map, addrbos, &prev_entry))
3422		return (KERN_NO_SPACE);
3423
3424	/*
3425	 * If we can't accomodate max_ssize in the current mapping, no go.
3426	 * However, we need to be aware that subsequent user mappings might
3427	 * map into the space we have reserved for stack, and currently this
3428	 * space is not protected.
3429	 *
3430	 * Hopefully we will at least detect this condition when we try to
3431	 * grow the stack.
3432	 */
3433	if ((prev_entry->next != &map->header) &&
3434	    (prev_entry->next->start < addrbos + max_ssize))
3435		return (KERN_NO_SPACE);
3436
3437	/*
3438	 * We initially map a stack of only init_ssize.  We will grow as
3439	 * needed later.  Depending on the orientation of the stack (i.e.
3440	 * the grow direction) we either map at the top of the range, the
3441	 * bottom of the range or in the middle.
3442	 *
3443	 * Note: we would normally expect prot and max to be VM_PROT_ALL,
3444	 * and cow to be 0.  Possibly we should eliminate these as input
3445	 * parameters, and just pass these values here in the insert call.
3446	 */
3447	if (orient == MAP_STACK_GROWS_DOWN)
3448		bot = addrbos + max_ssize - init_ssize;
3449	else if (orient == MAP_STACK_GROWS_UP)
3450		bot = addrbos;
3451	else
3452		bot = round_page(addrbos + max_ssize/2 - init_ssize/2);
3453	top = bot + init_ssize;
3454	rv = vm_map_insert(map, NULL, 0, bot, top, prot, max, cow);
3455
3456	/* Now set the avail_ssize amount. */
3457	if (rv == KERN_SUCCESS) {
3458		if (prev_entry != &map->header)
3459			vm_map_clip_end(map, prev_entry, bot);
3460		new_entry = prev_entry->next;
3461		if (new_entry->end != top || new_entry->start != bot)
3462			panic("Bad entry start/end for new stack entry");
3463
3464		new_entry->avail_ssize = max_ssize - init_ssize;
3465		if (orient & MAP_STACK_GROWS_DOWN)
3466			new_entry->eflags |= MAP_ENTRY_GROWS_DOWN;
3467		if (orient & MAP_STACK_GROWS_UP)
3468			new_entry->eflags |= MAP_ENTRY_GROWS_UP;
3469	}
3470
3471	return (rv);
3472}
3473
3474static int stack_guard_page = 0;
3475TUNABLE_INT("security.bsd.stack_guard_page", &stack_guard_page);
3476SYSCTL_INT(_security_bsd, OID_AUTO, stack_guard_page, CTLFLAG_RW,
3477    &stack_guard_page, 0,
3478    "Insert stack guard page ahead of the growable segments.");
3479
3480/* Attempts to grow a vm stack entry.  Returns KERN_SUCCESS if the
3481 * desired address is already mapped, or if we successfully grow
3482 * the stack.  Also returns KERN_SUCCESS if addr is outside the
3483 * stack range (this is strange, but preserves compatibility with
3484 * the grow function in vm_machdep.c).
3485 */
3486int
3487vm_map_growstack(struct proc *p, vm_offset_t addr)
3488{
3489	vm_map_entry_t next_entry, prev_entry;
3490	vm_map_entry_t new_entry, stack_entry;
3491	struct vmspace *vm = p->p_vmspace;
3492	vm_map_t map = &vm->vm_map;
3493	vm_offset_t end;
3494	vm_size_t growsize;
3495	size_t grow_amount, max_grow;
3496	rlim_t lmemlim, stacklim, vmemlim;
3497	int is_procstack, rv;
3498	struct ucred *cred;
3499#ifdef notyet
3500	uint64_t limit;
3501#endif
3502#ifdef RACCT
3503	int error;
3504#endif
3505
3506Retry:
3507	PROC_LOCK(p);
3508	lmemlim = lim_cur(p, RLIMIT_MEMLOCK);
3509	stacklim = lim_cur(p, RLIMIT_STACK);
3510	vmemlim = lim_cur(p, RLIMIT_VMEM);
3511	PROC_UNLOCK(p);
3512
3513	vm_map_lock_read(map);
3514
3515	/* If addr is already in the entry range, no need to grow.*/
3516	if (vm_map_lookup_entry(map, addr, &prev_entry)) {
3517		vm_map_unlock_read(map);
3518		return (KERN_SUCCESS);
3519	}
3520
3521	next_entry = prev_entry->next;
3522	if (!(prev_entry->eflags & MAP_ENTRY_GROWS_UP)) {
3523		/*
3524		 * This entry does not grow upwards. Since the address lies
3525		 * beyond this entry, the next entry (if one exists) has to
3526		 * be a downward growable entry. The entry list header is
3527		 * never a growable entry, so it suffices to check the flags.
3528		 */
3529		if (!(next_entry->eflags & MAP_ENTRY_GROWS_DOWN)) {
3530			vm_map_unlock_read(map);
3531			return (KERN_SUCCESS);
3532		}
3533		stack_entry = next_entry;
3534	} else {
3535		/*
3536		 * This entry grows upward. If the next entry does not at
3537		 * least grow downwards, this is the entry we need to grow.
3538		 * otherwise we have two possible choices and we have to
3539		 * select one.
3540		 */
3541		if (next_entry->eflags & MAP_ENTRY_GROWS_DOWN) {
3542			/*
3543			 * We have two choices; grow the entry closest to
3544			 * the address to minimize the amount of growth.
3545			 */
3546			if (addr - prev_entry->end <= next_entry->start - addr)
3547				stack_entry = prev_entry;
3548			else
3549				stack_entry = next_entry;
3550		} else
3551			stack_entry = prev_entry;
3552	}
3553
3554	if (stack_entry == next_entry) {
3555		KASSERT(stack_entry->eflags & MAP_ENTRY_GROWS_DOWN, ("foo"));
3556		KASSERT(addr < stack_entry->start, ("foo"));
3557		end = (prev_entry != &map->header) ? prev_entry->end :
3558		    stack_entry->start - stack_entry->avail_ssize;
3559		grow_amount = roundup(stack_entry->start - addr, PAGE_SIZE);
3560		max_grow = stack_entry->start - end;
3561	} else {
3562		KASSERT(stack_entry->eflags & MAP_ENTRY_GROWS_UP, ("foo"));
3563		KASSERT(addr >= stack_entry->end, ("foo"));
3564		end = (next_entry != &map->header) ? next_entry->start :
3565		    stack_entry->end + stack_entry->avail_ssize;
3566		grow_amount = roundup(addr + 1 - stack_entry->end, PAGE_SIZE);
3567		max_grow = end - stack_entry->end;
3568	}
3569
3570	if (grow_amount > stack_entry->avail_ssize) {
3571		vm_map_unlock_read(map);
3572		return (KERN_NO_SPACE);
3573	}
3574
3575	/*
3576	 * If there is no longer enough space between the entries nogo, and
3577	 * adjust the available space.  Note: this  should only happen if the
3578	 * user has mapped into the stack area after the stack was created,
3579	 * and is probably an error.
3580	 *
3581	 * This also effectively destroys any guard page the user might have
3582	 * intended by limiting the stack size.
3583	 */
3584	if (grow_amount + (stack_guard_page ? PAGE_SIZE : 0) > max_grow) {
3585		if (vm_map_lock_upgrade(map))
3586			goto Retry;
3587
3588		stack_entry->avail_ssize = max_grow;
3589
3590		vm_map_unlock(map);
3591		return (KERN_NO_SPACE);
3592	}
3593
3594	is_procstack = (addr >= (vm_offset_t)vm->vm_maxsaddr) ? 1 : 0;
3595
3596	/*
3597	 * If this is the main process stack, see if we're over the stack
3598	 * limit.
3599	 */
3600	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
3601		vm_map_unlock_read(map);
3602		return (KERN_NO_SPACE);
3603	}
3604#ifdef RACCT
3605	PROC_LOCK(p);
3606	if (is_procstack &&
3607	    racct_set(p, RACCT_STACK, ctob(vm->vm_ssize) + grow_amount)) {
3608		PROC_UNLOCK(p);
3609		vm_map_unlock_read(map);
3610		return (KERN_NO_SPACE);
3611	}
3612	PROC_UNLOCK(p);
3613#endif
3614
3615	/* Round up the grow amount modulo sgrowsiz */
3616	growsize = sgrowsiz;
3617	grow_amount = roundup(grow_amount, growsize);
3618	if (grow_amount > stack_entry->avail_ssize)
3619		grow_amount = stack_entry->avail_ssize;
3620	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
3621		grow_amount = trunc_page((vm_size_t)stacklim) -
3622		    ctob(vm->vm_ssize);
3623	}
3624#ifdef notyet
3625	PROC_LOCK(p);
3626	limit = racct_get_available(p, RACCT_STACK);
3627	PROC_UNLOCK(p);
3628	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > limit))
3629		grow_amount = limit - ctob(vm->vm_ssize);
3630#endif
3631	if (!old_mlock && map->flags & MAP_WIREFUTURE) {
3632		if (ptoa(pmap_wired_count(map->pmap)) + grow_amount > lmemlim) {
3633			vm_map_unlock_read(map);
3634			rv = KERN_NO_SPACE;
3635			goto out;
3636		}
3637#ifdef RACCT
3638		PROC_LOCK(p);
3639		if (racct_set(p, RACCT_MEMLOCK,
3640		    ptoa(pmap_wired_count(map->pmap)) + grow_amount)) {
3641			PROC_UNLOCK(p);
3642			vm_map_unlock_read(map);
3643			rv = KERN_NO_SPACE;
3644			goto out;
3645		}
3646		PROC_UNLOCK(p);
3647#endif
3648	}
3649	/* If we would blow our VMEM resource limit, no go */
3650	if (map->size + grow_amount > vmemlim) {
3651		vm_map_unlock_read(map);
3652		rv = KERN_NO_SPACE;
3653		goto out;
3654	}
3655#ifdef RACCT
3656	PROC_LOCK(p);
3657	if (racct_set(p, RACCT_VMEM, map->size + grow_amount)) {
3658		PROC_UNLOCK(p);
3659		vm_map_unlock_read(map);
3660		rv = KERN_NO_SPACE;
3661		goto out;
3662	}
3663	PROC_UNLOCK(p);
3664#endif
3665
3666	if (vm_map_lock_upgrade(map))
3667		goto Retry;
3668
3669	if (stack_entry == next_entry) {
3670		/*
3671		 * Growing downward.
3672		 */
3673		/* Get the preliminary new entry start value */
3674		addr = stack_entry->start - grow_amount;
3675
3676		/*
3677		 * If this puts us into the previous entry, cut back our
3678		 * growth to the available space. Also, see the note above.
3679		 */
3680		if (addr < end) {
3681			stack_entry->avail_ssize = max_grow;
3682			addr = end;
3683			if (stack_guard_page)
3684				addr += PAGE_SIZE;
3685		}
3686
3687		rv = vm_map_insert(map, NULL, 0, addr, stack_entry->start,
3688		    next_entry->protection, next_entry->max_protection, 0);
3689
3690		/* Adjust the available stack space by the amount we grew. */
3691		if (rv == KERN_SUCCESS) {
3692			if (prev_entry != &map->header)
3693				vm_map_clip_end(map, prev_entry, addr);
3694			new_entry = prev_entry->next;
3695			KASSERT(new_entry == stack_entry->prev, ("foo"));
3696			KASSERT(new_entry->end == stack_entry->start, ("foo"));
3697			KASSERT(new_entry->start == addr, ("foo"));
3698			grow_amount = new_entry->end - new_entry->start;
3699			new_entry->avail_ssize = stack_entry->avail_ssize -
3700			    grow_amount;
3701			stack_entry->eflags &= ~MAP_ENTRY_GROWS_DOWN;
3702			new_entry->eflags |= MAP_ENTRY_GROWS_DOWN;
3703		}
3704	} else {
3705		/*
3706		 * Growing upward.
3707		 */
3708		addr = stack_entry->end + grow_amount;
3709
3710		/*
3711		 * If this puts us into the next entry, cut back our growth
3712		 * to the available space. Also, see the note above.
3713		 */
3714		if (addr > end) {
3715			stack_entry->avail_ssize = end - stack_entry->end;
3716			addr = end;
3717			if (stack_guard_page)
3718				addr -= PAGE_SIZE;
3719		}
3720
3721		grow_amount = addr - stack_entry->end;
3722		cred = stack_entry->cred;
3723		if (cred == NULL && stack_entry->object.vm_object != NULL)
3724			cred = stack_entry->object.vm_object->cred;
3725		if (cred != NULL && !swap_reserve_by_cred(grow_amount, cred))
3726			rv = KERN_NO_SPACE;
3727		/* Grow the underlying object if applicable. */
3728		else if (stack_entry->object.vm_object == NULL ||
3729			 vm_object_coalesce(stack_entry->object.vm_object,
3730			 stack_entry->offset,
3731			 (vm_size_t)(stack_entry->end - stack_entry->start),
3732			 (vm_size_t)grow_amount, cred != NULL)) {
3733			map->size += (addr - stack_entry->end);
3734			/* Update the current entry. */
3735			stack_entry->end = addr;
3736			stack_entry->avail_ssize -= grow_amount;
3737			vm_map_entry_resize_free(map, stack_entry);
3738			rv = KERN_SUCCESS;
3739
3740			if (next_entry != &map->header)
3741				vm_map_clip_start(map, next_entry, addr);
3742		} else
3743			rv = KERN_FAILURE;
3744	}
3745
3746	if (rv == KERN_SUCCESS && is_procstack)
3747		vm->vm_ssize += btoc(grow_amount);
3748
3749	vm_map_unlock(map);
3750
3751	/*
3752	 * Heed the MAP_WIREFUTURE flag if it was set for this process.
3753	 */
3754	if (rv == KERN_SUCCESS && (map->flags & MAP_WIREFUTURE)) {
3755		vm_map_wire(map,
3756		    (stack_entry == next_entry) ? addr : addr - grow_amount,
3757		    (stack_entry == next_entry) ? stack_entry->start : addr,
3758		    (p->p_flag & P_SYSTEM)
3759		    ? VM_MAP_WIRE_SYSTEM|VM_MAP_WIRE_NOHOLES
3760		    : VM_MAP_WIRE_USER|VM_MAP_WIRE_NOHOLES);
3761	}
3762
3763out:
3764#ifdef RACCT
3765	if (rv != KERN_SUCCESS) {
3766		PROC_LOCK(p);
3767		error = racct_set(p, RACCT_VMEM, map->size);
3768		KASSERT(error == 0, ("decreasing RACCT_VMEM failed"));
3769		if (!old_mlock) {
3770			error = racct_set(p, RACCT_MEMLOCK,
3771			    ptoa(pmap_wired_count(map->pmap)));
3772			KASSERT(error == 0, ("decreasing RACCT_MEMLOCK failed"));
3773		}
3774	    	error = racct_set(p, RACCT_STACK, ctob(vm->vm_ssize));
3775		KASSERT(error == 0, ("decreasing RACCT_STACK failed"));
3776		PROC_UNLOCK(p);
3777	}
3778#endif
3779
3780	return (rv);
3781}
3782
3783/*
3784 * Unshare the specified VM space for exec.  If other processes are
3785 * mapped to it, then create a new one.  The new vmspace is null.
3786 */
3787int
3788vmspace_exec(struct proc *p, vm_offset_t minuser, vm_offset_t maxuser)
3789{
3790	struct vmspace *oldvmspace = p->p_vmspace;
3791	struct vmspace *newvmspace;
3792
3793	KASSERT((curthread->td_pflags & TDP_EXECVMSPC) == 0,
3794	    ("vmspace_exec recursed"));
3795	newvmspace = vmspace_alloc(minuser, maxuser, NULL);
3796	if (newvmspace == NULL)
3797		return (ENOMEM);
3798	newvmspace->vm_swrss = oldvmspace->vm_swrss;
3799	/*
3800	 * This code is written like this for prototype purposes.  The
3801	 * goal is to avoid running down the vmspace here, but let the
3802	 * other process's that are still using the vmspace to finally
3803	 * run it down.  Even though there is little or no chance of blocking
3804	 * here, it is a good idea to keep this form for future mods.
3805	 */
3806	PROC_VMSPACE_LOCK(p);
3807	p->p_vmspace = newvmspace;
3808	PROC_VMSPACE_UNLOCK(p);
3809	if (p == curthread->td_proc)
3810		pmap_activate(curthread);
3811	curthread->td_pflags |= TDP_EXECVMSPC;
3812	return (0);
3813}
3814
3815/*
3816 * Unshare the specified VM space for forcing COW.  This
3817 * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
3818 */
3819int
3820vmspace_unshare(struct proc *p)
3821{
3822	struct vmspace *oldvmspace = p->p_vmspace;
3823	struct vmspace *newvmspace;
3824	vm_ooffset_t fork_charge;
3825
3826	if (oldvmspace->vm_refcnt == 1)
3827		return (0);
3828	fork_charge = 0;
3829	newvmspace = vmspace_fork(oldvmspace, &fork_charge);
3830	if (newvmspace == NULL)
3831		return (ENOMEM);
3832	if (!swap_reserve_by_cred(fork_charge, p->p_ucred)) {
3833		vmspace_free(newvmspace);
3834		return (ENOMEM);
3835	}
3836	PROC_VMSPACE_LOCK(p);
3837	p->p_vmspace = newvmspace;
3838	PROC_VMSPACE_UNLOCK(p);
3839	if (p == curthread->td_proc)
3840		pmap_activate(curthread);
3841	vmspace_free(oldvmspace);
3842	return (0);
3843}
3844
3845/*
3846 *	vm_map_lookup:
3847 *
3848 *	Finds the VM object, offset, and
3849 *	protection for a given virtual address in the
3850 *	specified map, assuming a page fault of the
3851 *	type specified.
3852 *
3853 *	Leaves the map in question locked for read; return
3854 *	values are guaranteed until a vm_map_lookup_done
3855 *	call is performed.  Note that the map argument
3856 *	is in/out; the returned map must be used in
3857 *	the call to vm_map_lookup_done.
3858 *
3859 *	A handle (out_entry) is returned for use in
3860 *	vm_map_lookup_done, to make that fast.
3861 *
3862 *	If a lookup is requested with "write protection"
3863 *	specified, the map may be changed to perform virtual
3864 *	copying operations, although the data referenced will
3865 *	remain the same.
3866 */
3867int
3868vm_map_lookup(vm_map_t *var_map,		/* IN/OUT */
3869	      vm_offset_t vaddr,
3870	      vm_prot_t fault_typea,
3871	      vm_map_entry_t *out_entry,	/* OUT */
3872	      vm_object_t *object,		/* OUT */
3873	      vm_pindex_t *pindex,		/* OUT */
3874	      vm_prot_t *out_prot,		/* OUT */
3875	      boolean_t *wired)			/* OUT */
3876{
3877	vm_map_entry_t entry;
3878	vm_map_t map = *var_map;
3879	vm_prot_t prot;
3880	vm_prot_t fault_type = fault_typea;
3881	vm_object_t eobject;
3882	vm_size_t size;
3883	struct ucred *cred;
3884
3885RetryLookup:;
3886
3887	vm_map_lock_read(map);
3888
3889	/*
3890	 * Lookup the faulting address.
3891	 */
3892	if (!vm_map_lookup_entry(map, vaddr, out_entry)) {
3893		vm_map_unlock_read(map);
3894		return (KERN_INVALID_ADDRESS);
3895	}
3896
3897	entry = *out_entry;
3898
3899	/*
3900	 * Handle submaps.
3901	 */
3902	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
3903		vm_map_t old_map = map;
3904
3905		*var_map = map = entry->object.sub_map;
3906		vm_map_unlock_read(old_map);
3907		goto RetryLookup;
3908	}
3909
3910	/*
3911	 * Check whether this task is allowed to have this page.
3912	 */
3913	prot = entry->protection;
3914	fault_type &= (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE);
3915	if ((fault_type & prot) != fault_type || prot == VM_PROT_NONE) {
3916		vm_map_unlock_read(map);
3917		return (KERN_PROTECTION_FAILURE);
3918	}
3919	if ((entry->eflags & MAP_ENTRY_USER_WIRED) &&
3920	    (entry->eflags & MAP_ENTRY_COW) &&
3921	    (fault_type & VM_PROT_WRITE)) {
3922		vm_map_unlock_read(map);
3923		return (KERN_PROTECTION_FAILURE);
3924	}
3925	if ((fault_typea & VM_PROT_COPY) != 0 &&
3926	    (entry->max_protection & VM_PROT_WRITE) == 0 &&
3927	    (entry->eflags & MAP_ENTRY_COW) == 0) {
3928		vm_map_unlock_read(map);
3929		return (KERN_PROTECTION_FAILURE);
3930	}
3931
3932	/*
3933	 * If this page is not pageable, we have to get it for all possible
3934	 * accesses.
3935	 */
3936	*wired = (entry->wired_count != 0);
3937	if (*wired)
3938		fault_type = entry->protection;
3939	size = entry->end - entry->start;
3940	/*
3941	 * If the entry was copy-on-write, we either ...
3942	 */
3943	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3944		/*
3945		 * If we want to write the page, we may as well handle that
3946		 * now since we've got the map locked.
3947		 *
3948		 * If we don't need to write the page, we just demote the
3949		 * permissions allowed.
3950		 */
3951		if ((fault_type & VM_PROT_WRITE) != 0 ||
3952		    (fault_typea & VM_PROT_COPY) != 0) {
3953			/*
3954			 * Make a new object, and place it in the object
3955			 * chain.  Note that no new references have appeared
3956			 * -- one just moved from the map to the new
3957			 * object.
3958			 */
3959			if (vm_map_lock_upgrade(map))
3960				goto RetryLookup;
3961
3962			if (entry->cred == NULL) {
3963				/*
3964				 * The debugger owner is charged for
3965				 * the memory.
3966				 */
3967				cred = curthread->td_ucred;
3968				crhold(cred);
3969				if (!swap_reserve_by_cred(size, cred)) {
3970					crfree(cred);
3971					vm_map_unlock(map);
3972					return (KERN_RESOURCE_SHORTAGE);
3973				}
3974				entry->cred = cred;
3975			}
3976			vm_object_shadow(&entry->object.vm_object,
3977			    &entry->offset, size);
3978			entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
3979			eobject = entry->object.vm_object;
3980			if (eobject->cred != NULL) {
3981				/*
3982				 * The object was not shadowed.
3983				 */
3984				swap_release_by_cred(size, entry->cred);
3985				crfree(entry->cred);
3986				entry->cred = NULL;
3987			} else if (entry->cred != NULL) {
3988				VM_OBJECT_WLOCK(eobject);
3989				eobject->cred = entry->cred;
3990				eobject->charge = size;
3991				VM_OBJECT_WUNLOCK(eobject);
3992				entry->cred = NULL;
3993			}
3994
3995			vm_map_lock_downgrade(map);
3996		} else {
3997			/*
3998			 * We're attempting to read a copy-on-write page --
3999			 * don't allow writes.
4000			 */
4001			prot &= ~VM_PROT_WRITE;
4002		}
4003	}
4004
4005	/*
4006	 * Create an object if necessary.
4007	 */
4008	if (entry->object.vm_object == NULL &&
4009	    !map->system_map) {
4010		if (vm_map_lock_upgrade(map))
4011			goto RetryLookup;
4012		entry->object.vm_object = vm_object_allocate(OBJT_DEFAULT,
4013		    atop(size));
4014		entry->offset = 0;
4015		if (entry->cred != NULL) {
4016			VM_OBJECT_WLOCK(entry->object.vm_object);
4017			entry->object.vm_object->cred = entry->cred;
4018			entry->object.vm_object->charge = size;
4019			VM_OBJECT_WUNLOCK(entry->object.vm_object);
4020			entry->cred = NULL;
4021		}
4022		vm_map_lock_downgrade(map);
4023	}
4024
4025	/*
4026	 * Return the object/offset from this entry.  If the entry was
4027	 * copy-on-write or empty, it has been fixed up.
4028	 */
4029	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4030	*object = entry->object.vm_object;
4031
4032	*out_prot = prot;
4033	return (KERN_SUCCESS);
4034}
4035
4036/*
4037 *	vm_map_lookup_locked:
4038 *
4039 *	Lookup the faulting address.  A version of vm_map_lookup that returns
4040 *      KERN_FAILURE instead of blocking on map lock or memory allocation.
4041 */
4042int
4043vm_map_lookup_locked(vm_map_t *var_map,		/* IN/OUT */
4044		     vm_offset_t vaddr,
4045		     vm_prot_t fault_typea,
4046		     vm_map_entry_t *out_entry,	/* OUT */
4047		     vm_object_t *object,	/* OUT */
4048		     vm_pindex_t *pindex,	/* OUT */
4049		     vm_prot_t *out_prot,	/* OUT */
4050		     boolean_t *wired)		/* OUT */
4051{
4052	vm_map_entry_t entry;
4053	vm_map_t map = *var_map;
4054	vm_prot_t prot;
4055	vm_prot_t fault_type = fault_typea;
4056
4057	/*
4058	 * Lookup the faulting address.
4059	 */
4060	if (!vm_map_lookup_entry(map, vaddr, out_entry))
4061		return (KERN_INVALID_ADDRESS);
4062
4063	entry = *out_entry;
4064
4065	/*
4066	 * Fail if the entry refers to a submap.
4067	 */
4068	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
4069		return (KERN_FAILURE);
4070
4071	/*
4072	 * Check whether this task is allowed to have this page.
4073	 */
4074	prot = entry->protection;
4075	fault_type &= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
4076	if ((fault_type & prot) != fault_type)
4077		return (KERN_PROTECTION_FAILURE);
4078	if ((entry->eflags & MAP_ENTRY_USER_WIRED) &&
4079	    (entry->eflags & MAP_ENTRY_COW) &&
4080	    (fault_type & VM_PROT_WRITE))
4081		return (KERN_PROTECTION_FAILURE);
4082
4083	/*
4084	 * If this page is not pageable, we have to get it for all possible
4085	 * accesses.
4086	 */
4087	*wired = (entry->wired_count != 0);
4088	if (*wired)
4089		fault_type = entry->protection;
4090
4091	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4092		/*
4093		 * Fail if the entry was copy-on-write for a write fault.
4094		 */
4095		if (fault_type & VM_PROT_WRITE)
4096			return (KERN_FAILURE);
4097		/*
4098		 * We're attempting to read a copy-on-write page --
4099		 * don't allow writes.
4100		 */
4101		prot &= ~VM_PROT_WRITE;
4102	}
4103
4104	/*
4105	 * Fail if an object should be created.
4106	 */
4107	if (entry->object.vm_object == NULL && !map->system_map)
4108		return (KERN_FAILURE);
4109
4110	/*
4111	 * Return the object/offset from this entry.  If the entry was
4112	 * copy-on-write or empty, it has been fixed up.
4113	 */
4114	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4115	*object = entry->object.vm_object;
4116
4117	*out_prot = prot;
4118	return (KERN_SUCCESS);
4119}
4120
4121/*
4122 *	vm_map_lookup_done:
4123 *
4124 *	Releases locks acquired by a vm_map_lookup
4125 *	(according to the handle returned by that lookup).
4126 */
4127void
4128vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry)
4129{
4130	/*
4131	 * Unlock the main-level map
4132	 */
4133	vm_map_unlock_read(map);
4134}
4135
4136#include "opt_ddb.h"
4137#ifdef DDB
4138#include <sys/kernel.h>
4139
4140#include <ddb/ddb.h>
4141
4142static void
4143vm_map_print(vm_map_t map)
4144{
4145	vm_map_entry_t entry;
4146
4147	db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
4148	    (void *)map,
4149	    (void *)map->pmap, map->nentries, map->timestamp);
4150
4151	db_indent += 2;
4152	for (entry = map->header.next; entry != &map->header;
4153	    entry = entry->next) {
4154		db_iprintf("map entry %p: start=%p, end=%p\n",
4155		    (void *)entry, (void *)entry->start, (void *)entry->end);
4156		{
4157			static char *inheritance_name[4] =
4158			{"share", "copy", "none", "donate_copy"};
4159
4160			db_iprintf(" prot=%x/%x/%s",
4161			    entry->protection,
4162			    entry->max_protection,
4163			    inheritance_name[(int)(unsigned char)entry->inheritance]);
4164			if (entry->wired_count != 0)
4165				db_printf(", wired");
4166		}
4167		if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
4168			db_printf(", share=%p, offset=0x%jx\n",
4169			    (void *)entry->object.sub_map,
4170			    (uintmax_t)entry->offset);
4171			if ((entry->prev == &map->header) ||
4172			    (entry->prev->object.sub_map !=
4173				entry->object.sub_map)) {
4174				db_indent += 2;
4175				vm_map_print((vm_map_t)entry->object.sub_map);
4176				db_indent -= 2;
4177			}
4178		} else {
4179			if (entry->cred != NULL)
4180				db_printf(", ruid %d", entry->cred->cr_ruid);
4181			db_printf(", object=%p, offset=0x%jx",
4182			    (void *)entry->object.vm_object,
4183			    (uintmax_t)entry->offset);
4184			if (entry->object.vm_object && entry->object.vm_object->cred)
4185				db_printf(", obj ruid %d charge %jx",
4186				    entry->object.vm_object->cred->cr_ruid,
4187				    (uintmax_t)entry->object.vm_object->charge);
4188			if (entry->eflags & MAP_ENTRY_COW)
4189				db_printf(", copy (%s)",
4190				    (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
4191			db_printf("\n");
4192
4193			if ((entry->prev == &map->header) ||
4194			    (entry->prev->object.vm_object !=
4195				entry->object.vm_object)) {
4196				db_indent += 2;
4197				vm_object_print((db_expr_t)(intptr_t)
4198						entry->object.vm_object,
4199						0, 0, (char *)0);
4200				db_indent -= 2;
4201			}
4202		}
4203	}
4204	db_indent -= 2;
4205}
4206
4207DB_SHOW_COMMAND(map, map)
4208{
4209
4210	if (!have_addr) {
4211		db_printf("usage: show map <addr>\n");
4212		return;
4213	}
4214	vm_map_print((vm_map_t)addr);
4215}
4216
4217DB_SHOW_COMMAND(procvm, procvm)
4218{
4219	struct proc *p;
4220
4221	if (have_addr) {
4222		p = (struct proc *) addr;
4223	} else {
4224		p = curproc;
4225	}
4226
4227	db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
4228	    (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
4229	    (void *)vmspace_pmap(p->p_vmspace));
4230
4231	vm_map_print((vm_map_t)&p->p_vmspace->vm_map);
4232}
4233
4234#endif /* DDB */
4235