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