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