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