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