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