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