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