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