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