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