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