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