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