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