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