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