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