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