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