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