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