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