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