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