xref: /freebsd/sys/vm/vm_fault.c (revision 44d780e32b9d798a93b758fe0957d770e3190988)
1 /*-
2  * SPDX-License-Identifier: (BSD-4-Clause AND MIT-CMU)
3  *
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * Copyright (c) 1994 John S. Dyson
7  * All rights reserved.
8  * Copyright (c) 1994 David Greenman
9  * All rights reserved.
10  *
11  *
12  * This code is derived from software contributed to Berkeley by
13  * The Mach Operating System project at Carnegie-Mellon University.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  * 3. All advertising materials mentioning features or use of this software
24  *    must display the following acknowledgement:
25  *	This product includes software developed by the University of
26  *	California, Berkeley and its contributors.
27  * 4. Neither the name of the University nor the names of its contributors
28  *    may be used to endorse or promote products derived from this software
29  *    without specific prior written permission.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
32  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
35  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
37  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
39  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
40  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
41  * SUCH DAMAGE.
42  *
43  *	from: @(#)vm_fault.c	8.4 (Berkeley) 1/12/94
44  *
45  *
46  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
47  * All rights reserved.
48  *
49  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
50  *
51  * Permission to use, copy, modify and distribute this software and
52  * its documentation is hereby granted, provided that both the copyright
53  * notice and this permission notice appear in all copies of the
54  * software, derivative works or modified versions, and any portions
55  * thereof, and that both notices appear in supporting documentation.
56  *
57  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
58  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
59  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
60  *
61  * Carnegie Mellon requests users of this software to return to
62  *
63  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
64  *  School of Computer Science
65  *  Carnegie Mellon University
66  *  Pittsburgh PA 15213-3890
67  *
68  * any improvements or extensions that they make and grant Carnegie the
69  * rights to redistribute these changes.
70  */
71 
72 /*
73  *	Page fault handling module.
74  */
75 
76 #include <sys/cdefs.h>
77 __FBSDID("$FreeBSD$");
78 
79 #include "opt_ktrace.h"
80 #include "opt_vm.h"
81 
82 #include <sys/param.h>
83 #include <sys/systm.h>
84 #include <sys/kernel.h>
85 #include <sys/lock.h>
86 #include <sys/mman.h>
87 #include <sys/mutex.h>
88 #include <sys/proc.h>
89 #include <sys/racct.h>
90 #include <sys/refcount.h>
91 #include <sys/resourcevar.h>
92 #include <sys/rwlock.h>
93 #include <sys/signalvar.h>
94 #include <sys/sysctl.h>
95 #include <sys/sysent.h>
96 #include <sys/vmmeter.h>
97 #include <sys/vnode.h>
98 #ifdef KTRACE
99 #include <sys/ktrace.h>
100 #endif
101 
102 #include <vm/vm.h>
103 #include <vm/vm_param.h>
104 #include <vm/pmap.h>
105 #include <vm/vm_map.h>
106 #include <vm/vm_object.h>
107 #include <vm/vm_page.h>
108 #include <vm/vm_pageout.h>
109 #include <vm/vm_kern.h>
110 #include <vm/vm_pager.h>
111 #include <vm/vm_extern.h>
112 #include <vm/vm_reserv.h>
113 
114 #define PFBAK 4
115 #define PFFOR 4
116 
117 #define	VM_FAULT_READ_DEFAULT	(1 + VM_FAULT_READ_AHEAD_INIT)
118 #define	VM_FAULT_READ_MAX	(1 + VM_FAULT_READ_AHEAD_MAX)
119 
120 #define	VM_FAULT_DONTNEED_MIN	1048576
121 
122 struct faultstate {
123 	vm_page_t m;
124 	vm_object_t object;
125 	vm_pindex_t pindex;
126 	vm_page_t first_m;
127 	vm_object_t	first_object;
128 	vm_pindex_t first_pindex;
129 	vm_map_t map;
130 	vm_map_entry_t entry;
131 	int map_generation;
132 	bool lookup_still_valid;
133 	struct vnode *vp;
134 };
135 
136 static void vm_fault_dontneed(const struct faultstate *fs, vm_offset_t vaddr,
137 	    int ahead);
138 static void vm_fault_prefault(const struct faultstate *fs, vm_offset_t addra,
139 	    int backward, int forward, bool obj_locked);
140 
141 static int vm_pfault_oom_attempts = 3;
142 SYSCTL_INT(_vm, OID_AUTO, pfault_oom_attempts, CTLFLAG_RWTUN,
143     &vm_pfault_oom_attempts, 0,
144     "Number of page allocation attempts in page fault handler before it "
145     "triggers OOM handling");
146 
147 static int vm_pfault_oom_wait = 10;
148 SYSCTL_INT(_vm, OID_AUTO, pfault_oom_wait, CTLFLAG_RWTUN,
149     &vm_pfault_oom_wait, 0,
150     "Number of seconds to wait for free pages before retrying "
151     "the page fault handler");
152 
153 static inline void
154 release_page(struct faultstate *fs)
155 {
156 
157 	if (fs->m != NULL) {
158 		/*
159 		 * fs->m's object lock might not be held, so the page must be
160 		 * kept busy until we are done with it.
161 		 */
162 		vm_page_lock(fs->m);
163 		vm_page_deactivate(fs->m);
164 		vm_page_unlock(fs->m);
165 		vm_page_xunbusy(fs->m);
166 		fs->m = NULL;
167 	}
168 }
169 
170 static inline void
171 unlock_map(struct faultstate *fs)
172 {
173 
174 	if (fs->lookup_still_valid) {
175 		vm_map_lookup_done(fs->map, fs->entry);
176 		fs->lookup_still_valid = false;
177 	}
178 }
179 
180 static void
181 unlock_vp(struct faultstate *fs)
182 {
183 
184 	if (fs->vp != NULL) {
185 		vput(fs->vp);
186 		fs->vp = NULL;
187 	}
188 }
189 
190 static void
191 fault_deallocate(struct faultstate *fs)
192 {
193 
194 	vm_object_pip_wakeup(fs->object);
195 	if (fs->object != fs->first_object) {
196 		VM_OBJECT_WLOCK(fs->first_object);
197 		vm_page_free(fs->first_m);
198 		vm_object_pip_wakeup(fs->first_object);
199 		VM_OBJECT_WUNLOCK(fs->first_object);
200 		fs->first_m = NULL;
201 	}
202 	vm_object_deallocate(fs->first_object);
203 	unlock_map(fs);
204 	unlock_vp(fs);
205 }
206 
207 static void
208 unlock_and_deallocate(struct faultstate *fs)
209 {
210 
211 	VM_OBJECT_WUNLOCK(fs->object);
212 	fault_deallocate(fs);
213 }
214 
215 static void
216 vm_fault_dirty(vm_map_entry_t entry, vm_page_t m, vm_prot_t prot,
217     vm_prot_t fault_type, int fault_flags, bool excl)
218 {
219 	bool need_dirty;
220 
221 	if (((prot & VM_PROT_WRITE) == 0 &&
222 	    (fault_flags & VM_FAULT_DIRTY) == 0) ||
223 	    (m->oflags & VPO_UNMANAGED) != 0)
224 		return;
225 
226 	VM_OBJECT_ASSERT_LOCKED(m->object);
227 	VM_PAGE_OBJECT_BUSY_ASSERT(m);
228 
229 	need_dirty = ((fault_type & VM_PROT_WRITE) != 0 &&
230 	    (fault_flags & VM_FAULT_WIRE) == 0) ||
231 	    (fault_flags & VM_FAULT_DIRTY) != 0;
232 
233 	vm_object_set_writeable_dirty(m->object);
234 
235 	if (!excl)
236 		/*
237 		 * If two callers of vm_fault_dirty() with excl ==
238 		 * FALSE, one for the map entry with MAP_ENTRY_NOSYNC
239 		 * flag set, other with flag clear, race, it is
240 		 * possible for the no-NOSYNC thread to see m->dirty
241 		 * != 0 and not clear PGA_NOSYNC.  Take vm_page lock
242 		 * around manipulation of PGA_NOSYNC and
243 		 * vm_page_dirty() call to avoid the race.
244 		 */
245 		vm_page_lock(m);
246 
247 	/*
248 	 * If this is a NOSYNC mmap we do not want to set PGA_NOSYNC
249 	 * if the page is already dirty to prevent data written with
250 	 * the expectation of being synced from not being synced.
251 	 * Likewise if this entry does not request NOSYNC then make
252 	 * sure the page isn't marked NOSYNC.  Applications sharing
253 	 * data should use the same flags to avoid ping ponging.
254 	 */
255 	if ((entry->eflags & MAP_ENTRY_NOSYNC) != 0) {
256 		if (m->dirty == 0) {
257 			vm_page_aflag_set(m, PGA_NOSYNC);
258 		}
259 	} else {
260 		vm_page_aflag_clear(m, PGA_NOSYNC);
261 	}
262 
263 	/*
264 	 * If the fault is a write, we know that this page is being
265 	 * written NOW so dirty it explicitly to save on
266 	 * pmap_is_modified() calls later.
267 	 *
268 	 * Also, since the page is now dirty, we can possibly tell
269 	 * the pager to release any swap backing the page.  Calling
270 	 * the pager requires a write lock on the object.
271 	 */
272 	if (need_dirty)
273 		vm_page_dirty(m);
274 	if (!excl)
275 		vm_page_unlock(m);
276 	else if (need_dirty)
277 		vm_pager_page_unswapped(m);
278 }
279 
280 /*
281  * Unlocks fs.first_object and fs.map on success.
282  */
283 static int
284 vm_fault_soft_fast(struct faultstate *fs, vm_offset_t vaddr, vm_prot_t prot,
285     int fault_type, int fault_flags, boolean_t wired, vm_page_t *m_hold)
286 {
287 	vm_page_t m, m_map;
288 #if (defined(__aarch64__) || defined(__amd64__) || (defined(__arm__) && \
289     __ARM_ARCH >= 6) || defined(__i386__) || defined(__riscv)) && \
290     VM_NRESERVLEVEL > 0
291 	vm_page_t m_super;
292 	int flags;
293 #endif
294 	int psind, rv;
295 
296 	MPASS(fs->vp == NULL);
297 	vm_object_busy(fs->first_object);
298 	m = vm_page_lookup(fs->first_object, fs->first_pindex);
299 	/* A busy page can be mapped for read|execute access. */
300 	if (m == NULL || ((prot & VM_PROT_WRITE) != 0 &&
301 	    vm_page_busied(m)) || !vm_page_all_valid(m)) {
302 		rv = KERN_FAILURE;
303 		goto out;
304 	}
305 	m_map = m;
306 	psind = 0;
307 #if (defined(__aarch64__) || defined(__amd64__) || (defined(__arm__) && \
308     __ARM_ARCH >= 6) || defined(__i386__) || defined(__riscv)) && \
309     VM_NRESERVLEVEL > 0
310 	if ((m->flags & PG_FICTITIOUS) == 0 &&
311 	    (m_super = vm_reserv_to_superpage(m)) != NULL &&
312 	    rounddown2(vaddr, pagesizes[m_super->psind]) >= fs->entry->start &&
313 	    roundup2(vaddr + 1, pagesizes[m_super->psind]) <= fs->entry->end &&
314 	    (vaddr & (pagesizes[m_super->psind] - 1)) == (VM_PAGE_TO_PHYS(m) &
315 	    (pagesizes[m_super->psind] - 1)) && !wired &&
316 	    pmap_ps_enabled(fs->map->pmap)) {
317 		flags = PS_ALL_VALID;
318 		if ((prot & VM_PROT_WRITE) != 0) {
319 			/*
320 			 * Create a superpage mapping allowing write access
321 			 * only if none of the constituent pages are busy and
322 			 * all of them are already dirty (except possibly for
323 			 * the page that was faulted on).
324 			 */
325 			flags |= PS_NONE_BUSY;
326 			if ((fs->first_object->flags & OBJ_UNMANAGED) == 0)
327 				flags |= PS_ALL_DIRTY;
328 		}
329 		if (vm_page_ps_test(m_super, flags, m)) {
330 			m_map = m_super;
331 			psind = m_super->psind;
332 			vaddr = rounddown2(vaddr, pagesizes[psind]);
333 			/* Preset the modified bit for dirty superpages. */
334 			if ((flags & PS_ALL_DIRTY) != 0)
335 				fault_type |= VM_PROT_WRITE;
336 		}
337 	}
338 #endif
339 	rv = pmap_enter(fs->map->pmap, vaddr, m_map, prot, fault_type |
340 	    PMAP_ENTER_NOSLEEP | (wired ? PMAP_ENTER_WIRED : 0), psind);
341 	if (rv != KERN_SUCCESS)
342 		goto out;
343 	if (m_hold != NULL) {
344 		*m_hold = m;
345 		vm_page_wire(m);
346 	}
347 	vm_fault_dirty(fs->entry, m, prot, fault_type, fault_flags, false);
348 	if (psind == 0 && !wired)
349 		vm_fault_prefault(fs, vaddr, PFBAK, PFFOR, true);
350 	VM_OBJECT_RUNLOCK(fs->first_object);
351 	vm_map_lookup_done(fs->map, fs->entry);
352 	curthread->td_ru.ru_minflt++;
353 
354 out:
355 	vm_object_unbusy(fs->first_object);
356 	return (rv);
357 }
358 
359 static void
360 vm_fault_restore_map_lock(struct faultstate *fs)
361 {
362 
363 	VM_OBJECT_ASSERT_WLOCKED(fs->first_object);
364 	MPASS(REFCOUNT_COUNT(fs->first_object->paging_in_progress) > 0);
365 
366 	if (!vm_map_trylock_read(fs->map)) {
367 		VM_OBJECT_WUNLOCK(fs->first_object);
368 		vm_map_lock_read(fs->map);
369 		VM_OBJECT_WLOCK(fs->first_object);
370 	}
371 	fs->lookup_still_valid = true;
372 }
373 
374 static void
375 vm_fault_populate_check_page(vm_page_t m)
376 {
377 
378 	/*
379 	 * Check each page to ensure that the pager is obeying the
380 	 * interface: the page must be installed in the object, fully
381 	 * valid, and exclusively busied.
382 	 */
383 	MPASS(m != NULL);
384 	MPASS(vm_page_all_valid(m));
385 	MPASS(vm_page_xbusied(m));
386 }
387 
388 static void
389 vm_fault_populate_cleanup(vm_object_t object, vm_pindex_t first,
390     vm_pindex_t last)
391 {
392 	vm_page_t m;
393 	vm_pindex_t pidx;
394 
395 	VM_OBJECT_ASSERT_WLOCKED(object);
396 	MPASS(first <= last);
397 	for (pidx = first, m = vm_page_lookup(object, pidx);
398 	    pidx <= last; pidx++, m = vm_page_next(m)) {
399 		vm_fault_populate_check_page(m);
400 		vm_page_lock(m);
401 		vm_page_deactivate(m);
402 		vm_page_unlock(m);
403 		vm_page_xunbusy(m);
404 	}
405 }
406 
407 static int
408 vm_fault_populate(struct faultstate *fs, vm_prot_t prot, int fault_type,
409     int fault_flags, boolean_t wired, vm_page_t *m_hold)
410 {
411 	struct mtx *m_mtx;
412 	vm_offset_t vaddr;
413 	vm_page_t m;
414 	vm_pindex_t map_first, map_last, pager_first, pager_last, pidx;
415 	int i, npages, psind, rv;
416 
417 	MPASS(fs->object == fs->first_object);
418 	VM_OBJECT_ASSERT_WLOCKED(fs->first_object);
419 	MPASS(REFCOUNT_COUNT(fs->first_object->paging_in_progress) > 0);
420 	MPASS(fs->first_object->backing_object == NULL);
421 	MPASS(fs->lookup_still_valid);
422 
423 	pager_first = OFF_TO_IDX(fs->entry->offset);
424 	pager_last = pager_first + atop(fs->entry->end - fs->entry->start) - 1;
425 	unlock_map(fs);
426 	unlock_vp(fs);
427 
428 	/*
429 	 * Call the pager (driver) populate() method.
430 	 *
431 	 * There is no guarantee that the method will be called again
432 	 * if the current fault is for read, and a future fault is
433 	 * for write.  Report the entry's maximum allowed protection
434 	 * to the driver.
435 	 */
436 	rv = vm_pager_populate(fs->first_object, fs->first_pindex,
437 	    fault_type, fs->entry->max_protection, &pager_first, &pager_last);
438 
439 	VM_OBJECT_ASSERT_WLOCKED(fs->first_object);
440 	if (rv == VM_PAGER_BAD) {
441 		/*
442 		 * VM_PAGER_BAD is the backdoor for a pager to request
443 		 * normal fault handling.
444 		 */
445 		vm_fault_restore_map_lock(fs);
446 		if (fs->map->timestamp != fs->map_generation)
447 			return (KERN_RESOURCE_SHORTAGE); /* RetryFault */
448 		return (KERN_NOT_RECEIVER);
449 	}
450 	if (rv != VM_PAGER_OK)
451 		return (KERN_FAILURE); /* AKA SIGSEGV */
452 
453 	/* Ensure that the driver is obeying the interface. */
454 	MPASS(pager_first <= pager_last);
455 	MPASS(fs->first_pindex <= pager_last);
456 	MPASS(fs->first_pindex >= pager_first);
457 	MPASS(pager_last < fs->first_object->size);
458 
459 	vm_fault_restore_map_lock(fs);
460 	if (fs->map->timestamp != fs->map_generation) {
461 		vm_fault_populate_cleanup(fs->first_object, pager_first,
462 		    pager_last);
463 		return (KERN_RESOURCE_SHORTAGE); /* RetryFault */
464 	}
465 
466 	/*
467 	 * The map is unchanged after our last unlock.  Process the fault.
468 	 *
469 	 * The range [pager_first, pager_last] that is given to the
470 	 * pager is only a hint.  The pager may populate any range
471 	 * within the object that includes the requested page index.
472 	 * In case the pager expanded the range, clip it to fit into
473 	 * the map entry.
474 	 */
475 	map_first = OFF_TO_IDX(fs->entry->offset);
476 	if (map_first > pager_first) {
477 		vm_fault_populate_cleanup(fs->first_object, pager_first,
478 		    map_first - 1);
479 		pager_first = map_first;
480 	}
481 	map_last = map_first + atop(fs->entry->end - fs->entry->start) - 1;
482 	if (map_last < pager_last) {
483 		vm_fault_populate_cleanup(fs->first_object, map_last + 1,
484 		    pager_last);
485 		pager_last = map_last;
486 	}
487 	for (pidx = pager_first, m = vm_page_lookup(fs->first_object, pidx);
488 	    pidx <= pager_last;
489 	    pidx += npages, m = vm_page_next(&m[npages - 1])) {
490 		vaddr = fs->entry->start + IDX_TO_OFF(pidx) - fs->entry->offset;
491 #if defined(__aarch64__) || defined(__amd64__) || (defined(__arm__) && \
492     __ARM_ARCH >= 6) || defined(__i386__) || defined(__riscv)
493 		psind = m->psind;
494 		if (psind > 0 && ((vaddr & (pagesizes[psind] - 1)) != 0 ||
495 		    pidx + OFF_TO_IDX(pagesizes[psind]) - 1 > pager_last ||
496 		    !pmap_ps_enabled(fs->map->pmap) || wired))
497 			psind = 0;
498 #else
499 		psind = 0;
500 #endif
501 		npages = atop(pagesizes[psind]);
502 		for (i = 0; i < npages; i++) {
503 			vm_fault_populate_check_page(&m[i]);
504 			vm_fault_dirty(fs->entry, &m[i], prot, fault_type,
505 			    fault_flags, true);
506 		}
507 		VM_OBJECT_WUNLOCK(fs->first_object);
508 		rv = pmap_enter(fs->map->pmap, vaddr, m, prot, fault_type |
509 		    (wired ? PMAP_ENTER_WIRED : 0), psind);
510 #if defined(__amd64__)
511 		if (psind > 0 && rv == KERN_FAILURE) {
512 			for (i = 0; i < npages; i++) {
513 				rv = pmap_enter(fs->map->pmap, vaddr + ptoa(i),
514 				    &m[i], prot, fault_type |
515 				    (wired ? PMAP_ENTER_WIRED : 0), 0);
516 				MPASS(rv == KERN_SUCCESS);
517 			}
518 		}
519 #else
520 		MPASS(rv == KERN_SUCCESS);
521 #endif
522 		VM_OBJECT_WLOCK(fs->first_object);
523 		m_mtx = NULL;
524 		for (i = 0; i < npages; i++) {
525 			if ((fault_flags & VM_FAULT_WIRE) != 0) {
526 				vm_page_wire(&m[i]);
527 			} else {
528 				vm_page_change_lock(&m[i], &m_mtx);
529 				vm_page_activate(&m[i]);
530 			}
531 			if (m_hold != NULL && m[i].pindex == fs->first_pindex) {
532 				*m_hold = &m[i];
533 				vm_page_wire(&m[i]);
534 			}
535 			vm_page_xunbusy(&m[i]);
536 		}
537 		if (m_mtx != NULL)
538 			mtx_unlock(m_mtx);
539 	}
540 	curthread->td_ru.ru_majflt++;
541 	return (KERN_SUCCESS);
542 }
543 
544 static int prot_fault_translation;
545 SYSCTL_INT(_machdep, OID_AUTO, prot_fault_translation, CTLFLAG_RWTUN,
546     &prot_fault_translation, 0,
547     "Control signal to deliver on protection fault");
548 
549 /* compat definition to keep common code for signal translation */
550 #define	UCODE_PAGEFLT	12
551 #ifdef T_PAGEFLT
552 _Static_assert(UCODE_PAGEFLT == T_PAGEFLT, "T_PAGEFLT");
553 #endif
554 
555 /*
556  *	vm_fault_trap:
557  *
558  *	Handle a page fault occurring at the given address,
559  *	requiring the given permissions, in the map specified.
560  *	If successful, the page is inserted into the
561  *	associated physical map.
562  *
563  *	NOTE: the given address should be truncated to the
564  *	proper page address.
565  *
566  *	KERN_SUCCESS is returned if the page fault is handled; otherwise,
567  *	a standard error specifying why the fault is fatal is returned.
568  *
569  *	The map in question must be referenced, and remains so.
570  *	Caller may hold no locks.
571  */
572 int
573 vm_fault_trap(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
574     int fault_flags, int *signo, int *ucode)
575 {
576 	int result;
577 
578 	MPASS(signo == NULL || ucode != NULL);
579 #ifdef KTRACE
580 	if (map != kernel_map && KTRPOINT(curthread, KTR_FAULT))
581 		ktrfault(vaddr, fault_type);
582 #endif
583 	result = vm_fault(map, trunc_page(vaddr), fault_type, fault_flags,
584 	    NULL);
585 	KASSERT(result == KERN_SUCCESS || result == KERN_FAILURE ||
586 	    result == KERN_INVALID_ADDRESS ||
587 	    result == KERN_RESOURCE_SHORTAGE ||
588 	    result == KERN_PROTECTION_FAILURE ||
589 	    result == KERN_OUT_OF_BOUNDS,
590 	    ("Unexpected Mach error %d from vm_fault()", result));
591 #ifdef KTRACE
592 	if (map != kernel_map && KTRPOINT(curthread, KTR_FAULTEND))
593 		ktrfaultend(result);
594 #endif
595 	if (result != KERN_SUCCESS && signo != NULL) {
596 		switch (result) {
597 		case KERN_FAILURE:
598 		case KERN_INVALID_ADDRESS:
599 			*signo = SIGSEGV;
600 			*ucode = SEGV_MAPERR;
601 			break;
602 		case KERN_RESOURCE_SHORTAGE:
603 			*signo = SIGBUS;
604 			*ucode = BUS_OOMERR;
605 			break;
606 		case KERN_OUT_OF_BOUNDS:
607 			*signo = SIGBUS;
608 			*ucode = BUS_OBJERR;
609 			break;
610 		case KERN_PROTECTION_FAILURE:
611 			if (prot_fault_translation == 0) {
612 				/*
613 				 * Autodetect.  This check also covers
614 				 * the images without the ABI-tag ELF
615 				 * note.
616 				 */
617 				if (SV_CURPROC_ABI() == SV_ABI_FREEBSD &&
618 				    curproc->p_osrel >= P_OSREL_SIGSEGV) {
619 					*signo = SIGSEGV;
620 					*ucode = SEGV_ACCERR;
621 				} else {
622 					*signo = SIGBUS;
623 					*ucode = UCODE_PAGEFLT;
624 				}
625 			} else if (prot_fault_translation == 1) {
626 				/* Always compat mode. */
627 				*signo = SIGBUS;
628 				*ucode = UCODE_PAGEFLT;
629 			} else {
630 				/* Always SIGSEGV mode. */
631 				*signo = SIGSEGV;
632 				*ucode = SEGV_ACCERR;
633 			}
634 			break;
635 		default:
636 			KASSERT(0, ("Unexpected Mach error %d from vm_fault()",
637 			    result));
638 			break;
639 		}
640 	}
641 	return (result);
642 }
643 
644 static int
645 vm_fault_lock_vnode(struct faultstate *fs)
646 {
647 	struct vnode *vp;
648 	int error, locked;
649 
650 	if (fs->object->type != OBJT_VNODE)
651 		return (KERN_SUCCESS);
652 	vp = fs->object->handle;
653 	if (vp == fs->vp) {
654 		ASSERT_VOP_LOCKED(vp, "saved vnode is not locked");
655 		return (KERN_SUCCESS);
656 	}
657 
658 	/*
659 	 * Perform an unlock in case the desired vnode changed while
660 	 * the map was unlocked during a retry.
661 	 */
662 	unlock_vp(fs);
663 
664 	locked = VOP_ISLOCKED(vp);
665 	if (locked != LK_EXCLUSIVE)
666 		locked = LK_SHARED;
667 
668 	/*
669 	 * We must not sleep acquiring the vnode lock while we have
670 	 * the page exclusive busied or the object's
671 	 * paging-in-progress count incremented.  Otherwise, we could
672 	 * deadlock.
673 	 */
674 	error = vget(vp, locked | LK_CANRECURSE | LK_NOWAIT, curthread);
675 	if (error == 0) {
676 		fs->vp = vp;
677 		return (KERN_SUCCESS);
678 	}
679 
680 	vhold(vp);
681 	release_page(fs);
682 	unlock_and_deallocate(fs);
683 	error = vget(vp, locked | LK_RETRY | LK_CANRECURSE, curthread);
684 	vdrop(vp);
685 	fs->vp = vp;
686 	KASSERT(error == 0, ("vm_fault: vget failed %d", error));
687 	return (KERN_RESOURCE_SHORTAGE);
688 }
689 
690 int
691 vm_fault(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
692     int fault_flags, vm_page_t *m_hold)
693 {
694 	struct faultstate fs;
695 	struct domainset *dset;
696 	vm_object_t next_object, retry_object;
697 	vm_offset_t e_end, e_start;
698 	vm_pindex_t retry_pindex;
699 	vm_prot_t prot, retry_prot;
700 	int ahead, alloc_req, behind, cluster_offset, era, faultcount;
701 	int nera, oom, result, rv;
702 	u_char behavior;
703 	boolean_t wired;	/* Passed by reference. */
704 	bool dead, hardfault, is_first_object_locked;
705 
706 	VM_CNT_INC(v_vm_faults);
707 
708 	if ((curthread->td_pflags & TDP_NOFAULTING) != 0)
709 		return (KERN_PROTECTION_FAILURE);
710 
711 	fs.vp = NULL;
712 	faultcount = 0;
713 	nera = -1;
714 	hardfault = false;
715 
716 RetryFault:
717 	oom = 0;
718 RetryFault_oom:
719 
720 	/*
721 	 * Find the backing store object and offset into it to begin the
722 	 * search.
723 	 */
724 	fs.map = map;
725 	result = vm_map_lookup(&fs.map, vaddr, fault_type |
726 	    VM_PROT_FAULT_LOOKUP, &fs.entry, &fs.first_object,
727 	    &fs.first_pindex, &prot, &wired);
728 	if (result != KERN_SUCCESS) {
729 		unlock_vp(&fs);
730 		return (result);
731 	}
732 
733 	fs.map_generation = fs.map->timestamp;
734 
735 	if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
736 		panic("%s: fault on nofault entry, addr: %#lx",
737 		    __func__, (u_long)vaddr);
738 	}
739 
740 	if (fs.entry->eflags & MAP_ENTRY_IN_TRANSITION &&
741 	    fs.entry->wiring_thread != curthread) {
742 		vm_map_unlock_read(fs.map);
743 		vm_map_lock(fs.map);
744 		if (vm_map_lookup_entry(fs.map, vaddr, &fs.entry) &&
745 		    (fs.entry->eflags & MAP_ENTRY_IN_TRANSITION)) {
746 			unlock_vp(&fs);
747 			fs.entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
748 			vm_map_unlock_and_wait(fs.map, 0);
749 		} else
750 			vm_map_unlock(fs.map);
751 		goto RetryFault;
752 	}
753 
754 	MPASS((fs.entry->eflags & MAP_ENTRY_GUARD) == 0);
755 
756 	if (wired)
757 		fault_type = prot | (fault_type & VM_PROT_COPY);
758 	else
759 		KASSERT((fault_flags & VM_FAULT_WIRE) == 0,
760 		    ("!wired && VM_FAULT_WIRE"));
761 
762 	/*
763 	 * Try to avoid lock contention on the top-level object through
764 	 * special-case handling of some types of page faults, specifically,
765 	 * those that are mapping an existing page from the top-level object.
766 	 * Under this condition, a read lock on the object suffices, allowing
767 	 * multiple page faults of a similar type to run in parallel.
768 	 */
769 	if (fs.vp == NULL /* avoid locked vnode leak */ &&
770 	    (fault_flags & (VM_FAULT_WIRE | VM_FAULT_DIRTY)) == 0) {
771 		VM_OBJECT_RLOCK(fs.first_object);
772 		rv = vm_fault_soft_fast(&fs, vaddr, prot, fault_type,
773 		    fault_flags, wired, m_hold);
774 		if (rv == KERN_SUCCESS)
775 			return (rv);
776 		if (!VM_OBJECT_TRYUPGRADE(fs.first_object)) {
777 			VM_OBJECT_RUNLOCK(fs.first_object);
778 			VM_OBJECT_WLOCK(fs.first_object);
779 		}
780 	} else {
781 		VM_OBJECT_WLOCK(fs.first_object);
782 	}
783 
784 	/*
785 	 * Make a reference to this object to prevent its disposal while we
786 	 * are messing with it.  Once we have the reference, the map is free
787 	 * to be diddled.  Since objects reference their shadows (and copies),
788 	 * they will stay around as well.
789 	 *
790 	 * Bump the paging-in-progress count to prevent size changes (e.g.
791 	 * truncation operations) during I/O.
792 	 */
793 	vm_object_reference_locked(fs.first_object);
794 	vm_object_pip_add(fs.first_object, 1);
795 
796 	fs.lookup_still_valid = true;
797 
798 	fs.first_m = NULL;
799 
800 	/*
801 	 * Search for the page at object/offset.
802 	 */
803 	fs.object = fs.first_object;
804 	fs.pindex = fs.first_pindex;
805 	while (TRUE) {
806 		/*
807 		 * If the object is marked for imminent termination,
808 		 * we retry here, since the collapse pass has raced
809 		 * with us.  Otherwise, if we see terminally dead
810 		 * object, return fail.
811 		 */
812 		if ((fs.object->flags & OBJ_DEAD) != 0) {
813 			dead = fs.object->type == OBJT_DEAD;
814 			unlock_and_deallocate(&fs);
815 			if (dead)
816 				return (KERN_PROTECTION_FAILURE);
817 			pause("vmf_de", 1);
818 			goto RetryFault;
819 		}
820 
821 		/*
822 		 * See if page is resident
823 		 */
824 		fs.m = vm_page_lookup(fs.object, fs.pindex);
825 		if (fs.m != NULL) {
826 			/*
827 			 * Wait/Retry if the page is busy.  We have to do this
828 			 * if the page is either exclusive or shared busy
829 			 * because the vm_pager may be using read busy for
830 			 * pageouts (and even pageins if it is the vnode
831 			 * pager), and we could end up trying to pagein and
832 			 * pageout the same page simultaneously.
833 			 *
834 			 * We can theoretically allow the busy case on a read
835 			 * fault if the page is marked valid, but since such
836 			 * pages are typically already pmap'd, putting that
837 			 * special case in might be more effort then it is
838 			 * worth.  We cannot under any circumstances mess
839 			 * around with a shared busied page except, perhaps,
840 			 * to pmap it.
841 			 */
842 			if (vm_page_tryxbusy(fs.m) == 0) {
843 				/*
844 				 * Reference the page before unlocking and
845 				 * sleeping so that the page daemon is less
846 				 * likely to reclaim it.
847 				 */
848 				vm_page_aflag_set(fs.m, PGA_REFERENCED);
849 				if (fs.object != fs.first_object) {
850 					if (!VM_OBJECT_TRYWLOCK(
851 					    fs.first_object)) {
852 						VM_OBJECT_WUNLOCK(fs.object);
853 						VM_OBJECT_WLOCK(fs.first_object);
854 						VM_OBJECT_WLOCK(fs.object);
855 					}
856 					vm_page_free(fs.first_m);
857 					vm_object_pip_wakeup(fs.first_object);
858 					VM_OBJECT_WUNLOCK(fs.first_object);
859 					fs.first_m = NULL;
860 				}
861 				unlock_map(&fs);
862 				if (fs.m == vm_page_lookup(fs.object,
863 				    fs.pindex)) {
864 					vm_page_sleep_if_busy(fs.m, "vmpfw");
865 				}
866 				vm_object_pip_wakeup(fs.object);
867 				VM_OBJECT_WUNLOCK(fs.object);
868 				VM_CNT_INC(v_intrans);
869 				vm_object_deallocate(fs.first_object);
870 				goto RetryFault;
871 			}
872 
873 			/*
874 			 * The page is marked busy for other processes and the
875 			 * pagedaemon.  If it still isn't completely valid
876 			 * (readable), jump to readrest, else break-out ( we
877 			 * found the page ).
878 			 */
879 			if (!vm_page_all_valid(fs.m))
880 				goto readrest;
881 			break; /* break to PAGE HAS BEEN FOUND */
882 		}
883 		KASSERT(fs.m == NULL, ("fs.m should be NULL, not %p", fs.m));
884 
885 		/*
886 		 * Page is not resident.  If the pager might contain the page
887 		 * or this is the beginning of the search, allocate a new
888 		 * page.  (Default objects are zero-fill, so there is no real
889 		 * pager for them.)
890 		 */
891 		if (fs.object->type != OBJT_DEFAULT ||
892 		    fs.object == fs.first_object) {
893 			if ((fs.object->flags & OBJ_SIZEVNLOCK) != 0) {
894 				rv = vm_fault_lock_vnode(&fs);
895 				MPASS(rv == KERN_SUCCESS ||
896 				    rv == KERN_RESOURCE_SHORTAGE);
897 				if (rv == KERN_RESOURCE_SHORTAGE)
898 					goto RetryFault;
899 			}
900 			if (fs.pindex >= fs.object->size) {
901 				unlock_and_deallocate(&fs);
902 				return (KERN_OUT_OF_BOUNDS);
903 			}
904 
905 			if (fs.object == fs.first_object &&
906 			    (fs.first_object->flags & OBJ_POPULATE) != 0 &&
907 			    fs.first_object->shadow_count == 0) {
908 				rv = vm_fault_populate(&fs, prot, fault_type,
909 				    fault_flags, wired, m_hold);
910 				switch (rv) {
911 				case KERN_SUCCESS:
912 				case KERN_FAILURE:
913 					unlock_and_deallocate(&fs);
914 					return (rv);
915 				case KERN_RESOURCE_SHORTAGE:
916 					unlock_and_deallocate(&fs);
917 					goto RetryFault;
918 				case KERN_NOT_RECEIVER:
919 					/*
920 					 * Pager's populate() method
921 					 * returned VM_PAGER_BAD.
922 					 */
923 					break;
924 				default:
925 					panic("inconsistent return codes");
926 				}
927 			}
928 
929 			/*
930 			 * Allocate a new page for this object/offset pair.
931 			 *
932 			 * Unlocked read of the p_flag is harmless. At
933 			 * worst, the P_KILLED might be not observed
934 			 * there, and allocation can fail, causing
935 			 * restart and new reading of the p_flag.
936 			 */
937 			dset = fs.object->domain.dr_policy;
938 			if (dset == NULL)
939 				dset = curthread->td_domain.dr_policy;
940 			if (!vm_page_count_severe_set(&dset->ds_mask) ||
941 			    P_KILLED(curproc)) {
942 #if VM_NRESERVLEVEL > 0
943 				vm_object_color(fs.object, atop(vaddr) -
944 				    fs.pindex);
945 #endif
946 				alloc_req = P_KILLED(curproc) ?
947 				    VM_ALLOC_SYSTEM : VM_ALLOC_NORMAL;
948 				if (fs.object->type != OBJT_VNODE &&
949 				    fs.object->backing_object == NULL)
950 					alloc_req |= VM_ALLOC_ZERO;
951 				fs.m = vm_page_alloc(fs.object, fs.pindex,
952 				    alloc_req);
953 			}
954 			if (fs.m == NULL) {
955 				unlock_and_deallocate(&fs);
956 				if (vm_pfault_oom_attempts < 0 ||
957 				    oom < vm_pfault_oom_attempts) {
958 					oom++;
959 					vm_waitpfault(dset,
960 					    vm_pfault_oom_wait * hz);
961 					goto RetryFault_oom;
962 				}
963 				if (bootverbose)
964 					printf(
965 	"proc %d (%s) failed to alloc page on fault, starting OOM\n",
966 					    curproc->p_pid, curproc->p_comm);
967 				vm_pageout_oom(VM_OOM_MEM_PF);
968 				goto RetryFault;
969 			}
970 		}
971 
972 readrest:
973 		/*
974 		 * At this point, we have either allocated a new page or found
975 		 * an existing page that is only partially valid.
976 		 *
977 		 * We hold a reference on the current object and the page is
978 		 * exclusive busied.
979 		 */
980 
981 		/*
982 		 * If the pager for the current object might have the page,
983 		 * then determine the number of additional pages to read and
984 		 * potentially reprioritize previously read pages for earlier
985 		 * reclamation.  These operations should only be performed
986 		 * once per page fault.  Even if the current pager doesn't
987 		 * have the page, the number of additional pages to read will
988 		 * apply to subsequent objects in the shadow chain.
989 		 */
990 		if (fs.object->type != OBJT_DEFAULT && nera == -1 &&
991 		    !P_KILLED(curproc)) {
992 			KASSERT(fs.lookup_still_valid, ("map unlocked"));
993 			era = fs.entry->read_ahead;
994 			behavior = vm_map_entry_behavior(fs.entry);
995 			if (behavior == MAP_ENTRY_BEHAV_RANDOM) {
996 				nera = 0;
997 			} else if (behavior == MAP_ENTRY_BEHAV_SEQUENTIAL) {
998 				nera = VM_FAULT_READ_AHEAD_MAX;
999 				if (vaddr == fs.entry->next_read)
1000 					vm_fault_dontneed(&fs, vaddr, nera);
1001 			} else if (vaddr == fs.entry->next_read) {
1002 				/*
1003 				 * This is a sequential fault.  Arithmetically
1004 				 * increase the requested number of pages in
1005 				 * the read-ahead window.  The requested
1006 				 * number of pages is "# of sequential faults
1007 				 * x (read ahead min + 1) + read ahead min"
1008 				 */
1009 				nera = VM_FAULT_READ_AHEAD_MIN;
1010 				if (era > 0) {
1011 					nera += era + 1;
1012 					if (nera > VM_FAULT_READ_AHEAD_MAX)
1013 						nera = VM_FAULT_READ_AHEAD_MAX;
1014 				}
1015 				if (era == VM_FAULT_READ_AHEAD_MAX)
1016 					vm_fault_dontneed(&fs, vaddr, nera);
1017 			} else {
1018 				/*
1019 				 * This is a non-sequential fault.
1020 				 */
1021 				nera = 0;
1022 			}
1023 			if (era != nera) {
1024 				/*
1025 				 * A read lock on the map suffices to update
1026 				 * the read ahead count safely.
1027 				 */
1028 				fs.entry->read_ahead = nera;
1029 			}
1030 
1031 			/*
1032 			 * Prepare for unlocking the map.  Save the map
1033 			 * entry's start and end addresses, which are used to
1034 			 * optimize the size of the pager operation below.
1035 			 * Even if the map entry's addresses change after
1036 			 * unlocking the map, using the saved addresses is
1037 			 * safe.
1038 			 */
1039 			e_start = fs.entry->start;
1040 			e_end = fs.entry->end;
1041 		}
1042 
1043 		/*
1044 		 * Call the pager to retrieve the page if there is a chance
1045 		 * that the pager has it, and potentially retrieve additional
1046 		 * pages at the same time.
1047 		 */
1048 		if (fs.object->type != OBJT_DEFAULT) {
1049 			/*
1050 			 * Release the map lock before locking the vnode or
1051 			 * sleeping in the pager.  (If the current object has
1052 			 * a shadow, then an earlier iteration of this loop
1053 			 * may have already unlocked the map.)
1054 			 */
1055 			unlock_map(&fs);
1056 
1057 			rv = vm_fault_lock_vnode(&fs);
1058 			MPASS(rv == KERN_SUCCESS ||
1059 			    rv == KERN_RESOURCE_SHORTAGE);
1060 			if (rv == KERN_RESOURCE_SHORTAGE)
1061 				goto RetryFault;
1062 			KASSERT(fs.vp == NULL || !fs.map->system_map,
1063 			    ("vm_fault: vnode-backed object mapped by system map"));
1064 
1065 			/*
1066 			 * Page in the requested page and hint the pager,
1067 			 * that it may bring up surrounding pages.
1068 			 */
1069 			if (nera == -1 || behavior == MAP_ENTRY_BEHAV_RANDOM ||
1070 			    P_KILLED(curproc)) {
1071 				behind = 0;
1072 				ahead = 0;
1073 			} else {
1074 				/* Is this a sequential fault? */
1075 				if (nera > 0) {
1076 					behind = 0;
1077 					ahead = nera;
1078 				} else {
1079 					/*
1080 					 * Request a cluster of pages that is
1081 					 * aligned to a VM_FAULT_READ_DEFAULT
1082 					 * page offset boundary within the
1083 					 * object.  Alignment to a page offset
1084 					 * boundary is more likely to coincide
1085 					 * with the underlying file system
1086 					 * block than alignment to a virtual
1087 					 * address boundary.
1088 					 */
1089 					cluster_offset = fs.pindex %
1090 					    VM_FAULT_READ_DEFAULT;
1091 					behind = ulmin(cluster_offset,
1092 					    atop(vaddr - e_start));
1093 					ahead = VM_FAULT_READ_DEFAULT - 1 -
1094 					    cluster_offset;
1095 				}
1096 				ahead = ulmin(ahead, atop(e_end - vaddr) - 1);
1097 			}
1098 			rv = vm_pager_get_pages(fs.object, &fs.m, 1,
1099 			    &behind, &ahead);
1100 			if (rv == VM_PAGER_OK) {
1101 				faultcount = behind + 1 + ahead;
1102 				hardfault = true;
1103 				break; /* break to PAGE HAS BEEN FOUND */
1104 			}
1105 			if (rv == VM_PAGER_ERROR)
1106 				printf("vm_fault: pager read error, pid %d (%s)\n",
1107 				    curproc->p_pid, curproc->p_comm);
1108 
1109 			/*
1110 			 * If an I/O error occurred or the requested page was
1111 			 * outside the range of the pager, clean up and return
1112 			 * an error.
1113 			 */
1114 			if (rv == VM_PAGER_ERROR || rv == VM_PAGER_BAD) {
1115 				if (!vm_page_wired(fs.m))
1116 					vm_page_free(fs.m);
1117 				else
1118 					vm_page_xunbusy(fs.m);
1119 				fs.m = NULL;
1120 				unlock_and_deallocate(&fs);
1121 				return (KERN_OUT_OF_BOUNDS);
1122 			}
1123 
1124 			/*
1125 			 * The requested page does not exist at this object/
1126 			 * offset.  Remove the invalid page from the object,
1127 			 * waking up anyone waiting for it, and continue on to
1128 			 * the next object.  However, if this is the top-level
1129 			 * object, we must leave the busy page in place to
1130 			 * prevent another process from rushing past us, and
1131 			 * inserting the page in that object at the same time
1132 			 * that we are.
1133 			 */
1134 			if (fs.object != fs.first_object) {
1135 				if (!vm_page_wired(fs.m))
1136 					vm_page_free(fs.m);
1137 				else
1138 					vm_page_xunbusy(fs.m);
1139 				fs.m = NULL;
1140 			}
1141 		}
1142 
1143 		/*
1144 		 * We get here if the object has default pager (or unwiring)
1145 		 * or the pager doesn't have the page.
1146 		 */
1147 		if (fs.object == fs.first_object)
1148 			fs.first_m = fs.m;
1149 
1150 		/*
1151 		 * Move on to the next object.  Lock the next object before
1152 		 * unlocking the current one.
1153 		 */
1154 		next_object = fs.object->backing_object;
1155 		if (next_object == NULL) {
1156 			/*
1157 			 * If there's no object left, fill the page in the top
1158 			 * object with zeros.
1159 			 */
1160 			if (fs.object != fs.first_object) {
1161 				vm_object_pip_wakeup(fs.object);
1162 				VM_OBJECT_WUNLOCK(fs.object);
1163 
1164 				fs.object = fs.first_object;
1165 				fs.pindex = fs.first_pindex;
1166 				fs.m = fs.first_m;
1167 				VM_OBJECT_WLOCK(fs.object);
1168 			}
1169 			fs.first_m = NULL;
1170 
1171 			/*
1172 			 * Zero the page if necessary and mark it valid.
1173 			 */
1174 			if ((fs.m->flags & PG_ZERO) == 0) {
1175 				pmap_zero_page(fs.m);
1176 			} else {
1177 				VM_CNT_INC(v_ozfod);
1178 			}
1179 			VM_CNT_INC(v_zfod);
1180 			vm_page_valid(fs.m);
1181 			/* Don't try to prefault neighboring pages. */
1182 			faultcount = 1;
1183 			break;	/* break to PAGE HAS BEEN FOUND */
1184 		} else {
1185 			KASSERT(fs.object != next_object,
1186 			    ("object loop %p", next_object));
1187 			VM_OBJECT_WLOCK(next_object);
1188 			vm_object_pip_add(next_object, 1);
1189 			if (fs.object != fs.first_object)
1190 				vm_object_pip_wakeup(fs.object);
1191 			fs.pindex +=
1192 			    OFF_TO_IDX(fs.object->backing_object_offset);
1193 			VM_OBJECT_WUNLOCK(fs.object);
1194 			fs.object = next_object;
1195 		}
1196 	}
1197 
1198 	vm_page_assert_xbusied(fs.m);
1199 
1200 	/*
1201 	 * PAGE HAS BEEN FOUND. [Loop invariant still holds -- the object lock
1202 	 * is held.]
1203 	 */
1204 
1205 	/*
1206 	 * If the page is being written, but isn't already owned by the
1207 	 * top-level object, we have to copy it into a new page owned by the
1208 	 * top-level object.
1209 	 */
1210 	if (fs.object != fs.first_object) {
1211 		/*
1212 		 * We only really need to copy if we want to write it.
1213 		 */
1214 		if ((fault_type & (VM_PROT_COPY | VM_PROT_WRITE)) != 0) {
1215 			/*
1216 			 * This allows pages to be virtually copied from a
1217 			 * backing_object into the first_object, where the
1218 			 * backing object has no other refs to it, and cannot
1219 			 * gain any more refs.  Instead of a bcopy, we just
1220 			 * move the page from the backing object to the
1221 			 * first object.  Note that we must mark the page
1222 			 * dirty in the first object so that it will go out
1223 			 * to swap when needed.
1224 			 */
1225 			is_first_object_locked = false;
1226 			if (
1227 				/*
1228 				 * Only one shadow object
1229 				 */
1230 				(fs.object->shadow_count == 1) &&
1231 				/*
1232 				 * No COW refs, except us
1233 				 */
1234 				(fs.object->ref_count == 1) &&
1235 				/*
1236 				 * No one else can look this object up
1237 				 */
1238 				(fs.object->handle == NULL) &&
1239 				/*
1240 				 * No other ways to look the object up
1241 				 */
1242 				((fs.object->flags & OBJ_ANON) != 0) &&
1243 			    (is_first_object_locked = VM_OBJECT_TRYWLOCK(fs.first_object)) &&
1244 				/*
1245 				 * We don't chase down the shadow chain
1246 				 */
1247 			    fs.object == fs.first_object->backing_object) {
1248 
1249 				(void)vm_page_remove(fs.m);
1250 				vm_page_replace_checked(fs.m, fs.first_object,
1251 				    fs.first_pindex, fs.first_m);
1252 				vm_page_free(fs.first_m);
1253 				vm_page_dirty(fs.m);
1254 #if VM_NRESERVLEVEL > 0
1255 				/*
1256 				 * Rename the reservation.
1257 				 */
1258 				vm_reserv_rename(fs.m, fs.first_object,
1259 				    fs.object, OFF_TO_IDX(
1260 				    fs.first_object->backing_object_offset));
1261 #endif
1262 				VM_OBJECT_WUNLOCK(fs.object);
1263 				fs.first_m = fs.m;
1264 				fs.m = NULL;
1265 				VM_CNT_INC(v_cow_optim);
1266 			} else {
1267 				VM_OBJECT_WUNLOCK(fs.object);
1268 				/*
1269 				 * Oh, well, lets copy it.
1270 				 */
1271 				pmap_copy_page(fs.m, fs.first_m);
1272 				vm_page_valid(fs.first_m);
1273 				if (wired && (fault_flags &
1274 				    VM_FAULT_WIRE) == 0) {
1275 					vm_page_wire(fs.first_m);
1276 					vm_page_unwire(fs.m, PQ_INACTIVE);
1277 				}
1278 				/*
1279 				 * We no longer need the old page or object.
1280 				 */
1281 				release_page(&fs);
1282 			}
1283 			/*
1284 			 * fs.object != fs.first_object due to above
1285 			 * conditional
1286 			 */
1287 			vm_object_pip_wakeup(fs.object);
1288 
1289 			/*
1290 			 * We only try to prefault read-only mappings to the
1291 			 * neighboring pages when this copy-on-write fault is
1292 			 * a hard fault.  In other cases, trying to prefault
1293 			 * is typically wasted effort.
1294 			 */
1295 			if (faultcount == 0)
1296 				faultcount = 1;
1297 
1298 			/*
1299 			 * Only use the new page below...
1300 			 */
1301 			fs.object = fs.first_object;
1302 			fs.pindex = fs.first_pindex;
1303 			fs.m = fs.first_m;
1304 			if (!is_first_object_locked)
1305 				VM_OBJECT_WLOCK(fs.object);
1306 			VM_CNT_INC(v_cow_faults);
1307 			curthread->td_cow++;
1308 		} else {
1309 			prot &= ~VM_PROT_WRITE;
1310 		}
1311 	}
1312 
1313 	/*
1314 	 * We must verify that the maps have not changed since our last
1315 	 * lookup.
1316 	 */
1317 	if (!fs.lookup_still_valid) {
1318 		if (!vm_map_trylock_read(fs.map)) {
1319 			release_page(&fs);
1320 			unlock_and_deallocate(&fs);
1321 			goto RetryFault;
1322 		}
1323 		fs.lookup_still_valid = true;
1324 		if (fs.map->timestamp != fs.map_generation) {
1325 			result = vm_map_lookup_locked(&fs.map, vaddr, fault_type,
1326 			    &fs.entry, &retry_object, &retry_pindex, &retry_prot, &wired);
1327 
1328 			/*
1329 			 * If we don't need the page any longer, put it on the inactive
1330 			 * list (the easiest thing to do here).  If no one needs it,
1331 			 * pageout will grab it eventually.
1332 			 */
1333 			if (result != KERN_SUCCESS) {
1334 				release_page(&fs);
1335 				unlock_and_deallocate(&fs);
1336 
1337 				/*
1338 				 * If retry of map lookup would have blocked then
1339 				 * retry fault from start.
1340 				 */
1341 				if (result == KERN_FAILURE)
1342 					goto RetryFault;
1343 				return (result);
1344 			}
1345 			if ((retry_object != fs.first_object) ||
1346 			    (retry_pindex != fs.first_pindex)) {
1347 				release_page(&fs);
1348 				unlock_and_deallocate(&fs);
1349 				goto RetryFault;
1350 			}
1351 
1352 			/*
1353 			 * Check whether the protection has changed or the object has
1354 			 * been copied while we left the map unlocked. Changing from
1355 			 * read to write permission is OK - we leave the page
1356 			 * write-protected, and catch the write fault. Changing from
1357 			 * write to read permission means that we can't mark the page
1358 			 * write-enabled after all.
1359 			 */
1360 			prot &= retry_prot;
1361 			fault_type &= retry_prot;
1362 			if (prot == 0) {
1363 				release_page(&fs);
1364 				unlock_and_deallocate(&fs);
1365 				goto RetryFault;
1366 			}
1367 
1368 			/* Reassert because wired may have changed. */
1369 			KASSERT(wired || (fault_flags & VM_FAULT_WIRE) == 0,
1370 			    ("!wired && VM_FAULT_WIRE"));
1371 		}
1372 	}
1373 
1374 	/*
1375 	 * If the page was filled by a pager, save the virtual address that
1376 	 * should be faulted on next under a sequential access pattern to the
1377 	 * map entry.  A read lock on the map suffices to update this address
1378 	 * safely.
1379 	 */
1380 	if (hardfault)
1381 		fs.entry->next_read = vaddr + ptoa(ahead) + PAGE_SIZE;
1382 
1383 	vm_page_assert_xbusied(fs.m);
1384 	vm_fault_dirty(fs.entry, fs.m, prot, fault_type, fault_flags, true);
1385 
1386 	/*
1387 	 * Page must be completely valid or it is not fit to
1388 	 * map into user space.  vm_pager_get_pages() ensures this.
1389 	 */
1390 	KASSERT(vm_page_all_valid(fs.m),
1391 	    ("vm_fault: page %p partially invalid", fs.m));
1392 	VM_OBJECT_WUNLOCK(fs.object);
1393 
1394 	/*
1395 	 * Put this page into the physical map.  We had to do the unlock above
1396 	 * because pmap_enter() may sleep.  We don't put the page
1397 	 * back on the active queue until later so that the pageout daemon
1398 	 * won't find it (yet).
1399 	 */
1400 	pmap_enter(fs.map->pmap, vaddr, fs.m, prot,
1401 	    fault_type | (wired ? PMAP_ENTER_WIRED : 0), 0);
1402 	if (faultcount != 1 && (fault_flags & VM_FAULT_WIRE) == 0 &&
1403 	    wired == 0)
1404 		vm_fault_prefault(&fs, vaddr,
1405 		    faultcount > 0 ? behind : PFBAK,
1406 		    faultcount > 0 ? ahead : PFFOR, false);
1407 
1408 	/*
1409 	 * If the page is not wired down, then put it where the pageout daemon
1410 	 * can find it.
1411 	 */
1412 	if ((fault_flags & VM_FAULT_WIRE) != 0) {
1413 		vm_page_wire(fs.m);
1414 	} else {
1415 		vm_page_lock(fs.m);
1416 		vm_page_activate(fs.m);
1417 		vm_page_unlock(fs.m);
1418 	}
1419 	if (m_hold != NULL) {
1420 		*m_hold = fs.m;
1421 		vm_page_wire(fs.m);
1422 	}
1423 	vm_page_xunbusy(fs.m);
1424 
1425 	/*
1426 	 * Unlock everything, and return
1427 	 */
1428 	fault_deallocate(&fs);
1429 	if (hardfault) {
1430 		VM_CNT_INC(v_io_faults);
1431 		curthread->td_ru.ru_majflt++;
1432 #ifdef RACCT
1433 		if (racct_enable && fs.object->type == OBJT_VNODE) {
1434 			PROC_LOCK(curproc);
1435 			if ((fault_type & (VM_PROT_COPY | VM_PROT_WRITE)) != 0) {
1436 				racct_add_force(curproc, RACCT_WRITEBPS,
1437 				    PAGE_SIZE + behind * PAGE_SIZE);
1438 				racct_add_force(curproc, RACCT_WRITEIOPS, 1);
1439 			} else {
1440 				racct_add_force(curproc, RACCT_READBPS,
1441 				    PAGE_SIZE + ahead * PAGE_SIZE);
1442 				racct_add_force(curproc, RACCT_READIOPS, 1);
1443 			}
1444 			PROC_UNLOCK(curproc);
1445 		}
1446 #endif
1447 	} else
1448 		curthread->td_ru.ru_minflt++;
1449 
1450 	return (KERN_SUCCESS);
1451 }
1452 
1453 /*
1454  * Speed up the reclamation of pages that precede the faulting pindex within
1455  * the first object of the shadow chain.  Essentially, perform the equivalent
1456  * to madvise(..., MADV_DONTNEED) on a large cluster of pages that precedes
1457  * the faulting pindex by the cluster size when the pages read by vm_fault()
1458  * cross a cluster-size boundary.  The cluster size is the greater of the
1459  * smallest superpage size and VM_FAULT_DONTNEED_MIN.
1460  *
1461  * When "fs->first_object" is a shadow object, the pages in the backing object
1462  * that precede the faulting pindex are deactivated by vm_fault().  So, this
1463  * function must only be concerned with pages in the first object.
1464  */
1465 static void
1466 vm_fault_dontneed(const struct faultstate *fs, vm_offset_t vaddr, int ahead)
1467 {
1468 	vm_map_entry_t entry;
1469 	vm_object_t first_object, object;
1470 	vm_offset_t end, start;
1471 	vm_page_t m, m_next;
1472 	vm_pindex_t pend, pstart;
1473 	vm_size_t size;
1474 
1475 	object = fs->object;
1476 	VM_OBJECT_ASSERT_WLOCKED(object);
1477 	first_object = fs->first_object;
1478 	if (first_object != object) {
1479 		if (!VM_OBJECT_TRYWLOCK(first_object)) {
1480 			VM_OBJECT_WUNLOCK(object);
1481 			VM_OBJECT_WLOCK(first_object);
1482 			VM_OBJECT_WLOCK(object);
1483 		}
1484 	}
1485 	/* Neither fictitious nor unmanaged pages can be reclaimed. */
1486 	if ((first_object->flags & (OBJ_FICTITIOUS | OBJ_UNMANAGED)) == 0) {
1487 		size = VM_FAULT_DONTNEED_MIN;
1488 		if (MAXPAGESIZES > 1 && size < pagesizes[1])
1489 			size = pagesizes[1];
1490 		end = rounddown2(vaddr, size);
1491 		if (vaddr - end >= size - PAGE_SIZE - ptoa(ahead) &&
1492 		    (entry = fs->entry)->start < end) {
1493 			if (end - entry->start < size)
1494 				start = entry->start;
1495 			else
1496 				start = end - size;
1497 			pmap_advise(fs->map->pmap, start, end, MADV_DONTNEED);
1498 			pstart = OFF_TO_IDX(entry->offset) + atop(start -
1499 			    entry->start);
1500 			m_next = vm_page_find_least(first_object, pstart);
1501 			pend = OFF_TO_IDX(entry->offset) + atop(end -
1502 			    entry->start);
1503 			while ((m = m_next) != NULL && m->pindex < pend) {
1504 				m_next = TAILQ_NEXT(m, listq);
1505 				if (!vm_page_all_valid(m) ||
1506 				    vm_page_busied(m))
1507 					continue;
1508 
1509 				/*
1510 				 * Don't clear PGA_REFERENCED, since it would
1511 				 * likely represent a reference by a different
1512 				 * process.
1513 				 *
1514 				 * Typically, at this point, prefetched pages
1515 				 * are still in the inactive queue.  Only
1516 				 * pages that triggered page faults are in the
1517 				 * active queue.
1518 				 */
1519 				vm_page_lock(m);
1520 				if (!vm_page_inactive(m))
1521 					vm_page_deactivate(m);
1522 				vm_page_unlock(m);
1523 			}
1524 		}
1525 	}
1526 	if (first_object != object)
1527 		VM_OBJECT_WUNLOCK(first_object);
1528 }
1529 
1530 /*
1531  * vm_fault_prefault provides a quick way of clustering
1532  * pagefaults into a processes address space.  It is a "cousin"
1533  * of vm_map_pmap_enter, except it runs at page fault time instead
1534  * of mmap time.
1535  */
1536 static void
1537 vm_fault_prefault(const struct faultstate *fs, vm_offset_t addra,
1538     int backward, int forward, bool obj_locked)
1539 {
1540 	pmap_t pmap;
1541 	vm_map_entry_t entry;
1542 	vm_object_t backing_object, lobject;
1543 	vm_offset_t addr, starta;
1544 	vm_pindex_t pindex;
1545 	vm_page_t m;
1546 	int i;
1547 
1548 	pmap = fs->map->pmap;
1549 	if (pmap != vmspace_pmap(curthread->td_proc->p_vmspace))
1550 		return;
1551 
1552 	entry = fs->entry;
1553 
1554 	if (addra < backward * PAGE_SIZE) {
1555 		starta = entry->start;
1556 	} else {
1557 		starta = addra - backward * PAGE_SIZE;
1558 		if (starta < entry->start)
1559 			starta = entry->start;
1560 	}
1561 
1562 	/*
1563 	 * Generate the sequence of virtual addresses that are candidates for
1564 	 * prefaulting in an outward spiral from the faulting virtual address,
1565 	 * "addra".  Specifically, the sequence is "addra - PAGE_SIZE", "addra
1566 	 * + PAGE_SIZE", "addra - 2 * PAGE_SIZE", "addra + 2 * PAGE_SIZE", ...
1567 	 * If the candidate address doesn't have a backing physical page, then
1568 	 * the loop immediately terminates.
1569 	 */
1570 	for (i = 0; i < 2 * imax(backward, forward); i++) {
1571 		addr = addra + ((i >> 1) + 1) * ((i & 1) == 0 ? -PAGE_SIZE :
1572 		    PAGE_SIZE);
1573 		if (addr > addra + forward * PAGE_SIZE)
1574 			addr = 0;
1575 
1576 		if (addr < starta || addr >= entry->end)
1577 			continue;
1578 
1579 		if (!pmap_is_prefaultable(pmap, addr))
1580 			continue;
1581 
1582 		pindex = ((addr - entry->start) + entry->offset) >> PAGE_SHIFT;
1583 		lobject = entry->object.vm_object;
1584 		if (!obj_locked)
1585 			VM_OBJECT_RLOCK(lobject);
1586 		while ((m = vm_page_lookup(lobject, pindex)) == NULL &&
1587 		    lobject->type == OBJT_DEFAULT &&
1588 		    (backing_object = lobject->backing_object) != NULL) {
1589 			KASSERT((lobject->backing_object_offset & PAGE_MASK) ==
1590 			    0, ("vm_fault_prefault: unaligned object offset"));
1591 			pindex += lobject->backing_object_offset >> PAGE_SHIFT;
1592 			VM_OBJECT_RLOCK(backing_object);
1593 			if (!obj_locked || lobject != entry->object.vm_object)
1594 				VM_OBJECT_RUNLOCK(lobject);
1595 			lobject = backing_object;
1596 		}
1597 		if (m == NULL) {
1598 			if (!obj_locked || lobject != entry->object.vm_object)
1599 				VM_OBJECT_RUNLOCK(lobject);
1600 			break;
1601 		}
1602 		if (vm_page_all_valid(m) &&
1603 		    (m->flags & PG_FICTITIOUS) == 0)
1604 			pmap_enter_quick(pmap, addr, m, entry->protection);
1605 		if (!obj_locked || lobject != entry->object.vm_object)
1606 			VM_OBJECT_RUNLOCK(lobject);
1607 	}
1608 }
1609 
1610 /*
1611  * Hold each of the physical pages that are mapped by the specified range of
1612  * virtual addresses, ["addr", "addr" + "len"), if those mappings are valid
1613  * and allow the specified types of access, "prot".  If all of the implied
1614  * pages are successfully held, then the number of held pages is returned
1615  * together with pointers to those pages in the array "ma".  However, if any
1616  * of the pages cannot be held, -1 is returned.
1617  */
1618 int
1619 vm_fault_quick_hold_pages(vm_map_t map, vm_offset_t addr, vm_size_t len,
1620     vm_prot_t prot, vm_page_t *ma, int max_count)
1621 {
1622 	vm_offset_t end, va;
1623 	vm_page_t *mp;
1624 	int count;
1625 	boolean_t pmap_failed;
1626 
1627 	if (len == 0)
1628 		return (0);
1629 	end = round_page(addr + len);
1630 	addr = trunc_page(addr);
1631 
1632 	/*
1633 	 * Check for illegal addresses.
1634 	 */
1635 	if (addr < vm_map_min(map) || addr > end || end > vm_map_max(map))
1636 		return (-1);
1637 
1638 	if (atop(end - addr) > max_count)
1639 		panic("vm_fault_quick_hold_pages: count > max_count");
1640 	count = atop(end - addr);
1641 
1642 	/*
1643 	 * Most likely, the physical pages are resident in the pmap, so it is
1644 	 * faster to try pmap_extract_and_hold() first.
1645 	 */
1646 	pmap_failed = FALSE;
1647 	for (mp = ma, va = addr; va < end; mp++, va += PAGE_SIZE) {
1648 		*mp = pmap_extract_and_hold(map->pmap, va, prot);
1649 		if (*mp == NULL)
1650 			pmap_failed = TRUE;
1651 		else if ((prot & VM_PROT_WRITE) != 0 &&
1652 		    (*mp)->dirty != VM_PAGE_BITS_ALL) {
1653 			/*
1654 			 * Explicitly dirty the physical page.  Otherwise, the
1655 			 * caller's changes may go unnoticed because they are
1656 			 * performed through an unmanaged mapping or by a DMA
1657 			 * operation.
1658 			 *
1659 			 * The object lock is not held here.
1660 			 * See vm_page_clear_dirty_mask().
1661 			 */
1662 			vm_page_dirty(*mp);
1663 		}
1664 	}
1665 	if (pmap_failed) {
1666 		/*
1667 		 * One or more pages could not be held by the pmap.  Either no
1668 		 * page was mapped at the specified virtual address or that
1669 		 * mapping had insufficient permissions.  Attempt to fault in
1670 		 * and hold these pages.
1671 		 *
1672 		 * If vm_fault_disable_pagefaults() was called,
1673 		 * i.e., TDP_NOFAULTING is set, we must not sleep nor
1674 		 * acquire MD VM locks, which means we must not call
1675 		 * vm_fault().  Some (out of tree) callers mark
1676 		 * too wide a code area with vm_fault_disable_pagefaults()
1677 		 * already, use the VM_PROT_QUICK_NOFAULT flag to request
1678 		 * the proper behaviour explicitly.
1679 		 */
1680 		if ((prot & VM_PROT_QUICK_NOFAULT) != 0 &&
1681 		    (curthread->td_pflags & TDP_NOFAULTING) != 0)
1682 			goto error;
1683 		for (mp = ma, va = addr; va < end; mp++, va += PAGE_SIZE)
1684 			if (*mp == NULL && vm_fault(map, va, prot,
1685 			    VM_FAULT_NORMAL, mp) != KERN_SUCCESS)
1686 				goto error;
1687 	}
1688 	return (count);
1689 error:
1690 	for (mp = ma; mp < ma + count; mp++)
1691 		if (*mp != NULL)
1692 			vm_page_unwire(*mp, PQ_INACTIVE);
1693 	return (-1);
1694 }
1695 
1696 /*
1697  *	Routine:
1698  *		vm_fault_copy_entry
1699  *	Function:
1700  *		Create new shadow object backing dst_entry with private copy of
1701  *		all underlying pages. When src_entry is equal to dst_entry,
1702  *		function implements COW for wired-down map entry. Otherwise,
1703  *		it forks wired entry into dst_map.
1704  *
1705  *	In/out conditions:
1706  *		The source and destination maps must be locked for write.
1707  *		The source map entry must be wired down (or be a sharing map
1708  *		entry corresponding to a main map entry that is wired down).
1709  */
1710 void
1711 vm_fault_copy_entry(vm_map_t dst_map, vm_map_t src_map,
1712     vm_map_entry_t dst_entry, vm_map_entry_t src_entry,
1713     vm_ooffset_t *fork_charge)
1714 {
1715 	vm_object_t backing_object, dst_object, object, src_object;
1716 	vm_pindex_t dst_pindex, pindex, src_pindex;
1717 	vm_prot_t access, prot;
1718 	vm_offset_t vaddr;
1719 	vm_page_t dst_m;
1720 	vm_page_t src_m;
1721 	boolean_t upgrade;
1722 
1723 #ifdef	lint
1724 	src_map++;
1725 #endif	/* lint */
1726 
1727 	upgrade = src_entry == dst_entry;
1728 	access = prot = dst_entry->protection;
1729 
1730 	src_object = src_entry->object.vm_object;
1731 	src_pindex = OFF_TO_IDX(src_entry->offset);
1732 
1733 	if (upgrade && (dst_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) {
1734 		dst_object = src_object;
1735 		vm_object_reference(dst_object);
1736 	} else {
1737 		/*
1738 		 * Create the top-level object for the destination entry.
1739 		 * Doesn't actually shadow anything - we copy the pages
1740 		 * directly.
1741 		 */
1742 		dst_object = vm_object_allocate_anon(atop(dst_entry->end -
1743 		    dst_entry->start), NULL, NULL, 0);
1744 #if VM_NRESERVLEVEL > 0
1745 		dst_object->flags |= OBJ_COLORED;
1746 		dst_object->pg_color = atop(dst_entry->start);
1747 #endif
1748 		dst_object->domain = src_object->domain;
1749 		dst_object->charge = dst_entry->end - dst_entry->start;
1750 	}
1751 
1752 	VM_OBJECT_WLOCK(dst_object);
1753 	KASSERT(upgrade || dst_entry->object.vm_object == NULL,
1754 	    ("vm_fault_copy_entry: vm_object not NULL"));
1755 	if (src_object != dst_object) {
1756 		dst_entry->object.vm_object = dst_object;
1757 		dst_entry->offset = 0;
1758 		dst_entry->eflags &= ~MAP_ENTRY_VN_EXEC;
1759 	}
1760 	if (fork_charge != NULL) {
1761 		KASSERT(dst_entry->cred == NULL,
1762 		    ("vm_fault_copy_entry: leaked swp charge"));
1763 		dst_object->cred = curthread->td_ucred;
1764 		crhold(dst_object->cred);
1765 		*fork_charge += dst_object->charge;
1766 	} else if ((dst_object->type == OBJT_DEFAULT ||
1767 	    dst_object->type == OBJT_SWAP) &&
1768 	    dst_object->cred == NULL) {
1769 		KASSERT(dst_entry->cred != NULL, ("no cred for entry %p",
1770 		    dst_entry));
1771 		dst_object->cred = dst_entry->cred;
1772 		dst_entry->cred = NULL;
1773 	}
1774 
1775 	/*
1776 	 * If not an upgrade, then enter the mappings in the pmap as
1777 	 * read and/or execute accesses.  Otherwise, enter them as
1778 	 * write accesses.
1779 	 *
1780 	 * A writeable large page mapping is only created if all of
1781 	 * the constituent small page mappings are modified. Marking
1782 	 * PTEs as modified on inception allows promotion to happen
1783 	 * without taking potentially large number of soft faults.
1784 	 */
1785 	if (!upgrade)
1786 		access &= ~VM_PROT_WRITE;
1787 
1788 	/*
1789 	 * Loop through all of the virtual pages within the entry's
1790 	 * range, copying each page from the source object to the
1791 	 * destination object.  Since the source is wired, those pages
1792 	 * must exist.  In contrast, the destination is pageable.
1793 	 * Since the destination object doesn't share any backing storage
1794 	 * with the source object, all of its pages must be dirtied,
1795 	 * regardless of whether they can be written.
1796 	 */
1797 	for (vaddr = dst_entry->start, dst_pindex = 0;
1798 	    vaddr < dst_entry->end;
1799 	    vaddr += PAGE_SIZE, dst_pindex++) {
1800 again:
1801 		/*
1802 		 * Find the page in the source object, and copy it in.
1803 		 * Because the source is wired down, the page will be
1804 		 * in memory.
1805 		 */
1806 		if (src_object != dst_object)
1807 			VM_OBJECT_RLOCK(src_object);
1808 		object = src_object;
1809 		pindex = src_pindex + dst_pindex;
1810 		while ((src_m = vm_page_lookup(object, pindex)) == NULL &&
1811 		    (backing_object = object->backing_object) != NULL) {
1812 			/*
1813 			 * Unless the source mapping is read-only or
1814 			 * it is presently being upgraded from
1815 			 * read-only, the first object in the shadow
1816 			 * chain should provide all of the pages.  In
1817 			 * other words, this loop body should never be
1818 			 * executed when the source mapping is already
1819 			 * read/write.
1820 			 */
1821 			KASSERT((src_entry->protection & VM_PROT_WRITE) == 0 ||
1822 			    upgrade,
1823 			    ("vm_fault_copy_entry: main object missing page"));
1824 
1825 			VM_OBJECT_RLOCK(backing_object);
1826 			pindex += OFF_TO_IDX(object->backing_object_offset);
1827 			if (object != dst_object)
1828 				VM_OBJECT_RUNLOCK(object);
1829 			object = backing_object;
1830 		}
1831 		KASSERT(src_m != NULL, ("vm_fault_copy_entry: page missing"));
1832 
1833 		if (object != dst_object) {
1834 			/*
1835 			 * Allocate a page in the destination object.
1836 			 */
1837 			dst_m = vm_page_alloc(dst_object, (src_object ==
1838 			    dst_object ? src_pindex : 0) + dst_pindex,
1839 			    VM_ALLOC_NORMAL);
1840 			if (dst_m == NULL) {
1841 				VM_OBJECT_WUNLOCK(dst_object);
1842 				VM_OBJECT_RUNLOCK(object);
1843 				vm_wait(dst_object);
1844 				VM_OBJECT_WLOCK(dst_object);
1845 				goto again;
1846 			}
1847 			pmap_copy_page(src_m, dst_m);
1848 			VM_OBJECT_RUNLOCK(object);
1849 			dst_m->dirty = dst_m->valid = src_m->valid;
1850 		} else {
1851 			dst_m = src_m;
1852 			if (vm_page_busy_acquire(dst_m, VM_ALLOC_WAITFAIL) == 0)
1853 				goto again;
1854 			if (dst_m->pindex >= dst_object->size) {
1855 				/*
1856 				 * We are upgrading.  Index can occur
1857 				 * out of bounds if the object type is
1858 				 * vnode and the file was truncated.
1859 				 */
1860 				vm_page_xunbusy(dst_m);
1861 				break;
1862 			}
1863 		}
1864 		VM_OBJECT_WUNLOCK(dst_object);
1865 
1866 		/*
1867 		 * Enter it in the pmap. If a wired, copy-on-write
1868 		 * mapping is being replaced by a write-enabled
1869 		 * mapping, then wire that new mapping.
1870 		 *
1871 		 * The page can be invalid if the user called
1872 		 * msync(MS_INVALIDATE) or truncated the backing vnode
1873 		 * or shared memory object.  In this case, do not
1874 		 * insert it into pmap, but still do the copy so that
1875 		 * all copies of the wired map entry have similar
1876 		 * backing pages.
1877 		 */
1878 		if (vm_page_all_valid(dst_m)) {
1879 			pmap_enter(dst_map->pmap, vaddr, dst_m, prot,
1880 			    access | (upgrade ? PMAP_ENTER_WIRED : 0), 0);
1881 		}
1882 
1883 		/*
1884 		 * Mark it no longer busy, and put it on the active list.
1885 		 */
1886 		VM_OBJECT_WLOCK(dst_object);
1887 
1888 		if (upgrade) {
1889 			if (src_m != dst_m) {
1890 				vm_page_unwire(src_m, PQ_INACTIVE);
1891 				vm_page_wire(dst_m);
1892 			} else {
1893 				KASSERT(vm_page_wired(dst_m),
1894 				    ("dst_m %p is not wired", dst_m));
1895 			}
1896 		} else {
1897 			vm_page_lock(dst_m);
1898 			vm_page_activate(dst_m);
1899 			vm_page_unlock(dst_m);
1900 		}
1901 		vm_page_xunbusy(dst_m);
1902 	}
1903 	VM_OBJECT_WUNLOCK(dst_object);
1904 	if (upgrade) {
1905 		dst_entry->eflags &= ~(MAP_ENTRY_COW | MAP_ENTRY_NEEDS_COPY);
1906 		vm_object_deallocate(src_object);
1907 	}
1908 }
1909 
1910 /*
1911  * Block entry into the machine-independent layer's page fault handler by
1912  * the calling thread.  Subsequent calls to vm_fault() by that thread will
1913  * return KERN_PROTECTION_FAILURE.  Enable machine-dependent handling of
1914  * spurious page faults.
1915  */
1916 int
1917 vm_fault_disable_pagefaults(void)
1918 {
1919 
1920 	return (curthread_pflags_set(TDP_NOFAULTING | TDP_RESETSPUR));
1921 }
1922 
1923 void
1924 vm_fault_enable_pagefaults(int save)
1925 {
1926 
1927 	curthread_pflags_restore(save);
1928 }
1929