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