vm_fault.c revision 303246
1/*-
2 * Copyright (c) 1991, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 * Copyright (c) 1994 John S. Dyson
5 * All rights reserved.
6 * Copyright (c) 1994 David Greenman
7 * All rights reserved.
8 *
9 *
10 * This code is derived from software contributed to Berkeley by
11 * The Mach Operating System project at Carnegie-Mellon University.
12 *
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
15 * are met:
16 * 1. Redistributions of source code must retain the above copyright
17 *    notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 *    notice, this list of conditions and the following disclaimer in the
20 *    documentation and/or other materials provided with the distribution.
21 * 3. All advertising materials mentioning features or use of this software
22 *    must display the following acknowledgement:
23 *	This product includes software developed by the University of
24 *	California, Berkeley and its contributors.
25 * 4. Neither the name of the University nor the names of its contributors
26 *    may be used to endorse or promote products derived from this software
27 *    without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 * SUCH DAMAGE.
40 *
41 *	from: @(#)vm_fault.c	8.4 (Berkeley) 1/12/94
42 *
43 *
44 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
45 * All rights reserved.
46 *
47 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
48 *
49 * Permission to use, copy, modify and distribute this software and
50 * its documentation is hereby granted, provided that both the copyright
51 * notice and this permission notice appear in all copies of the
52 * software, derivative works or modified versions, and any portions
53 * thereof, and that both notices appear in supporting documentation.
54 *
55 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
56 * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
57 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
58 *
59 * Carnegie Mellon requests users of this software to return to
60 *
61 *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
62 *  School of Computer Science
63 *  Carnegie Mellon University
64 *  Pittsburgh PA 15213-3890
65 *
66 * any improvements or extensions that they make and grant Carnegie the
67 * rights to redistribute these changes.
68 */
69
70/*
71 *	Page fault handling module.
72 */
73
74#include <sys/cdefs.h>
75__FBSDID("$FreeBSD: stable/10/sys/vm/vm_fault.c 303246 2016-07-23 21:15:40Z alc $");
76
77#include "opt_ktrace.h"
78#include "opt_vm.h"
79
80#include <sys/param.h>
81#include <sys/systm.h>
82#include <sys/kernel.h>
83#include <sys/lock.h>
84#include <sys/proc.h>
85#include <sys/resourcevar.h>
86#include <sys/rwlock.h>
87#include <sys/sysctl.h>
88#include <sys/vmmeter.h>
89#include <sys/vnode.h>
90#ifdef KTRACE
91#include <sys/ktrace.h>
92#endif
93
94#include <vm/vm.h>
95#include <vm/vm_param.h>
96#include <vm/pmap.h>
97#include <vm/vm_map.h>
98#include <vm/vm_object.h>
99#include <vm/vm_page.h>
100#include <vm/vm_pageout.h>
101#include <vm/vm_kern.h>
102#include <vm/vm_pager.h>
103#include <vm/vm_extern.h>
104#include <vm/vm_reserv.h>
105
106#define PFBAK 4
107#define PFFOR 4
108
109static int vm_fault_additional_pages(vm_page_t, int, int, vm_page_t *, int *);
110
111#define	VM_FAULT_READ_BEHIND	8
112#define	VM_FAULT_READ_MAX	(1 + VM_FAULT_READ_AHEAD_MAX)
113#define	VM_FAULT_NINCR		(VM_FAULT_READ_MAX / VM_FAULT_READ_BEHIND)
114#define	VM_FAULT_SUM		(VM_FAULT_NINCR * (VM_FAULT_NINCR + 1) / 2)
115#define	VM_FAULT_CACHE_BEHIND	(VM_FAULT_READ_BEHIND * VM_FAULT_SUM)
116
117struct faultstate {
118	vm_page_t m;
119	vm_object_t object;
120	vm_pindex_t pindex;
121	vm_page_t first_m;
122	vm_object_t	first_object;
123	vm_pindex_t first_pindex;
124	vm_map_t map;
125	vm_map_entry_t entry;
126	int lookup_still_valid;
127	struct vnode *vp;
128};
129
130static void vm_fault_cache_behind(const struct faultstate *fs, int distance);
131static void vm_fault_prefault(const struct faultstate *fs, vm_offset_t addra,
132	    int faultcount, int reqpage);
133
134static inline void
135release_page(struct faultstate *fs)
136{
137
138	vm_page_xunbusy(fs->m);
139	vm_page_lock(fs->m);
140	vm_page_deactivate(fs->m);
141	vm_page_unlock(fs->m);
142	fs->m = NULL;
143}
144
145static inline void
146unlock_map(struct faultstate *fs)
147{
148
149	if (fs->lookup_still_valid) {
150		vm_map_lookup_done(fs->map, fs->entry);
151		fs->lookup_still_valid = FALSE;
152	}
153}
154
155static void
156unlock_and_deallocate(struct faultstate *fs)
157{
158
159	vm_object_pip_wakeup(fs->object);
160	VM_OBJECT_WUNLOCK(fs->object);
161	if (fs->object != fs->first_object) {
162		VM_OBJECT_WLOCK(fs->first_object);
163		vm_page_lock(fs->first_m);
164		vm_page_free(fs->first_m);
165		vm_page_unlock(fs->first_m);
166		vm_object_pip_wakeup(fs->first_object);
167		VM_OBJECT_WUNLOCK(fs->first_object);
168		fs->first_m = NULL;
169	}
170	vm_object_deallocate(fs->first_object);
171	unlock_map(fs);
172	if (fs->vp != NULL) {
173		vput(fs->vp);
174		fs->vp = NULL;
175	}
176}
177
178static void
179vm_fault_dirty(vm_map_entry_t entry, vm_page_t m, vm_prot_t prot,
180    vm_prot_t fault_type, int fault_flags, boolean_t set_wd)
181{
182	boolean_t need_dirty;
183
184	if (((prot & VM_PROT_WRITE) == 0 &&
185	    (fault_flags & VM_FAULT_DIRTY) == 0) ||
186	    (m->oflags & VPO_UNMANAGED) != 0)
187		return;
188
189	VM_OBJECT_ASSERT_LOCKED(m->object);
190
191	need_dirty = ((fault_type & VM_PROT_WRITE) != 0 &&
192	    (fault_flags & VM_FAULT_WIRE) == 0) ||
193	    (fault_flags & VM_FAULT_DIRTY) != 0;
194
195	if (set_wd)
196		vm_object_set_writeable_dirty(m->object);
197	else
198		/*
199		 * If two callers of vm_fault_dirty() with set_wd ==
200		 * FALSE, one for the map entry with MAP_ENTRY_NOSYNC
201		 * flag set, other with flag clear, race, it is
202		 * possible for the no-NOSYNC thread to see m->dirty
203		 * != 0 and not clear VPO_NOSYNC.  Take vm_page lock
204		 * around manipulation of VPO_NOSYNC and
205		 * vm_page_dirty() call, to avoid the race and keep
206		 * m->oflags consistent.
207		 */
208		vm_page_lock(m);
209
210	/*
211	 * If this is a NOSYNC mmap we do not want to set VPO_NOSYNC
212	 * if the page is already dirty to prevent data written with
213	 * the expectation of being synced from not being synced.
214	 * Likewise if this entry does not request NOSYNC then make
215	 * sure the page isn't marked NOSYNC.  Applications sharing
216	 * data should use the same flags to avoid ping ponging.
217	 */
218	if ((entry->eflags & MAP_ENTRY_NOSYNC) != 0) {
219		if (m->dirty == 0) {
220			m->oflags |= VPO_NOSYNC;
221		}
222	} else {
223		m->oflags &= ~VPO_NOSYNC;
224	}
225
226	/*
227	 * If the fault is a write, we know that this page is being
228	 * written NOW so dirty it explicitly to save on
229	 * pmap_is_modified() calls later.
230	 *
231	 * Also tell the backing pager, if any, that it should remove
232	 * any swap backing since the page is now dirty.
233	 */
234	if (need_dirty)
235		vm_page_dirty(m);
236	if (!set_wd)
237		vm_page_unlock(m);
238	if (need_dirty)
239		vm_pager_page_unswapped(m);
240}
241
242/*
243 *	vm_fault:
244 *
245 *	Handle a page fault occurring at the given address,
246 *	requiring the given permissions, in the map specified.
247 *	If successful, the page is inserted into the
248 *	associated physical map.
249 *
250 *	NOTE: the given address should be truncated to the
251 *	proper page address.
252 *
253 *	KERN_SUCCESS is returned if the page fault is handled; otherwise,
254 *	a standard error specifying why the fault is fatal is returned.
255 *
256 *	The map in question must be referenced, and remains so.
257 *	Caller may hold no locks.
258 */
259int
260vm_fault(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
261    int fault_flags)
262{
263	struct thread *td;
264	int result;
265
266	td = curthread;
267	if ((td->td_pflags & TDP_NOFAULTING) != 0)
268		return (KERN_PROTECTION_FAILURE);
269#ifdef KTRACE
270	if (map != kernel_map && KTRPOINT(td, KTR_FAULT))
271		ktrfault(vaddr, fault_type);
272#endif
273	result = vm_fault_hold(map, trunc_page(vaddr), fault_type, fault_flags,
274	    NULL);
275#ifdef KTRACE
276	if (map != kernel_map && KTRPOINT(td, KTR_FAULTEND))
277		ktrfaultend(result);
278#endif
279	return (result);
280}
281
282int
283vm_fault_hold(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
284    int fault_flags, vm_page_t *m_hold)
285{
286	vm_prot_t prot;
287	long ahead, behind;
288	int alloc_req, era, faultcount, nera, reqpage, result;
289	boolean_t dead, growstack, is_first_object_locked, wired;
290	int map_generation;
291	vm_object_t next_object;
292	vm_page_t marray[VM_FAULT_READ_MAX];
293	int hardfault;
294	struct faultstate fs;
295	struct vnode *vp;
296	vm_page_t m;
297	int locked, error;
298
299	hardfault = 0;
300	growstack = TRUE;
301	PCPU_INC(cnt.v_vm_faults);
302	fs.vp = NULL;
303	faultcount = reqpage = 0;
304
305RetryFault:;
306
307	/*
308	 * Find the backing store object and offset into it to begin the
309	 * search.
310	 */
311	fs.map = map;
312	result = vm_map_lookup(&fs.map, vaddr, fault_type, &fs.entry,
313	    &fs.first_object, &fs.first_pindex, &prot, &wired);
314	if (result != KERN_SUCCESS) {
315		if (growstack && result == KERN_INVALID_ADDRESS &&
316		    map != kernel_map) {
317			result = vm_map_growstack(curproc, vaddr);
318			if (result != KERN_SUCCESS)
319				return (KERN_FAILURE);
320			growstack = FALSE;
321			goto RetryFault;
322		}
323		return (result);
324	}
325
326	map_generation = fs.map->timestamp;
327
328	if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
329		panic("vm_fault: fault on nofault entry, addr: %lx",
330		    (u_long)vaddr);
331	}
332
333	if (fs.entry->eflags & MAP_ENTRY_IN_TRANSITION &&
334	    fs.entry->wiring_thread != curthread) {
335		vm_map_unlock_read(fs.map);
336		vm_map_lock(fs.map);
337		if (vm_map_lookup_entry(fs.map, vaddr, &fs.entry) &&
338		    (fs.entry->eflags & MAP_ENTRY_IN_TRANSITION)) {
339			if (fs.vp != NULL) {
340				vput(fs.vp);
341				fs.vp = NULL;
342			}
343			fs.entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
344			vm_map_unlock_and_wait(fs.map, 0);
345		} else
346			vm_map_unlock(fs.map);
347		goto RetryFault;
348	}
349
350	if (wired)
351		fault_type = prot | (fault_type & VM_PROT_COPY);
352	else
353		KASSERT((fault_flags & VM_FAULT_WIRE) == 0,
354		    ("!wired && VM_FAULT_WIRE"));
355
356	/*
357	 * Try to avoid lock contention on the top-level object through
358	 * special-case handling of some types of page faults, specifically,
359	 * those that are both (1) mapping an existing page from the top-
360	 * level object and (2) not having to mark that object as containing
361	 * dirty pages.  Under these conditions, a read lock on the top-level
362	 * object suffices, allowing multiple page faults of a similar type to
363	 * run in parallel on the same top-level object.
364	 */
365	if (fs.vp == NULL /* avoid locked vnode leak */ &&
366	    (fault_flags & (VM_FAULT_WIRE | VM_FAULT_DIRTY)) == 0 &&
367	    /* avoid calling vm_object_set_writeable_dirty() */
368	    ((prot & VM_PROT_WRITE) == 0 ||
369	    (fs.first_object->type != OBJT_VNODE &&
370	    (fs.first_object->flags & OBJ_TMPFS_NODE) == 0) ||
371	    (fs.first_object->flags & OBJ_MIGHTBEDIRTY) != 0)) {
372		VM_OBJECT_RLOCK(fs.first_object);
373		if ((prot & VM_PROT_WRITE) != 0 &&
374		    (fs.first_object->type == OBJT_VNODE ||
375		    (fs.first_object->flags & OBJ_TMPFS_NODE) != 0) &&
376		    (fs.first_object->flags & OBJ_MIGHTBEDIRTY) == 0)
377			goto fast_failed;
378		m = vm_page_lookup(fs.first_object, fs.first_pindex);
379		/* A busy page can be mapped for read|execute access. */
380		if (m == NULL || ((prot & VM_PROT_WRITE) != 0 &&
381		    vm_page_busied(m)) || m->valid != VM_PAGE_BITS_ALL)
382			goto fast_failed;
383		result = pmap_enter(fs.map->pmap, vaddr, m, prot,
384		   fault_type | PMAP_ENTER_NOSLEEP | (wired ? PMAP_ENTER_WIRED :
385		   0), 0);
386		if (result != KERN_SUCCESS)
387			goto fast_failed;
388		if (m_hold != NULL) {
389			*m_hold = m;
390			vm_page_lock(m);
391			vm_page_hold(m);
392			vm_page_unlock(m);
393		}
394		vm_fault_dirty(fs.entry, m, prot, fault_type, fault_flags,
395		    FALSE);
396		VM_OBJECT_RUNLOCK(fs.first_object);
397		if (!wired)
398			vm_fault_prefault(&fs, vaddr, 0, 0);
399		vm_map_lookup_done(fs.map, fs.entry);
400		curthread->td_ru.ru_minflt++;
401		return (KERN_SUCCESS);
402fast_failed:
403		if (!VM_OBJECT_TRYUPGRADE(fs.first_object)) {
404			VM_OBJECT_RUNLOCK(fs.first_object);
405			VM_OBJECT_WLOCK(fs.first_object);
406		}
407	} else {
408		VM_OBJECT_WLOCK(fs.first_object);
409	}
410
411	/*
412	 * Make a reference to this object to prevent its disposal while we
413	 * are messing with it.  Once we have the reference, the map is free
414	 * to be diddled.  Since objects reference their shadows (and copies),
415	 * they will stay around as well.
416	 *
417	 * Bump the paging-in-progress count to prevent size changes (e.g.
418	 * truncation operations) during I/O.  This must be done after
419	 * obtaining the vnode lock in order to avoid possible deadlocks.
420	 */
421	vm_object_reference_locked(fs.first_object);
422	vm_object_pip_add(fs.first_object, 1);
423
424	fs.lookup_still_valid = TRUE;
425
426	fs.first_m = NULL;
427
428	/*
429	 * Search for the page at object/offset.
430	 */
431	fs.object = fs.first_object;
432	fs.pindex = fs.first_pindex;
433	while (TRUE) {
434		/*
435		 * If the object is marked for imminent termination,
436		 * we retry here, since the collapse pass has raced
437		 * with us.  Otherwise, if we see terminally dead
438		 * object, return fail.
439		 */
440		if ((fs.object->flags & OBJ_DEAD) != 0) {
441			dead = fs.object->type == OBJT_DEAD;
442			unlock_and_deallocate(&fs);
443			if (dead)
444				return (KERN_PROTECTION_FAILURE);
445			pause("vmf_de", 1);
446			goto RetryFault;
447		}
448
449		/*
450		 * See if page is resident
451		 */
452		fs.m = vm_page_lookup(fs.object, fs.pindex);
453		if (fs.m != NULL) {
454			/*
455			 * Wait/Retry if the page is busy.  We have to do this
456			 * if the page is either exclusive or shared busy
457			 * because the vm_pager may be using read busy for
458			 * pageouts (and even pageins if it is the vnode
459			 * pager), and we could end up trying to pagein and
460			 * pageout the same page simultaneously.
461			 *
462			 * We can theoretically allow the busy case on a read
463			 * fault if the page is marked valid, but since such
464			 * pages are typically already pmap'd, putting that
465			 * special case in might be more effort then it is
466			 * worth.  We cannot under any circumstances mess
467			 * around with a shared busied page except, perhaps,
468			 * to pmap it.
469			 */
470			if (vm_page_busied(fs.m)) {
471				/*
472				 * Reference the page before unlocking and
473				 * sleeping so that the page daemon is less
474				 * likely to reclaim it.
475				 */
476				vm_page_aflag_set(fs.m, PGA_REFERENCED);
477				if (fs.object != fs.first_object) {
478					if (!VM_OBJECT_TRYWLOCK(
479					    fs.first_object)) {
480						VM_OBJECT_WUNLOCK(fs.object);
481						VM_OBJECT_WLOCK(fs.first_object);
482						VM_OBJECT_WLOCK(fs.object);
483					}
484					vm_page_lock(fs.first_m);
485					vm_page_free(fs.first_m);
486					vm_page_unlock(fs.first_m);
487					vm_object_pip_wakeup(fs.first_object);
488					VM_OBJECT_WUNLOCK(fs.first_object);
489					fs.first_m = NULL;
490				}
491				unlock_map(&fs);
492				if (fs.m == vm_page_lookup(fs.object,
493				    fs.pindex)) {
494					vm_page_sleep_if_busy(fs.m, "vmpfw");
495				}
496				vm_object_pip_wakeup(fs.object);
497				VM_OBJECT_WUNLOCK(fs.object);
498				PCPU_INC(cnt.v_intrans);
499				vm_object_deallocate(fs.first_object);
500				goto RetryFault;
501			}
502			vm_page_lock(fs.m);
503			vm_page_remque(fs.m);
504			vm_page_unlock(fs.m);
505
506			/*
507			 * Mark page busy for other processes, and the
508			 * pagedaemon.  If it still isn't completely valid
509			 * (readable), jump to readrest, else break-out ( we
510			 * found the page ).
511			 */
512			vm_page_xbusy(fs.m);
513			if (fs.m->valid != VM_PAGE_BITS_ALL)
514				goto readrest;
515			break;
516		}
517
518		/*
519		 * Page is not resident.  If this is the search termination
520		 * or the pager might contain the page, allocate a new page.
521		 * Default objects are zero-fill, there is no real pager.
522		 */
523		if (fs.object->type != OBJT_DEFAULT ||
524		    fs.object == fs.first_object) {
525			if (fs.pindex >= fs.object->size) {
526				unlock_and_deallocate(&fs);
527				return (KERN_PROTECTION_FAILURE);
528			}
529
530			/*
531			 * Allocate a new page for this object/offset pair.
532			 *
533			 * Unlocked read of the p_flag is harmless. At
534			 * worst, the P_KILLED might be not observed
535			 * there, and allocation can fail, causing
536			 * restart and new reading of the p_flag.
537			 */
538			fs.m = NULL;
539			if (!vm_page_count_severe() || P_KILLED(curproc)) {
540#if VM_NRESERVLEVEL > 0
541				if ((fs.object->flags & OBJ_COLORED) == 0) {
542					fs.object->flags |= OBJ_COLORED;
543					fs.object->pg_color = atop(vaddr) -
544					    fs.pindex;
545				}
546#endif
547				alloc_req = P_KILLED(curproc) ?
548				    VM_ALLOC_SYSTEM : VM_ALLOC_NORMAL;
549				if (fs.object->type != OBJT_VNODE &&
550				    fs.object->backing_object == NULL)
551					alloc_req |= VM_ALLOC_ZERO;
552				fs.m = vm_page_alloc(fs.object, fs.pindex,
553				    alloc_req);
554			}
555			if (fs.m == NULL) {
556				unlock_and_deallocate(&fs);
557				VM_WAITPFAULT;
558				goto RetryFault;
559			} else if (fs.m->valid == VM_PAGE_BITS_ALL)
560				break;
561		}
562
563readrest:
564		/*
565		 * We have found a valid page or we have allocated a new page.
566		 * The page thus may not be valid or may not be entirely
567		 * valid.
568		 *
569		 * Attempt to fault-in the page if there is a chance that the
570		 * pager has it, and potentially fault in additional pages
571		 * at the same time.  For default objects simply provide
572		 * zero-filled pages.
573		 */
574		if (fs.object->type != OBJT_DEFAULT) {
575			int rv;
576			u_char behavior = vm_map_entry_behavior(fs.entry);
577
578			if (behavior == MAP_ENTRY_BEHAV_RANDOM ||
579			    P_KILLED(curproc)) {
580				behind = 0;
581				ahead = 0;
582			} else if (behavior == MAP_ENTRY_BEHAV_SEQUENTIAL) {
583				behind = 0;
584				ahead = atop(fs.entry->end - vaddr) - 1;
585				if (ahead > VM_FAULT_READ_AHEAD_MAX)
586					ahead = VM_FAULT_READ_AHEAD_MAX;
587				if (fs.pindex == fs.entry->next_read)
588					vm_fault_cache_behind(&fs,
589					    VM_FAULT_READ_MAX);
590			} else {
591				/*
592				 * If this is a sequential page fault, then
593				 * arithmetically increase the number of pages
594				 * in the read-ahead window.  Otherwise, reset
595				 * the read-ahead window to its smallest size.
596				 */
597				behind = atop(vaddr - fs.entry->start);
598				if (behind > VM_FAULT_READ_BEHIND)
599					behind = VM_FAULT_READ_BEHIND;
600				ahead = atop(fs.entry->end - vaddr) - 1;
601				era = fs.entry->read_ahead;
602				if (fs.pindex == fs.entry->next_read) {
603					nera = era + behind;
604					if (nera > VM_FAULT_READ_AHEAD_MAX)
605						nera = VM_FAULT_READ_AHEAD_MAX;
606					behind = 0;
607					if (ahead > nera)
608						ahead = nera;
609					if (era == VM_FAULT_READ_AHEAD_MAX)
610						vm_fault_cache_behind(&fs,
611						    VM_FAULT_CACHE_BEHIND);
612				} else if (ahead > VM_FAULT_READ_AHEAD_MIN)
613					ahead = VM_FAULT_READ_AHEAD_MIN;
614				if (era != ahead)
615					fs.entry->read_ahead = ahead;
616			}
617
618			/*
619			 * Call the pager to retrieve the data, if any, after
620			 * releasing the lock on the map.  We hold a ref on
621			 * fs.object and the pages are exclusive busied.
622			 */
623			unlock_map(&fs);
624
625			if (fs.object->type == OBJT_VNODE) {
626				vp = fs.object->handle;
627				if (vp == fs.vp)
628					goto vnode_locked;
629				else if (fs.vp != NULL) {
630					vput(fs.vp);
631					fs.vp = NULL;
632				}
633				locked = VOP_ISLOCKED(vp);
634
635				if (locked != LK_EXCLUSIVE)
636					locked = LK_SHARED;
637				/* Do not sleep for vnode lock while fs.m is busy */
638				error = vget(vp, locked | LK_CANRECURSE |
639				    LK_NOWAIT, curthread);
640				if (error != 0) {
641					vhold(vp);
642					release_page(&fs);
643					unlock_and_deallocate(&fs);
644					error = vget(vp, locked | LK_RETRY |
645					    LK_CANRECURSE, curthread);
646					vdrop(vp);
647					fs.vp = vp;
648					KASSERT(error == 0,
649					    ("vm_fault: vget failed"));
650					goto RetryFault;
651				}
652				fs.vp = vp;
653			}
654vnode_locked:
655			KASSERT(fs.vp == NULL || !fs.map->system_map,
656			    ("vm_fault: vnode-backed object mapped by system map"));
657
658			/*
659			 * now we find out if any other pages should be paged
660			 * in at this time this routine checks to see if the
661			 * pages surrounding this fault reside in the same
662			 * object as the page for this fault.  If they do,
663			 * then they are faulted in also into the object.  The
664			 * array "marray" returned contains an array of
665			 * vm_page_t structs where one of them is the
666			 * vm_page_t passed to the routine.  The reqpage
667			 * return value is the index into the marray for the
668			 * vm_page_t passed to the routine.
669			 *
670			 * fs.m plus the additional pages are exclusive busied.
671			 */
672			faultcount = vm_fault_additional_pages(
673			    fs.m, behind, ahead, marray, &reqpage);
674
675			rv = faultcount ?
676			    vm_pager_get_pages(fs.object, marray, faultcount,
677				reqpage) : VM_PAGER_FAIL;
678
679			if (rv == VM_PAGER_OK) {
680				/*
681				 * Found the page. Leave it busy while we play
682				 * with it.
683				 */
684
685				/*
686				 * Relookup in case pager changed page. Pager
687				 * is responsible for disposition of old page
688				 * if moved.
689				 */
690				fs.m = vm_page_lookup(fs.object, fs.pindex);
691				if (!fs.m) {
692					unlock_and_deallocate(&fs);
693					goto RetryFault;
694				}
695
696				hardfault++;
697				break; /* break to PAGE HAS BEEN FOUND */
698			}
699			/*
700			 * Remove the bogus page (which does not exist at this
701			 * object/offset); before doing so, we must get back
702			 * our object lock to preserve our invariant.
703			 *
704			 * Also wake up any other process that may want to bring
705			 * in this page.
706			 *
707			 * If this is the top-level object, we must leave the
708			 * busy page to prevent another process from rushing
709			 * past us, and inserting the page in that object at
710			 * the same time that we are.
711			 */
712			if (rv == VM_PAGER_ERROR)
713				printf("vm_fault: pager read error, pid %d (%s)\n",
714				    curproc->p_pid, curproc->p_comm);
715			/*
716			 * Data outside the range of the pager or an I/O error
717			 */
718			/*
719			 * XXX - the check for kernel_map is a kludge to work
720			 * around having the machine panic on a kernel space
721			 * fault w/ I/O error.
722			 */
723			if (((fs.map != kernel_map) && (rv == VM_PAGER_ERROR)) ||
724				(rv == VM_PAGER_BAD)) {
725				vm_page_lock(fs.m);
726				vm_page_free(fs.m);
727				vm_page_unlock(fs.m);
728				fs.m = NULL;
729				unlock_and_deallocate(&fs);
730				return ((rv == VM_PAGER_ERROR) ? KERN_FAILURE : KERN_PROTECTION_FAILURE);
731			}
732			if (fs.object != fs.first_object) {
733				vm_page_lock(fs.m);
734				vm_page_free(fs.m);
735				vm_page_unlock(fs.m);
736				fs.m = NULL;
737				/*
738				 * XXX - we cannot just fall out at this
739				 * point, m has been freed and is invalid!
740				 */
741			}
742		}
743
744		/*
745		 * We get here if the object has default pager (or unwiring)
746		 * or the pager doesn't have the page.
747		 */
748		if (fs.object == fs.first_object)
749			fs.first_m = fs.m;
750
751		/*
752		 * Move on to the next object.  Lock the next object before
753		 * unlocking the current one.
754		 */
755		fs.pindex += OFF_TO_IDX(fs.object->backing_object_offset);
756		next_object = fs.object->backing_object;
757		if (next_object == NULL) {
758			/*
759			 * If there's no object left, fill the page in the top
760			 * object with zeros.
761			 */
762			if (fs.object != fs.first_object) {
763				vm_object_pip_wakeup(fs.object);
764				VM_OBJECT_WUNLOCK(fs.object);
765
766				fs.object = fs.first_object;
767				fs.pindex = fs.first_pindex;
768				fs.m = fs.first_m;
769				VM_OBJECT_WLOCK(fs.object);
770			}
771			fs.first_m = NULL;
772
773			/*
774			 * Zero the page if necessary and mark it valid.
775			 */
776			if ((fs.m->flags & PG_ZERO) == 0) {
777				pmap_zero_page(fs.m);
778			} else {
779				PCPU_INC(cnt.v_ozfod);
780			}
781			PCPU_INC(cnt.v_zfod);
782			fs.m->valid = VM_PAGE_BITS_ALL;
783			/* Don't try to prefault neighboring pages. */
784			faultcount = 1;
785			break;	/* break to PAGE HAS BEEN FOUND */
786		} else {
787			KASSERT(fs.object != next_object,
788			    ("object loop %p", next_object));
789			VM_OBJECT_WLOCK(next_object);
790			vm_object_pip_add(next_object, 1);
791			if (fs.object != fs.first_object)
792				vm_object_pip_wakeup(fs.object);
793			VM_OBJECT_WUNLOCK(fs.object);
794			fs.object = next_object;
795		}
796	}
797
798	vm_page_assert_xbusied(fs.m);
799
800	/*
801	 * PAGE HAS BEEN FOUND. [Loop invariant still holds -- the object lock
802	 * is held.]
803	 */
804
805	/*
806	 * If the page is being written, but isn't already owned by the
807	 * top-level object, we have to copy it into a new page owned by the
808	 * top-level object.
809	 */
810	if (fs.object != fs.first_object) {
811		/*
812		 * We only really need to copy if we want to write it.
813		 */
814		if ((fault_type & (VM_PROT_COPY | VM_PROT_WRITE)) != 0) {
815			/*
816			 * This allows pages to be virtually copied from a
817			 * backing_object into the first_object, where the
818			 * backing object has no other refs to it, and cannot
819			 * gain any more refs.  Instead of a bcopy, we just
820			 * move the page from the backing object to the
821			 * first object.  Note that we must mark the page
822			 * dirty in the first object so that it will go out
823			 * to swap when needed.
824			 */
825			is_first_object_locked = FALSE;
826			if (
827				/*
828				 * Only one shadow object
829				 */
830				(fs.object->shadow_count == 1) &&
831				/*
832				 * No COW refs, except us
833				 */
834				(fs.object->ref_count == 1) &&
835				/*
836				 * No one else can look this object up
837				 */
838				(fs.object->handle == NULL) &&
839				/*
840				 * No other ways to look the object up
841				 */
842				((fs.object->type == OBJT_DEFAULT) ||
843				 (fs.object->type == OBJT_SWAP)) &&
844			    (is_first_object_locked = VM_OBJECT_TRYWLOCK(fs.first_object)) &&
845				/*
846				 * We don't chase down the shadow chain
847				 */
848			    fs.object == fs.first_object->backing_object) {
849				/*
850				 * get rid of the unnecessary page
851				 */
852				vm_page_lock(fs.first_m);
853				vm_page_free(fs.first_m);
854				vm_page_unlock(fs.first_m);
855				/*
856				 * grab the page and put it into the
857				 * process'es object.  The page is
858				 * automatically made dirty.
859				 */
860				if (vm_page_rename(fs.m, fs.first_object,
861				    fs.first_pindex)) {
862					unlock_and_deallocate(&fs);
863					goto RetryFault;
864				}
865#if VM_NRESERVLEVEL > 0
866				/*
867				 * Rename the reservation.
868				 */
869				vm_reserv_rename(fs.m, fs.first_object,
870				    fs.object, OFF_TO_IDX(
871				    fs.first_object->backing_object_offset));
872#endif
873				vm_page_xbusy(fs.m);
874				fs.first_m = fs.m;
875				fs.m = NULL;
876				PCPU_INC(cnt.v_cow_optim);
877			} else {
878				/*
879				 * Oh, well, lets copy it.
880				 */
881				pmap_copy_page(fs.m, fs.first_m);
882				fs.first_m->valid = VM_PAGE_BITS_ALL;
883				if (wired && (fault_flags &
884				    VM_FAULT_WIRE) == 0) {
885					vm_page_lock(fs.first_m);
886					vm_page_wire(fs.first_m);
887					vm_page_unlock(fs.first_m);
888
889					vm_page_lock(fs.m);
890					vm_page_unwire(fs.m, FALSE);
891					vm_page_unlock(fs.m);
892				}
893				/*
894				 * We no longer need the old page or object.
895				 */
896				release_page(&fs);
897			}
898			/*
899			 * fs.object != fs.first_object due to above
900			 * conditional
901			 */
902			vm_object_pip_wakeup(fs.object);
903			VM_OBJECT_WUNLOCK(fs.object);
904			/*
905			 * Only use the new page below...
906			 */
907			fs.object = fs.first_object;
908			fs.pindex = fs.first_pindex;
909			fs.m = fs.first_m;
910			if (!is_first_object_locked)
911				VM_OBJECT_WLOCK(fs.object);
912			PCPU_INC(cnt.v_cow_faults);
913			curthread->td_cow++;
914		} else {
915			prot &= ~VM_PROT_WRITE;
916		}
917	}
918
919	/*
920	 * We must verify that the maps have not changed since our last
921	 * lookup.
922	 */
923	if (!fs.lookup_still_valid) {
924		vm_object_t retry_object;
925		vm_pindex_t retry_pindex;
926		vm_prot_t retry_prot;
927
928		if (!vm_map_trylock_read(fs.map)) {
929			release_page(&fs);
930			unlock_and_deallocate(&fs);
931			goto RetryFault;
932		}
933		fs.lookup_still_valid = TRUE;
934		if (fs.map->timestamp != map_generation) {
935			result = vm_map_lookup_locked(&fs.map, vaddr, fault_type,
936			    &fs.entry, &retry_object, &retry_pindex, &retry_prot, &wired);
937
938			/*
939			 * If we don't need the page any longer, put it on the inactive
940			 * list (the easiest thing to do here).  If no one needs it,
941			 * pageout will grab it eventually.
942			 */
943			if (result != KERN_SUCCESS) {
944				release_page(&fs);
945				unlock_and_deallocate(&fs);
946
947				/*
948				 * If retry of map lookup would have blocked then
949				 * retry fault from start.
950				 */
951				if (result == KERN_FAILURE)
952					goto RetryFault;
953				return (result);
954			}
955			if ((retry_object != fs.first_object) ||
956			    (retry_pindex != fs.first_pindex)) {
957				release_page(&fs);
958				unlock_and_deallocate(&fs);
959				goto RetryFault;
960			}
961
962			/*
963			 * Check whether the protection has changed or the object has
964			 * been copied while we left the map unlocked. Changing from
965			 * read to write permission is OK - we leave the page
966			 * write-protected, and catch the write fault. Changing from
967			 * write to read permission means that we can't mark the page
968			 * write-enabled after all.
969			 */
970			prot &= retry_prot;
971		}
972	}
973	/*
974	 * If the page was filled by a pager, update the map entry's
975	 * last read offset.  Since the pager does not return the
976	 * actual set of pages that it read, this update is based on
977	 * the requested set.  Typically, the requested and actual
978	 * sets are the same.
979	 *
980	 * XXX The following assignment modifies the map
981	 * without holding a write lock on it.
982	 */
983	if (hardfault)
984		fs.entry->next_read = fs.pindex + faultcount - reqpage;
985
986	vm_fault_dirty(fs.entry, fs.m, prot, fault_type, fault_flags, TRUE);
987	vm_page_assert_xbusied(fs.m);
988
989	/*
990	 * Page must be completely valid or it is not fit to
991	 * map into user space.  vm_pager_get_pages() ensures this.
992	 */
993	KASSERT(fs.m->valid == VM_PAGE_BITS_ALL,
994	    ("vm_fault: page %p partially invalid", fs.m));
995	VM_OBJECT_WUNLOCK(fs.object);
996
997	/*
998	 * Put this page into the physical map.  We had to do the unlock above
999	 * because pmap_enter() may sleep.  We don't put the page
1000	 * back on the active queue until later so that the pageout daemon
1001	 * won't find it (yet).
1002	 */
1003	pmap_enter(fs.map->pmap, vaddr, fs.m, prot,
1004	    fault_type | (wired ? PMAP_ENTER_WIRED : 0), 0);
1005	if (faultcount != 1 && (fault_flags & VM_FAULT_WIRE) == 0 &&
1006	    wired == 0)
1007		vm_fault_prefault(&fs, vaddr, faultcount, reqpage);
1008	VM_OBJECT_WLOCK(fs.object);
1009	vm_page_lock(fs.m);
1010
1011	/*
1012	 * If the page is not wired down, then put it where the pageout daemon
1013	 * can find it.
1014	 */
1015	if ((fault_flags & VM_FAULT_WIRE) != 0) {
1016		KASSERT(wired, ("VM_FAULT_WIRE && !wired"));
1017		vm_page_wire(fs.m);
1018	} else
1019		vm_page_activate(fs.m);
1020	if (m_hold != NULL) {
1021		*m_hold = fs.m;
1022		vm_page_hold(fs.m);
1023	}
1024	vm_page_unlock(fs.m);
1025	vm_page_xunbusy(fs.m);
1026
1027	/*
1028	 * Unlock everything, and return
1029	 */
1030	unlock_and_deallocate(&fs);
1031	if (hardfault) {
1032		PCPU_INC(cnt.v_io_faults);
1033		curthread->td_ru.ru_majflt++;
1034	} else
1035		curthread->td_ru.ru_minflt++;
1036
1037	return (KERN_SUCCESS);
1038}
1039
1040/*
1041 * Speed up the reclamation of up to "distance" pages that precede the
1042 * faulting pindex within the first object of the shadow chain.
1043 */
1044static void
1045vm_fault_cache_behind(const struct faultstate *fs, int distance)
1046{
1047	vm_object_t first_object, object;
1048	vm_page_t m, m_prev;
1049	vm_pindex_t pindex;
1050
1051	object = fs->object;
1052	VM_OBJECT_ASSERT_WLOCKED(object);
1053	first_object = fs->first_object;
1054	if (first_object != object) {
1055		if (!VM_OBJECT_TRYWLOCK(first_object)) {
1056			VM_OBJECT_WUNLOCK(object);
1057			VM_OBJECT_WLOCK(first_object);
1058			VM_OBJECT_WLOCK(object);
1059		}
1060	}
1061	/* Neither fictitious nor unmanaged pages can be cached. */
1062	if ((first_object->flags & (OBJ_FICTITIOUS | OBJ_UNMANAGED)) == 0) {
1063		if (fs->first_pindex < distance)
1064			pindex = 0;
1065		else
1066			pindex = fs->first_pindex - distance;
1067		if (pindex < OFF_TO_IDX(fs->entry->offset))
1068			pindex = OFF_TO_IDX(fs->entry->offset);
1069		m = first_object != object ? fs->first_m : fs->m;
1070		vm_page_assert_xbusied(m);
1071		m_prev = vm_page_prev(m);
1072		while ((m = m_prev) != NULL && m->pindex >= pindex &&
1073		    m->valid == VM_PAGE_BITS_ALL) {
1074			m_prev = vm_page_prev(m);
1075			if (vm_page_busied(m))
1076				continue;
1077			vm_page_lock(m);
1078			if (m->hold_count == 0 && m->wire_count == 0) {
1079				pmap_remove_all(m);
1080				vm_page_aflag_clear(m, PGA_REFERENCED);
1081				if (m->dirty != 0)
1082					vm_page_deactivate(m);
1083				else
1084					vm_page_cache(m);
1085			}
1086			vm_page_unlock(m);
1087		}
1088	}
1089	if (first_object != object)
1090		VM_OBJECT_WUNLOCK(first_object);
1091}
1092
1093/*
1094 * vm_fault_prefault provides a quick way of clustering
1095 * pagefaults into a processes address space.  It is a "cousin"
1096 * of vm_map_pmap_enter, except it runs at page fault time instead
1097 * of mmap time.
1098 */
1099static void
1100vm_fault_prefault(const struct faultstate *fs, vm_offset_t addra,
1101    int faultcount, int reqpage)
1102{
1103	pmap_t pmap;
1104	vm_map_entry_t entry;
1105	vm_object_t backing_object, lobject;
1106	vm_offset_t addr, starta;
1107	vm_pindex_t pindex;
1108	vm_page_t m;
1109	int backward, forward, i;
1110
1111	pmap = fs->map->pmap;
1112	if (pmap != vmspace_pmap(curthread->td_proc->p_vmspace))
1113		return;
1114
1115	if (faultcount > 0) {
1116		backward = reqpage;
1117		forward = faultcount - reqpage - 1;
1118	} else {
1119		backward = PFBAK;
1120		forward = PFFOR;
1121	}
1122	entry = fs->entry;
1123
1124	starta = addra - backward * PAGE_SIZE;
1125	if (starta < entry->start) {
1126		starta = entry->start;
1127	} else if (starta > addra) {
1128		starta = 0;
1129	}
1130
1131	/*
1132	 * Generate the sequence of virtual addresses that are candidates for
1133	 * prefaulting in an outward spiral from the faulting virtual address,
1134	 * "addra".  Specifically, the sequence is "addra - PAGE_SIZE", "addra
1135	 * + PAGE_SIZE", "addra - 2 * PAGE_SIZE", "addra + 2 * PAGE_SIZE", ...
1136	 * If the candidate address doesn't have a backing physical page, then
1137	 * the loop immediately terminates.
1138	 */
1139	for (i = 0; i < 2 * imax(backward, forward); i++) {
1140		addr = addra + ((i >> 1) + 1) * ((i & 1) == 0 ? -PAGE_SIZE :
1141		    PAGE_SIZE);
1142		if (addr > addra + forward * PAGE_SIZE)
1143			addr = 0;
1144
1145		if (addr < starta || addr >= entry->end)
1146			continue;
1147
1148		if (!pmap_is_prefaultable(pmap, addr))
1149			continue;
1150
1151		pindex = ((addr - entry->start) + entry->offset) >> PAGE_SHIFT;
1152		lobject = entry->object.vm_object;
1153		VM_OBJECT_RLOCK(lobject);
1154		while ((m = vm_page_lookup(lobject, pindex)) == NULL &&
1155		    lobject->type == OBJT_DEFAULT &&
1156		    (backing_object = lobject->backing_object) != NULL) {
1157			KASSERT((lobject->backing_object_offset & PAGE_MASK) ==
1158			    0, ("vm_fault_prefault: unaligned object offset"));
1159			pindex += lobject->backing_object_offset >> PAGE_SHIFT;
1160			VM_OBJECT_RLOCK(backing_object);
1161			VM_OBJECT_RUNLOCK(lobject);
1162			lobject = backing_object;
1163		}
1164		if (m == NULL) {
1165			VM_OBJECT_RUNLOCK(lobject);
1166			break;
1167		}
1168		if (m->valid == VM_PAGE_BITS_ALL &&
1169		    (m->flags & PG_FICTITIOUS) == 0)
1170			pmap_enter_quick(pmap, addr, m, entry->protection);
1171		VM_OBJECT_RUNLOCK(lobject);
1172	}
1173}
1174
1175/*
1176 * Hold each of the physical pages that are mapped by the specified range of
1177 * virtual addresses, ["addr", "addr" + "len"), if those mappings are valid
1178 * and allow the specified types of access, "prot".  If all of the implied
1179 * pages are successfully held, then the number of held pages is returned
1180 * together with pointers to those pages in the array "ma".  However, if any
1181 * of the pages cannot be held, -1 is returned.
1182 */
1183int
1184vm_fault_quick_hold_pages(vm_map_t map, vm_offset_t addr, vm_size_t len,
1185    vm_prot_t prot, vm_page_t *ma, int max_count)
1186{
1187	vm_offset_t end, va;
1188	vm_page_t *mp;
1189	int count;
1190	boolean_t pmap_failed;
1191
1192	if (len == 0)
1193		return (0);
1194	end = round_page(addr + len);
1195	addr = trunc_page(addr);
1196
1197	/*
1198	 * Check for illegal addresses.
1199	 */
1200	if (addr < vm_map_min(map) || addr > end || end > vm_map_max(map))
1201		return (-1);
1202
1203	if (atop(end - addr) > max_count)
1204		panic("vm_fault_quick_hold_pages: count > max_count");
1205	count = atop(end - addr);
1206
1207	/*
1208	 * Most likely, the physical pages are resident in the pmap, so it is
1209	 * faster to try pmap_extract_and_hold() first.
1210	 */
1211	pmap_failed = FALSE;
1212	for (mp = ma, va = addr; va < end; mp++, va += PAGE_SIZE) {
1213		*mp = pmap_extract_and_hold(map->pmap, va, prot);
1214		if (*mp == NULL)
1215			pmap_failed = TRUE;
1216		else if ((prot & VM_PROT_WRITE) != 0 &&
1217		    (*mp)->dirty != VM_PAGE_BITS_ALL) {
1218			/*
1219			 * Explicitly dirty the physical page.  Otherwise, the
1220			 * caller's changes may go unnoticed because they are
1221			 * performed through an unmanaged mapping or by a DMA
1222			 * operation.
1223			 *
1224			 * The object lock is not held here.
1225			 * See vm_page_clear_dirty_mask().
1226			 */
1227			vm_page_dirty(*mp);
1228		}
1229	}
1230	if (pmap_failed) {
1231		/*
1232		 * One or more pages could not be held by the pmap.  Either no
1233		 * page was mapped at the specified virtual address or that
1234		 * mapping had insufficient permissions.  Attempt to fault in
1235		 * and hold these pages.
1236		 */
1237		for (mp = ma, va = addr; va < end; mp++, va += PAGE_SIZE)
1238			if (*mp == NULL && vm_fault_hold(map, va, prot,
1239			    VM_FAULT_NORMAL, mp) != KERN_SUCCESS)
1240				goto error;
1241	}
1242	return (count);
1243error:
1244	for (mp = ma; mp < ma + count; mp++)
1245		if (*mp != NULL) {
1246			vm_page_lock(*mp);
1247			vm_page_unhold(*mp);
1248			vm_page_unlock(*mp);
1249		}
1250	return (-1);
1251}
1252
1253/*
1254 *	Routine:
1255 *		vm_fault_copy_entry
1256 *	Function:
1257 *		Create new shadow object backing dst_entry with private copy of
1258 *		all underlying pages. When src_entry is equal to dst_entry,
1259 *		function implements COW for wired-down map entry. Otherwise,
1260 *		it forks wired entry into dst_map.
1261 *
1262 *	In/out conditions:
1263 *		The source and destination maps must be locked for write.
1264 *		The source map entry must be wired down (or be a sharing map
1265 *		entry corresponding to a main map entry that is wired down).
1266 */
1267void
1268vm_fault_copy_entry(vm_map_t dst_map, vm_map_t src_map,
1269    vm_map_entry_t dst_entry, vm_map_entry_t src_entry,
1270    vm_ooffset_t *fork_charge)
1271{
1272	vm_object_t backing_object, dst_object, object, src_object;
1273	vm_pindex_t dst_pindex, pindex, src_pindex;
1274	vm_prot_t access, prot;
1275	vm_offset_t vaddr;
1276	vm_page_t dst_m;
1277	vm_page_t src_m;
1278	boolean_t upgrade;
1279
1280#ifdef	lint
1281	src_map++;
1282#endif	/* lint */
1283
1284	upgrade = src_entry == dst_entry;
1285	access = prot = dst_entry->protection;
1286
1287	src_object = src_entry->object.vm_object;
1288	src_pindex = OFF_TO_IDX(src_entry->offset);
1289
1290	if (upgrade && (dst_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) {
1291		dst_object = src_object;
1292		vm_object_reference(dst_object);
1293	} else {
1294		/*
1295		 * Create the top-level object for the destination entry. (Doesn't
1296		 * actually shadow anything - we copy the pages directly.)
1297		 */
1298		dst_object = vm_object_allocate(OBJT_DEFAULT,
1299		    OFF_TO_IDX(dst_entry->end - dst_entry->start));
1300#if VM_NRESERVLEVEL > 0
1301		dst_object->flags |= OBJ_COLORED;
1302		dst_object->pg_color = atop(dst_entry->start);
1303#endif
1304	}
1305
1306	VM_OBJECT_WLOCK(dst_object);
1307	KASSERT(upgrade || dst_entry->object.vm_object == NULL,
1308	    ("vm_fault_copy_entry: vm_object not NULL"));
1309	if (src_object != dst_object) {
1310		dst_entry->object.vm_object = dst_object;
1311		dst_entry->offset = 0;
1312		dst_object->charge = dst_entry->end - dst_entry->start;
1313	}
1314	if (fork_charge != NULL) {
1315		KASSERT(dst_entry->cred == NULL,
1316		    ("vm_fault_copy_entry: leaked swp charge"));
1317		dst_object->cred = curthread->td_ucred;
1318		crhold(dst_object->cred);
1319		*fork_charge += dst_object->charge;
1320	} else if (dst_object->cred == NULL) {
1321		KASSERT(dst_entry->cred != NULL, ("no cred for entry %p",
1322		    dst_entry));
1323		dst_object->cred = dst_entry->cred;
1324		dst_entry->cred = NULL;
1325	}
1326
1327	/*
1328	 * If not an upgrade, then enter the mappings in the pmap as
1329	 * read and/or execute accesses.  Otherwise, enter them as
1330	 * write accesses.
1331	 *
1332	 * A writeable large page mapping is only created if all of
1333	 * the constituent small page mappings are modified. Marking
1334	 * PTEs as modified on inception allows promotion to happen
1335	 * without taking potentially large number of soft faults.
1336	 */
1337	if (!upgrade)
1338		access &= ~VM_PROT_WRITE;
1339
1340	/*
1341	 * Loop through all of the virtual pages within the entry's
1342	 * range, copying each page from the source object to the
1343	 * destination object.  Since the source is wired, those pages
1344	 * must exist.  In contrast, the destination is pageable.
1345	 * Since the destination object does share any backing storage
1346	 * with the source object, all of its pages must be dirtied,
1347	 * regardless of whether they can be written.
1348	 */
1349	for (vaddr = dst_entry->start, dst_pindex = 0;
1350	    vaddr < dst_entry->end;
1351	    vaddr += PAGE_SIZE, dst_pindex++) {
1352again:
1353		/*
1354		 * Find the page in the source object, and copy it in.
1355		 * Because the source is wired down, the page will be
1356		 * in memory.
1357		 */
1358		if (src_object != dst_object)
1359			VM_OBJECT_RLOCK(src_object);
1360		object = src_object;
1361		pindex = src_pindex + dst_pindex;
1362		while ((src_m = vm_page_lookup(object, pindex)) == NULL &&
1363		    (backing_object = object->backing_object) != NULL) {
1364			/*
1365			 * Unless the source mapping is read-only or
1366			 * it is presently being upgraded from
1367			 * read-only, the first object in the shadow
1368			 * chain should provide all of the pages.  In
1369			 * other words, this loop body should never be
1370			 * executed when the source mapping is already
1371			 * read/write.
1372			 */
1373			KASSERT((src_entry->protection & VM_PROT_WRITE) == 0 ||
1374			    upgrade,
1375			    ("vm_fault_copy_entry: main object missing page"));
1376
1377			VM_OBJECT_RLOCK(backing_object);
1378			pindex += OFF_TO_IDX(object->backing_object_offset);
1379			if (object != dst_object)
1380				VM_OBJECT_RUNLOCK(object);
1381			object = backing_object;
1382		}
1383		KASSERT(src_m != NULL, ("vm_fault_copy_entry: page missing"));
1384
1385		if (object != dst_object) {
1386			/*
1387			 * Allocate a page in the destination object.
1388			 */
1389			dst_m = vm_page_alloc(dst_object, (src_object ==
1390			    dst_object ? src_pindex : 0) + dst_pindex,
1391			    VM_ALLOC_NORMAL);
1392			if (dst_m == NULL) {
1393				VM_OBJECT_WUNLOCK(dst_object);
1394				VM_OBJECT_RUNLOCK(object);
1395				VM_WAIT;
1396				VM_OBJECT_WLOCK(dst_object);
1397				goto again;
1398			}
1399			pmap_copy_page(src_m, dst_m);
1400			VM_OBJECT_RUNLOCK(object);
1401			dst_m->valid = VM_PAGE_BITS_ALL;
1402			dst_m->dirty = VM_PAGE_BITS_ALL;
1403		} else {
1404			dst_m = src_m;
1405			if (vm_page_sleep_if_busy(dst_m, "fltupg"))
1406				goto again;
1407			vm_page_xbusy(dst_m);
1408			KASSERT(dst_m->valid == VM_PAGE_BITS_ALL,
1409			    ("invalid dst page %p", dst_m));
1410		}
1411		VM_OBJECT_WUNLOCK(dst_object);
1412
1413		/*
1414		 * Enter it in the pmap. If a wired, copy-on-write
1415		 * mapping is being replaced by a write-enabled
1416		 * mapping, then wire that new mapping.
1417		 */
1418		pmap_enter(dst_map->pmap, vaddr, dst_m, prot,
1419		    access | (upgrade ? PMAP_ENTER_WIRED : 0), 0);
1420
1421		/*
1422		 * Mark it no longer busy, and put it on the active list.
1423		 */
1424		VM_OBJECT_WLOCK(dst_object);
1425
1426		if (upgrade) {
1427			if (src_m != dst_m) {
1428				vm_page_lock(src_m);
1429				vm_page_unwire(src_m, 0);
1430				vm_page_unlock(src_m);
1431				vm_page_lock(dst_m);
1432				vm_page_wire(dst_m);
1433				vm_page_unlock(dst_m);
1434			} else {
1435				KASSERT(dst_m->wire_count > 0,
1436				    ("dst_m %p is not wired", dst_m));
1437			}
1438		} else {
1439			vm_page_lock(dst_m);
1440			vm_page_activate(dst_m);
1441			vm_page_unlock(dst_m);
1442		}
1443		vm_page_xunbusy(dst_m);
1444	}
1445	VM_OBJECT_WUNLOCK(dst_object);
1446	if (upgrade) {
1447		dst_entry->eflags &= ~(MAP_ENTRY_COW | MAP_ENTRY_NEEDS_COPY);
1448		vm_object_deallocate(src_object);
1449	}
1450}
1451
1452
1453/*
1454 * This routine checks around the requested page for other pages that
1455 * might be able to be faulted in.  This routine brackets the viable
1456 * pages for the pages to be paged in.
1457 *
1458 * Inputs:
1459 *	m, rbehind, rahead
1460 *
1461 * Outputs:
1462 *  marray (array of vm_page_t), reqpage (index of requested page)
1463 *
1464 * Return value:
1465 *  number of pages in marray
1466 */
1467static int
1468vm_fault_additional_pages(m, rbehind, rahead, marray, reqpage)
1469	vm_page_t m;
1470	int rbehind;
1471	int rahead;
1472	vm_page_t *marray;
1473	int *reqpage;
1474{
1475	int i,j;
1476	vm_object_t object;
1477	vm_pindex_t pindex, startpindex, endpindex, tpindex;
1478	vm_page_t rtm;
1479	int cbehind, cahead;
1480
1481	VM_OBJECT_ASSERT_WLOCKED(m->object);
1482
1483	object = m->object;
1484	pindex = m->pindex;
1485	cbehind = cahead = 0;
1486
1487	/*
1488	 * if the requested page is not available, then give up now
1489	 */
1490	if (!vm_pager_has_page(object, pindex, &cbehind, &cahead)) {
1491		return 0;
1492	}
1493
1494	if ((cbehind == 0) && (cahead == 0)) {
1495		*reqpage = 0;
1496		marray[0] = m;
1497		return 1;
1498	}
1499
1500	if (rahead > cahead) {
1501		rahead = cahead;
1502	}
1503
1504	if (rbehind > cbehind) {
1505		rbehind = cbehind;
1506	}
1507
1508	/*
1509	 * scan backward for the read behind pages -- in memory
1510	 */
1511	if (pindex > 0) {
1512		if (rbehind > pindex) {
1513			rbehind = pindex;
1514			startpindex = 0;
1515		} else {
1516			startpindex = pindex - rbehind;
1517		}
1518
1519		if ((rtm = TAILQ_PREV(m, pglist, listq)) != NULL &&
1520		    rtm->pindex >= startpindex)
1521			startpindex = rtm->pindex + 1;
1522
1523		/* tpindex is unsigned; beware of numeric underflow. */
1524		for (i = 0, tpindex = pindex - 1; tpindex >= startpindex &&
1525		    tpindex < pindex; i++, tpindex--) {
1526
1527			rtm = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL |
1528			    VM_ALLOC_IFNOTCACHED);
1529			if (rtm == NULL) {
1530				/*
1531				 * Shift the allocated pages to the
1532				 * beginning of the array.
1533				 */
1534				for (j = 0; j < i; j++) {
1535					marray[j] = marray[j + tpindex + 1 -
1536					    startpindex];
1537				}
1538				break;
1539			}
1540
1541			marray[tpindex - startpindex] = rtm;
1542		}
1543	} else {
1544		startpindex = 0;
1545		i = 0;
1546	}
1547
1548	marray[i] = m;
1549	/* page offset of the required page */
1550	*reqpage = i;
1551
1552	tpindex = pindex + 1;
1553	i++;
1554
1555	/*
1556	 * scan forward for the read ahead pages
1557	 */
1558	endpindex = tpindex + rahead;
1559	if ((rtm = TAILQ_NEXT(m, listq)) != NULL && rtm->pindex < endpindex)
1560		endpindex = rtm->pindex;
1561	if (endpindex > object->size)
1562		endpindex = object->size;
1563
1564	for (; tpindex < endpindex; i++, tpindex++) {
1565
1566		rtm = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL |
1567		    VM_ALLOC_IFNOTCACHED);
1568		if (rtm == NULL) {
1569			break;
1570		}
1571
1572		marray[i] = rtm;
1573	}
1574
1575	/* return number of pages */
1576	return i;
1577}
1578
1579/*
1580 * Block entry into the machine-independent layer's page fault handler by
1581 * the calling thread.  Subsequent calls to vm_fault() by that thread will
1582 * return KERN_PROTECTION_FAILURE.  Enable machine-dependent handling of
1583 * spurious page faults.
1584 */
1585int
1586vm_fault_disable_pagefaults(void)
1587{
1588
1589	return (curthread_pflags_set(TDP_NOFAULTING | TDP_RESETSPUR));
1590}
1591
1592void
1593vm_fault_enable_pagefaults(int save)
1594{
1595
1596	curthread_pflags_restore(save);
1597}
1598