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