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