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