xref: /freebsd/sys/vm/vm_fault.c (revision dce6e6518b85561495cff38a3074a69d29d58a55)
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 <sys/param.h>
78 #include <sys/systm.h>
79 #include <sys/kernel.h>
80 #include <sys/lock.h>
81 #include <sys/mutex.h>
82 #include <sys/proc.h>
83 #include <sys/resourcevar.h>
84 #include <sys/sysctl.h>
85 #include <sys/vmmeter.h>
86 #include <sys/vnode.h>
87 
88 #include <vm/vm.h>
89 #include <vm/vm_param.h>
90 #include <vm/pmap.h>
91 #include <vm/vm_map.h>
92 #include <vm/vm_object.h>
93 #include <vm/vm_page.h>
94 #include <vm/vm_pageout.h>
95 #include <vm/vm_kern.h>
96 #include <vm/vm_pager.h>
97 #include <vm/vnode_pager.h>
98 #include <vm/vm_extern.h>
99 
100 static int vm_fault_additional_pages(vm_page_t, int, int, vm_page_t *, int *);
101 
102 #define VM_FAULT_READ_AHEAD 8
103 #define VM_FAULT_READ_BEHIND 7
104 #define VM_FAULT_READ (VM_FAULT_READ_AHEAD+VM_FAULT_READ_BEHIND+1)
105 
106 struct faultstate {
107 	vm_page_t m;
108 	vm_object_t object;
109 	vm_pindex_t pindex;
110 	vm_page_t first_m;
111 	vm_object_t	first_object;
112 	vm_pindex_t first_pindex;
113 	vm_map_t map;
114 	vm_map_entry_t entry;
115 	int lookup_still_valid;
116 	struct vnode *vp;
117 };
118 
119 static __inline void
120 release_page(struct faultstate *fs)
121 {
122 	vm_page_lock_queues();
123 	vm_page_wakeup(fs->m);
124 	vm_page_deactivate(fs->m);
125 	vm_page_unlock_queues();
126 	fs->m = NULL;
127 }
128 
129 static __inline void
130 unlock_map(struct faultstate *fs)
131 {
132 	if (fs->lookup_still_valid) {
133 		vm_map_lookup_done(fs->map, fs->entry);
134 		fs->lookup_still_valid = FALSE;
135 	}
136 }
137 
138 static void
139 _unlock_things(struct faultstate *fs, int dealloc)
140 {
141 
142 	vm_object_pip_wakeup(fs->object);
143 	VM_OBJECT_UNLOCK(fs->object);
144 	if (fs->object != fs->first_object) {
145 		VM_OBJECT_LOCK(fs->first_object);
146 		vm_page_lock_queues();
147 		vm_page_free(fs->first_m);
148 		vm_page_unlock_queues();
149 		vm_object_pip_wakeup(fs->first_object);
150 		VM_OBJECT_UNLOCK(fs->first_object);
151 		fs->first_m = NULL;
152 	}
153 	if (dealloc) {
154 		vm_object_deallocate(fs->first_object);
155 	}
156 	unlock_map(fs);
157 	if (fs->vp != NULL) {
158 		vput(fs->vp);
159 		fs->vp = NULL;
160 	}
161 }
162 
163 #define unlock_things(fs) _unlock_things(fs, 0)
164 #define unlock_and_deallocate(fs) _unlock_things(fs, 1)
165 
166 /*
167  * TRYPAGER - used by vm_fault to calculate whether the pager for the
168  *	      current object *might* contain the page.
169  *
170  *	      default objects are zero-fill, there is no real pager.
171  */
172 #define TRYPAGER	(fs.object->type != OBJT_DEFAULT && \
173 			(((fault_flags & VM_FAULT_WIRE_MASK) == 0) || wired))
174 
175 /*
176  *	vm_fault:
177  *
178  *	Handle a page fault occurring at the given address,
179  *	requiring the given permissions, in the map specified.
180  *	If successful, the page is inserted into the
181  *	associated physical map.
182  *
183  *	NOTE: the given address should be truncated to the
184  *	proper page address.
185  *
186  *	KERN_SUCCESS is returned if the page fault is handled; otherwise,
187  *	a standard error specifying why the fault is fatal is returned.
188  *
189  *
190  *	The map in question must be referenced, and remains so.
191  *	Caller may hold no locks.
192  */
193 int
194 vm_fault(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
195 	 int fault_flags)
196 {
197 	vm_prot_t prot;
198 	int is_first_object_locked, result;
199 	boolean_t growstack, wired;
200 	int map_generation;
201 	vm_object_t next_object;
202 	vm_page_t marray[VM_FAULT_READ];
203 	int hardfault;
204 	int faultcount;
205 	struct faultstate fs;
206 
207 	hardfault = 0;
208 	growstack = TRUE;
209 	atomic_add_int(&cnt.v_vm_faults, 1);
210 
211 	mtx_lock(&Giant);
212 RetryFault:;
213 
214 	/*
215 	 * Find the backing store object and offset into it to begin the
216 	 * search.
217 	 */
218 	fs.map = map;
219 	result = vm_map_lookup(&fs.map, vaddr, fault_type, &fs.entry,
220 	    &fs.first_object, &fs.first_pindex, &prot, &wired);
221 	if (result != KERN_SUCCESS) {
222 		if (result != KERN_PROTECTION_FAILURE ||
223 		    (fault_flags & VM_FAULT_WIRE_MASK) != VM_FAULT_USER_WIRE) {
224 			if (growstack && result == KERN_INVALID_ADDRESS &&
225 			    map != kernel_map && curproc != NULL) {
226 				result = vm_map_growstack(curproc, vaddr);
227 				if (result != KERN_SUCCESS) {
228 					mtx_unlock(&Giant);
229 					return (KERN_FAILURE);
230 				}
231 				growstack = FALSE;
232 				goto RetryFault;
233 			}
234 			mtx_unlock(&Giant);
235 			return (result);
236 		}
237 
238 		/*
239    		 * If we are user-wiring a r/w segment, and it is COW, then
240    		 * we need to do the COW operation.  Note that we don't COW
241    		 * currently RO sections now, because it is NOT desirable
242    		 * to COW .text.  We simply keep .text from ever being COW'ed
243    		 * and take the heat that one cannot debug wired .text sections.
244    		 */
245 		result = vm_map_lookup(&fs.map, vaddr,
246 			VM_PROT_READ|VM_PROT_WRITE|VM_PROT_OVERRIDE_WRITE,
247 			&fs.entry, &fs.first_object, &fs.first_pindex, &prot, &wired);
248 		if (result != KERN_SUCCESS) {
249 			mtx_unlock(&Giant);
250 			return (result);
251 		}
252 
253 		/*
254 		 * If we don't COW now, on a user wire, the user will never
255 		 * be able to write to the mapping.  If we don't make this
256 		 * restriction, the bookkeeping would be nearly impossible.
257 		 *
258 		 * XXX The following assignment modifies the map without
259 		 * holding a write lock on it.
260 		 */
261 		if ((fs.entry->protection & VM_PROT_WRITE) == 0)
262 			fs.entry->max_protection &= ~VM_PROT_WRITE;
263 	}
264 
265 	map_generation = fs.map->timestamp;
266 
267 	if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
268 		panic("vm_fault: fault on nofault entry, addr: %lx",
269 		    (u_long)vaddr);
270 	}
271 
272 	/*
273 	 * Make a reference to this object to prevent its disposal while we
274 	 * are messing with it.  Once we have the reference, the map is free
275 	 * to be diddled.  Since objects reference their shadows (and copies),
276 	 * they will stay around as well.
277 	 *
278 	 * Bump the paging-in-progress count to prevent size changes (e.g.
279 	 * truncation operations) during I/O.  This must be done after
280 	 * obtaining the vnode lock in order to avoid possible deadlocks.
281 	 *
282 	 * XXX vnode_pager_lock() can block without releasing the map lock.
283 	 */
284 	vm_object_reference(fs.first_object);
285 	fs.vp = vnode_pager_lock(fs.first_object);
286 	VM_OBJECT_LOCK(fs.first_object);
287 	vm_object_pip_add(fs.first_object, 1);
288 
289 	fs.lookup_still_valid = TRUE;
290 
291 	if (wired)
292 		fault_type = prot;
293 
294 	fs.first_m = NULL;
295 
296 	/*
297 	 * Search for the page at object/offset.
298 	 */
299 	fs.object = fs.first_object;
300 	fs.pindex = fs.first_pindex;
301 	while (TRUE) {
302 		/*
303 		 * If the object is dead, we stop here
304 		 */
305 		if (fs.object->flags & OBJ_DEAD) {
306 			unlock_and_deallocate(&fs);
307 			mtx_unlock(&Giant);
308 			return (KERN_PROTECTION_FAILURE);
309 		}
310 
311 		/*
312 		 * See if page is resident
313 		 */
314 		fs.m = vm_page_lookup(fs.object, fs.pindex);
315 		if (fs.m != NULL) {
316 			int queue, s;
317 
318 			/*
319 			 * check for page-based copy on write.
320 			 * We check fs.object == fs.first_object so
321 			 * as to ensure the legacy COW mechanism is
322 			 * used when the page in question is part of
323 			 * a shadow object.  Otherwise, vm_page_cowfault()
324 			 * removes the page from the backing object,
325 			 * which is not what we want.
326 			 */
327 			vm_page_lock_queues();
328 			if ((fs.m->cow) &&
329 			    (fault_type & VM_PROT_WRITE) &&
330 			    (fs.object == fs.first_object)) {
331 				s = splvm();
332 				vm_page_cowfault(fs.m);
333 				splx(s);
334 				vm_page_unlock_queues();
335 				unlock_and_deallocate(&fs);
336 				goto RetryFault;
337 			}
338 
339 			/*
340 			 * Wait/Retry if the page is busy.  We have to do this
341 			 * if the page is busy via either PG_BUSY or
342 			 * vm_page_t->busy because the vm_pager may be using
343 			 * vm_page_t->busy for pageouts ( and even pageins if
344 			 * it is the vnode pager ), and we could end up trying
345 			 * to pagein and pageout the same page simultaneously.
346 			 *
347 			 * We can theoretically allow the busy case on a read
348 			 * fault if the page is marked valid, but since such
349 			 * pages are typically already pmap'd, putting that
350 			 * special case in might be more effort then it is
351 			 * worth.  We cannot under any circumstances mess
352 			 * around with a vm_page_t->busy page except, perhaps,
353 			 * to pmap it.
354 			 */
355 			if ((fs.m->flags & PG_BUSY) || fs.m->busy) {
356 				vm_page_unlock_queues();
357 				unlock_things(&fs);
358 				vm_page_lock_queues();
359 				if (!vm_page_sleep_if_busy(fs.m, TRUE, "vmpfw"))
360 					vm_page_unlock_queues();
361 				cnt.v_intrans++;
362 				vm_object_deallocate(fs.first_object);
363 				goto RetryFault;
364 			}
365 			queue = fs.m->queue;
366 
367 			s = splvm();
368 			vm_pageq_remove_nowakeup(fs.m);
369 			splx(s);
370 
371 			if ((queue - fs.m->pc) == PQ_CACHE && vm_page_count_severe()) {
372 				vm_page_activate(fs.m);
373 				vm_page_unlock_queues();
374 				unlock_and_deallocate(&fs);
375 				VM_WAITPFAULT;
376 				goto RetryFault;
377 			}
378 
379 			/*
380 			 * Mark page busy for other processes, and the
381 			 * pagedaemon.  If it still isn't completely valid
382 			 * (readable), jump to readrest, else break-out ( we
383 			 * found the page ).
384 			 */
385 			vm_page_busy(fs.m);
386 			vm_page_unlock_queues();
387 			if (((fs.m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) &&
388 				fs.m->object != kernel_object && fs.m->object != kmem_object) {
389 				goto readrest;
390 			}
391 
392 			break;
393 		}
394 
395 		/*
396 		 * Page is not resident, If this is the search termination
397 		 * or the pager might contain the page, allocate a new page.
398 		 */
399 		if (TRYPAGER || fs.object == fs.first_object) {
400 			if (fs.pindex >= fs.object->size) {
401 				unlock_and_deallocate(&fs);
402 				mtx_unlock(&Giant);
403 				return (KERN_PROTECTION_FAILURE);
404 			}
405 
406 			/*
407 			 * Allocate a new page for this object/offset pair.
408 			 */
409 			fs.m = NULL;
410 			if (!vm_page_count_severe()) {
411 				fs.m = vm_page_alloc(fs.object, fs.pindex,
412 				    (fs.vp || fs.object->backing_object)? VM_ALLOC_NORMAL: VM_ALLOC_ZERO);
413 			}
414 			if (fs.m == NULL) {
415 				unlock_and_deallocate(&fs);
416 				VM_WAITPFAULT;
417 				goto RetryFault;
418 			}
419 		}
420 
421 readrest:
422 		/*
423 		 * We have found a valid page or we have allocated a new page.
424 		 * The page thus may not be valid or may not be entirely
425 		 * valid.
426 		 *
427 		 * Attempt to fault-in the page if there is a chance that the
428 		 * pager has it, and potentially fault in additional pages
429 		 * at the same time.
430 		 */
431 		if (TRYPAGER) {
432 			int rv;
433 			int reqpage;
434 			int ahead, behind;
435 			u_char behavior = vm_map_entry_behavior(fs.entry);
436 
437 			if (behavior == MAP_ENTRY_BEHAV_RANDOM) {
438 				ahead = 0;
439 				behind = 0;
440 			} else {
441 				behind = (vaddr - fs.entry->start) >> PAGE_SHIFT;
442 				if (behind > VM_FAULT_READ_BEHIND)
443 					behind = VM_FAULT_READ_BEHIND;
444 
445 				ahead = ((fs.entry->end - vaddr) >> PAGE_SHIFT) - 1;
446 				if (ahead > VM_FAULT_READ_AHEAD)
447 					ahead = VM_FAULT_READ_AHEAD;
448 			}
449 
450 			if ((fs.first_object->type != OBJT_DEVICE) &&
451 			    (behavior == MAP_ENTRY_BEHAV_SEQUENTIAL ||
452                                 (behavior != MAP_ENTRY_BEHAV_RANDOM &&
453                                 fs.pindex >= fs.entry->lastr &&
454                                 fs.pindex < fs.entry->lastr + VM_FAULT_READ))
455 			) {
456 				vm_pindex_t firstpindex, tmppindex;
457 
458 				if (fs.first_pindex < 2 * VM_FAULT_READ)
459 					firstpindex = 0;
460 				else
461 					firstpindex = fs.first_pindex - 2 * VM_FAULT_READ;
462 
463 				vm_page_lock_queues();
464 				/*
465 				 * note: partially valid pages cannot be
466 				 * included in the lookahead - NFS piecemeal
467 				 * writes will barf on it badly.
468 				 */
469 				for (tmppindex = fs.first_pindex - 1;
470 					tmppindex >= firstpindex;
471 					--tmppindex) {
472 					vm_page_t mt;
473 
474 					mt = vm_page_lookup(fs.first_object, tmppindex);
475 					if (mt == NULL || (mt->valid != VM_PAGE_BITS_ALL))
476 						break;
477 					if (mt->busy ||
478 						(mt->flags & (PG_BUSY | PG_FICTITIOUS | PG_UNMANAGED)) ||
479 						mt->hold_count ||
480 						mt->wire_count)
481 						continue;
482 					if (mt->dirty == 0)
483 						vm_page_test_dirty(mt);
484 					if (mt->dirty) {
485 						pmap_remove_all(mt);
486 						vm_page_deactivate(mt);
487 					} else {
488 						vm_page_cache(mt);
489 					}
490 				}
491 				vm_page_unlock_queues();
492 				ahead += behind;
493 				behind = 0;
494 			}
495 
496 			/*
497 			 * now we find out if any other pages should be paged
498 			 * in at this time this routine checks to see if the
499 			 * pages surrounding this fault reside in the same
500 			 * object as the page for this fault.  If they do,
501 			 * then they are faulted in also into the object.  The
502 			 * array "marray" returned contains an array of
503 			 * vm_page_t structs where one of them is the
504 			 * vm_page_t passed to the routine.  The reqpage
505 			 * return value is the index into the marray for the
506 			 * vm_page_t passed to the routine.
507 			 *
508 			 * fs.m plus the additional pages are PG_BUSY'd.
509 			 *
510 			 * XXX vm_fault_additional_pages() can block
511 			 * without releasing the map lock.
512 			 */
513 			faultcount = vm_fault_additional_pages(
514 			    fs.m, behind, ahead, marray, &reqpage);
515 
516 			/*
517 			 * update lastr imperfectly (we do not know how much
518 			 * getpages will actually read), but good enough.
519 			 *
520 			 * XXX The following assignment modifies the map
521 			 * without holding a write lock on it.
522 			 */
523 			fs.entry->lastr = fs.pindex + faultcount - behind;
524 
525 			/*
526 			 * Call the pager to retrieve the data, if any, after
527 			 * releasing the lock on the map.  We hold a ref on
528 			 * fs.object and the pages are PG_BUSY'd.
529 			 */
530 			unlock_map(&fs);
531 
532 			rv = faultcount ?
533 			    vm_pager_get_pages(fs.object, marray, faultcount,
534 				reqpage) : VM_PAGER_FAIL;
535 
536 			if (rv == VM_PAGER_OK) {
537 				/*
538 				 * Found the page. Leave it busy while we play
539 				 * with it.
540 				 */
541 
542 				/*
543 				 * Relookup in case pager changed page. Pager
544 				 * is responsible for disposition of old page
545 				 * if moved.
546 				 */
547 				fs.m = vm_page_lookup(fs.object, fs.pindex);
548 				if (!fs.m) {
549 					unlock_and_deallocate(&fs);
550 					goto RetryFault;
551 				}
552 
553 				hardfault++;
554 				break; /* break to PAGE HAS BEEN FOUND */
555 			}
556 			/*
557 			 * Remove the bogus page (which does not exist at this
558 			 * object/offset); before doing so, we must get back
559 			 * our object lock to preserve our invariant.
560 			 *
561 			 * Also wake up any other process that may want to bring
562 			 * in this page.
563 			 *
564 			 * If this is the top-level object, we must leave the
565 			 * busy page to prevent another process from rushing
566 			 * past us, and inserting the page in that object at
567 			 * the same time that we are.
568 			 */
569 			if (rv == VM_PAGER_ERROR)
570 				printf("vm_fault: pager read error, pid %d (%s)\n",
571 				    curproc->p_pid, curproc->p_comm);
572 			/*
573 			 * Data outside the range of the pager or an I/O error
574 			 */
575 			/*
576 			 * XXX - the check for kernel_map is a kludge to work
577 			 * around having the machine panic on a kernel space
578 			 * fault w/ I/O error.
579 			 */
580 			if (((fs.map != kernel_map) && (rv == VM_PAGER_ERROR)) ||
581 				(rv == VM_PAGER_BAD)) {
582 				vm_page_lock_queues();
583 				vm_page_free(fs.m);
584 				vm_page_unlock_queues();
585 				fs.m = NULL;
586 				unlock_and_deallocate(&fs);
587 				mtx_unlock(&Giant);
588 				return ((rv == VM_PAGER_ERROR) ? KERN_FAILURE : KERN_PROTECTION_FAILURE);
589 			}
590 			if (fs.object != fs.first_object) {
591 				vm_page_lock_queues();
592 				vm_page_free(fs.m);
593 				vm_page_unlock_queues();
594 				fs.m = NULL;
595 				/*
596 				 * XXX - we cannot just fall out at this
597 				 * point, m has been freed and is invalid!
598 				 */
599 			}
600 		}
601 
602 		/*
603 		 * We get here if the object has default pager (or unwiring)
604 		 * or the pager doesn't have the page.
605 		 */
606 		if (fs.object == fs.first_object)
607 			fs.first_m = fs.m;
608 
609 		/*
610 		 * Move on to the next object.  Lock the next object before
611 		 * unlocking the current one.
612 		 */
613 		fs.pindex += OFF_TO_IDX(fs.object->backing_object_offset);
614 		next_object = fs.object->backing_object;
615 		if (next_object == NULL) {
616 			/*
617 			 * If there's no object left, fill the page in the top
618 			 * object with zeros.
619 			 */
620 			if (fs.object != fs.first_object) {
621 				vm_object_pip_wakeup(fs.object);
622 				VM_OBJECT_UNLOCK(fs.object);
623 
624 				fs.object = fs.first_object;
625 				fs.pindex = fs.first_pindex;
626 				fs.m = fs.first_m;
627 				VM_OBJECT_LOCK(fs.object);
628 			}
629 			fs.first_m = NULL;
630 
631 			/*
632 			 * Zero the page if necessary and mark it valid.
633 			 */
634 			if ((fs.m->flags & PG_ZERO) == 0) {
635 				pmap_zero_page(fs.m);
636 			} else {
637 				cnt.v_ozfod++;
638 			}
639 			cnt.v_zfod++;
640 			fs.m->valid = VM_PAGE_BITS_ALL;
641 			break;	/* break to PAGE HAS BEEN FOUND */
642 		} else {
643 			KASSERT(fs.object != next_object,
644 			    ("object loop %p", next_object));
645 			VM_OBJECT_LOCK(next_object);
646 			vm_object_pip_add(next_object, 1);
647 			if (fs.object != fs.first_object)
648 				vm_object_pip_wakeup(fs.object);
649 			VM_OBJECT_UNLOCK(fs.object);
650 			fs.object = next_object;
651 		}
652 	}
653 
654 	KASSERT((fs.m->flags & PG_BUSY) != 0,
655 	    ("vm_fault: not busy after main loop"));
656 
657 	/*
658 	 * PAGE HAS BEEN FOUND. [Loop invariant still holds -- the object lock
659 	 * is held.]
660 	 */
661 
662 	/*
663 	 * If the page is being written, but isn't already owned by the
664 	 * top-level object, we have to copy it into a new page owned by the
665 	 * top-level object.
666 	 */
667 	if (fs.object != fs.first_object) {
668 		/*
669 		 * We only really need to copy if we want to write it.
670 		 */
671 		if (fault_type & VM_PROT_WRITE) {
672 			/*
673 			 * This allows pages to be virtually copied from a
674 			 * backing_object into the first_object, where the
675 			 * backing object has no other refs to it, and cannot
676 			 * gain any more refs.  Instead of a bcopy, we just
677 			 * move the page from the backing object to the
678 			 * first object.  Note that we must mark the page
679 			 * dirty in the first object so that it will go out
680 			 * to swap when needed.
681 			 */
682 			is_first_object_locked = FALSE;
683 			if (
684 				/*
685 				 * Only one shadow object
686 				 */
687 				(fs.object->shadow_count == 1) &&
688 				/*
689 				 * No COW refs, except us
690 				 */
691 				(fs.object->ref_count == 1) &&
692 				/*
693 				 * No one else can look this object up
694 				 */
695 				(fs.object->handle == NULL) &&
696 				/*
697 				 * No other ways to look the object up
698 				 */
699 				((fs.object->type == OBJT_DEFAULT) ||
700 				 (fs.object->type == OBJT_SWAP)) &&
701 			    (is_first_object_locked = VM_OBJECT_TRYLOCK(fs.first_object)) &&
702 				/*
703 				 * We don't chase down the shadow chain
704 				 */
705 			    fs.object == fs.first_object->backing_object) {
706 				vm_page_lock_queues();
707 				/*
708 				 * get rid of the unnecessary page
709 				 */
710 				pmap_remove_all(fs.first_m);
711 				vm_page_free(fs.first_m);
712 				/*
713 				 * grab the page and put it into the
714 				 * process'es object.  The page is
715 				 * automatically made dirty.
716 				 */
717 				vm_page_rename(fs.m, fs.first_object, fs.first_pindex);
718 				vm_page_busy(fs.m);
719 				vm_page_unlock_queues();
720 				fs.first_m = fs.m;
721 				fs.m = NULL;
722 				cnt.v_cow_optim++;
723 			} else {
724 				/*
725 				 * Oh, well, lets copy it.
726 				 */
727 				vm_page_copy(fs.m, fs.first_m);
728 			}
729 			if (fs.m) {
730 				/*
731 				 * We no longer need the old page or object.
732 				 */
733 				release_page(&fs);
734 			}
735 			/*
736 			 * fs.object != fs.first_object due to above
737 			 * conditional
738 			 */
739 			vm_object_pip_wakeup(fs.object);
740 			VM_OBJECT_UNLOCK(fs.object);
741 			/*
742 			 * Only use the new page below...
743 			 */
744 			fs.object = fs.first_object;
745 			fs.pindex = fs.first_pindex;
746 			fs.m = fs.first_m;
747 			if (!is_first_object_locked)
748 				VM_OBJECT_LOCK(fs.object);
749 			cnt.v_cow_faults++;
750 		} else {
751 			prot &= ~VM_PROT_WRITE;
752 		}
753 	}
754 
755 	/*
756 	 * We must verify that the maps have not changed since our last
757 	 * lookup.
758 	 */
759 	if (!fs.lookup_still_valid &&
760 		(fs.map->timestamp != map_generation)) {
761 		vm_object_t retry_object;
762 		vm_pindex_t retry_pindex;
763 		vm_prot_t retry_prot;
764 
765 		/*
766 		 * Since map entries may be pageable, make sure we can take a
767 		 * page fault on them.
768 		 */
769 
770 		/*
771 		 * Unlock vnode before the lookup to avoid deadlock.   E.G.
772 		 * avoid a deadlock between the inode and exec_map that can
773 		 * occur due to locks being obtained in different orders.
774 		 */
775 		if (fs.vp != NULL) {
776 			vput(fs.vp);
777 			fs.vp = NULL;
778 		}
779 
780 		if (fs.map->infork) {
781 			release_page(&fs);
782 			unlock_and_deallocate(&fs);
783 			goto RetryFault;
784 		}
785 		VM_OBJECT_UNLOCK(fs.object);
786 
787 		/*
788 		 * To avoid trying to write_lock the map while another process
789 		 * has it read_locked (in vm_map_pageable), we do not try for
790 		 * write permission.  If the page is still writable, we will
791 		 * get write permission.  If it is not, or has been marked
792 		 * needs_copy, we enter the mapping without write permission,
793 		 * and will merely take another fault.
794 		 */
795 		result = vm_map_lookup(&fs.map, vaddr, fault_type & ~VM_PROT_WRITE,
796 		    &fs.entry, &retry_object, &retry_pindex, &retry_prot, &wired);
797 		map_generation = fs.map->timestamp;
798 
799 		VM_OBJECT_LOCK(fs.object);
800 		/*
801 		 * If we don't need the page any longer, put it on the active
802 		 * list (the easiest thing to do here).  If no one needs it,
803 		 * pageout will grab it eventually.
804 		 */
805 		if (result != KERN_SUCCESS) {
806 			release_page(&fs);
807 			unlock_and_deallocate(&fs);
808 			mtx_unlock(&Giant);
809 			return (result);
810 		}
811 		fs.lookup_still_valid = TRUE;
812 
813 		if ((retry_object != fs.first_object) ||
814 		    (retry_pindex != fs.first_pindex)) {
815 			release_page(&fs);
816 			unlock_and_deallocate(&fs);
817 			goto RetryFault;
818 		}
819 		/*
820 		 * Check whether the protection has changed or the object has
821 		 * been copied while we left the map unlocked. Changing from
822 		 * read to write permission is OK - we leave the page
823 		 * write-protected, and catch the write fault. Changing from
824 		 * write to read permission means that we can't mark the page
825 		 * write-enabled after all.
826 		 */
827 		prot &= retry_prot;
828 	}
829 
830 	/*
831 	 * Put this page into the physical map. We had to do the unlock above
832 	 * because pmap_enter may cause other faults.   We don't put the page
833 	 * back on the active queue until later so that the page-out daemon
834 	 * won't find us (yet).
835 	 */
836 
837 	if (prot & VM_PROT_WRITE) {
838 		vm_page_lock_queues();
839 		vm_page_flag_set(fs.m, PG_WRITEABLE);
840 		vm_object_set_writeable_dirty(fs.m->object);
841 
842 		/*
843 		 * If the fault is a write, we know that this page is being
844 		 * written NOW so dirty it explicitly to save on
845 		 * pmap_is_modified() calls later.
846 		 *
847 		 * If this is a NOSYNC mmap we do not want to set PG_NOSYNC
848 		 * if the page is already dirty to prevent data written with
849 		 * the expectation of being synced from not being synced.
850 		 * Likewise if this entry does not request NOSYNC then make
851 		 * sure the page isn't marked NOSYNC.  Applications sharing
852 		 * data should use the same flags to avoid ping ponging.
853 		 *
854 		 * Also tell the backing pager, if any, that it should remove
855 		 * any swap backing since the page is now dirty.
856 		 */
857 		if (fs.entry->eflags & MAP_ENTRY_NOSYNC) {
858 			if (fs.m->dirty == 0)
859 				vm_page_flag_set(fs.m, PG_NOSYNC);
860 		} else {
861 			vm_page_flag_clear(fs.m, PG_NOSYNC);
862 		}
863 		vm_page_unlock_queues();
864 		if (fault_flags & VM_FAULT_DIRTY) {
865 			int s;
866 			vm_page_dirty(fs.m);
867 			s = splvm();
868 			vm_pager_page_unswapped(fs.m);
869 			splx(s);
870 		}
871 	}
872 
873 	/*
874 	 * Page had better still be busy
875 	 */
876 	KASSERT(fs.m->flags & PG_BUSY,
877 		("vm_fault: page %p not busy!", fs.m));
878 	unlock_things(&fs);
879 
880 	/*
881 	 * Sanity check: page must be completely valid or it is not fit to
882 	 * map into user space.  vm_pager_get_pages() ensures this.
883 	 */
884 	if (fs.m->valid != VM_PAGE_BITS_ALL) {
885 		vm_page_zero_invalid(fs.m, TRUE);
886 		printf("Warning: page %p partially invalid on fault\n", fs.m);
887 	}
888 	pmap_enter(fs.map->pmap, vaddr, fs.m, prot, wired);
889 	if (((fault_flags & VM_FAULT_WIRE_MASK) == 0) && (wired == 0)) {
890 		pmap_prefault(fs.map->pmap, vaddr, fs.entry);
891 	}
892 	vm_page_lock_queues();
893 	vm_page_flag_clear(fs.m, PG_ZERO);
894 	vm_page_flag_set(fs.m, PG_REFERENCED);
895 
896 	/*
897 	 * If the page is not wired down, then put it where the pageout daemon
898 	 * can find it.
899 	 */
900 	if (fault_flags & VM_FAULT_WIRE_MASK) {
901 		if (wired)
902 			vm_page_wire(fs.m);
903 		else
904 			vm_page_unwire(fs.m, 1);
905 	} else {
906 		vm_page_activate(fs.m);
907 	}
908 	vm_page_wakeup(fs.m);
909 	vm_page_unlock_queues();
910 
911 	PROC_LOCK(curproc);
912 	if ((curproc->p_sflag & PS_INMEM) && curproc->p_stats) {
913 		if (hardfault) {
914 			curproc->p_stats->p_ru.ru_majflt++;
915 		} else {
916 			curproc->p_stats->p_ru.ru_minflt++;
917 		}
918 	}
919 	PROC_UNLOCK(curproc);
920 
921 	/*
922 	 * Unlock everything, and return
923 	 */
924 	vm_object_deallocate(fs.first_object);
925 	mtx_unlock(&Giant);
926 	return (KERN_SUCCESS);
927 }
928 
929 /*
930  *	vm_fault_quick:
931  *
932  *	Ensure that the requested virtual address, which may be in userland,
933  *	is valid.  Fault-in the page if necessary.  Return -1 on failure.
934  */
935 int
936 vm_fault_quick(caddr_t v, int prot)
937 {
938 	int r;
939 
940 	if (prot & VM_PROT_WRITE)
941 		r = subyte(v, fubyte(v));
942 	else
943 		r = fubyte(v);
944 	return(r);
945 }
946 
947 /*
948  *	vm_fault_wire:
949  *
950  *	Wire down a range of virtual addresses in a map.
951  */
952 int
953 vm_fault_wire(map, start, end, user_wire)
954 	vm_map_t map;
955 	vm_offset_t start, end;
956 	boolean_t user_wire;
957 {
958 	vm_offset_t va;
959 	int rv;
960 
961 	/*
962 	 * We simulate a fault to get the page and enter it in the physical
963 	 * map.  For user wiring, we only ask for read access on currently
964 	 * read-only sections.
965 	 */
966 	for (va = start; va < end; va += PAGE_SIZE) {
967 		rv = vm_fault(map, va,
968 		    user_wire ? VM_PROT_READ : VM_PROT_READ | VM_PROT_WRITE,
969 		    user_wire ? VM_FAULT_USER_WIRE : VM_FAULT_CHANGE_WIRING);
970 		if (rv) {
971 			if (va != start)
972 				vm_fault_unwire(map, start, va);
973 			return (rv);
974 		}
975 	}
976 	return (KERN_SUCCESS);
977 }
978 
979 /*
980  *	vm_fault_unwire:
981  *
982  *	Unwire a range of virtual addresses in a map.
983  */
984 void
985 vm_fault_unwire(map, start, end)
986 	vm_map_t map;
987 	vm_offset_t start, end;
988 {
989 	vm_paddr_t pa;
990 	vm_offset_t va;
991 	pmap_t pmap;
992 
993 	pmap = vm_map_pmap(map);
994 
995 	mtx_lock(&Giant);
996 	/*
997 	 * Since the pages are wired down, we must be able to get their
998 	 * mappings from the physical map system.
999 	 */
1000 	for (va = start; va < end; va += PAGE_SIZE) {
1001 		pa = pmap_extract(pmap, va);
1002 		if (pa != 0) {
1003 			pmap_change_wiring(pmap, va, FALSE);
1004 			vm_page_lock_queues();
1005 			vm_page_unwire(PHYS_TO_VM_PAGE(pa), 1);
1006 			vm_page_unlock_queues();
1007 		}
1008 	}
1009 	mtx_unlock(&Giant);
1010 }
1011 
1012 /*
1013  *	Routine:
1014  *		vm_fault_copy_entry
1015  *	Function:
1016  *		Copy all of the pages from a wired-down map entry to another.
1017  *
1018  *	In/out conditions:
1019  *		The source and destination maps must be locked for write.
1020  *		The source map entry must be wired down (or be a sharing map
1021  *		entry corresponding to a main map entry that is wired down).
1022  */
1023 void
1024 vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry)
1025 	vm_map_t dst_map;
1026 	vm_map_t src_map;
1027 	vm_map_entry_t dst_entry;
1028 	vm_map_entry_t src_entry;
1029 {
1030 	vm_object_t dst_object;
1031 	vm_object_t src_object;
1032 	vm_ooffset_t dst_offset;
1033 	vm_ooffset_t src_offset;
1034 	vm_prot_t prot;
1035 	vm_offset_t vaddr;
1036 	vm_page_t dst_m;
1037 	vm_page_t src_m;
1038 
1039 #ifdef	lint
1040 	src_map++;
1041 #endif	/* lint */
1042 
1043 	src_object = src_entry->object.vm_object;
1044 	src_offset = src_entry->offset;
1045 
1046 	/*
1047 	 * Create the top-level object for the destination entry. (Doesn't
1048 	 * actually shadow anything - we copy the pages directly.)
1049 	 */
1050 	dst_object = vm_object_allocate(OBJT_DEFAULT,
1051 	    (vm_size_t) OFF_TO_IDX(dst_entry->end - dst_entry->start));
1052 
1053 	dst_entry->object.vm_object = dst_object;
1054 	dst_entry->offset = 0;
1055 
1056 	prot = dst_entry->max_protection;
1057 
1058 	/*
1059 	 * Loop through all of the pages in the entry's range, copying each
1060 	 * one from the source object (it should be there) to the destination
1061 	 * object.
1062 	 */
1063 	for (vaddr = dst_entry->start, dst_offset = 0;
1064 	    vaddr < dst_entry->end;
1065 	    vaddr += PAGE_SIZE, dst_offset += PAGE_SIZE) {
1066 
1067 		/*
1068 		 * Allocate a page in the destination object
1069 		 */
1070 		do {
1071 			dst_m = vm_page_alloc(dst_object,
1072 				OFF_TO_IDX(dst_offset), VM_ALLOC_NORMAL);
1073 			if (dst_m == NULL) {
1074 				VM_WAIT;
1075 			}
1076 		} while (dst_m == NULL);
1077 
1078 		/*
1079 		 * Find the page in the source object, and copy it in.
1080 		 * (Because the source is wired down, the page will be in
1081 		 * memory.)
1082 		 */
1083 		VM_OBJECT_LOCK(src_object);
1084 		src_m = vm_page_lookup(src_object,
1085 			OFF_TO_IDX(dst_offset + src_offset));
1086 		VM_OBJECT_UNLOCK(src_object);
1087 		if (src_m == NULL)
1088 			panic("vm_fault_copy_wired: page missing");
1089 
1090 		vm_page_copy(src_m, dst_m);
1091 
1092 		/*
1093 		 * Enter it in the pmap...
1094 		 */
1095 		pmap_enter(dst_map->pmap, vaddr, dst_m, prot, FALSE);
1096 		vm_page_lock_queues();
1097 		vm_page_flag_set(dst_m, PG_WRITEABLE);
1098 
1099 		/*
1100 		 * Mark it no longer busy, and put it on the active list.
1101 		 */
1102 		vm_page_activate(dst_m);
1103 		vm_page_wakeup(dst_m);
1104 		vm_page_unlock_queues();
1105 	}
1106 }
1107 
1108 
1109 /*
1110  * This routine checks around the requested page for other pages that
1111  * might be able to be faulted in.  This routine brackets the viable
1112  * pages for the pages to be paged in.
1113  *
1114  * Inputs:
1115  *	m, rbehind, rahead
1116  *
1117  * Outputs:
1118  *  marray (array of vm_page_t), reqpage (index of requested page)
1119  *
1120  * Return value:
1121  *  number of pages in marray
1122  *
1123  * This routine can't block.
1124  */
1125 static int
1126 vm_fault_additional_pages(m, rbehind, rahead, marray, reqpage)
1127 	vm_page_t m;
1128 	int rbehind;
1129 	int rahead;
1130 	vm_page_t *marray;
1131 	int *reqpage;
1132 {
1133 	int i,j;
1134 	vm_object_t object;
1135 	vm_pindex_t pindex, startpindex, endpindex, tpindex;
1136 	vm_page_t rtm;
1137 	int cbehind, cahead;
1138 
1139 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1140 
1141 	object = m->object;
1142 	pindex = m->pindex;
1143 
1144 	/*
1145 	 * we don't fault-ahead for device pager
1146 	 */
1147 	if (object->type == OBJT_DEVICE) {
1148 		*reqpage = 0;
1149 		marray[0] = m;
1150 		return 1;
1151 	}
1152 
1153 	/*
1154 	 * if the requested page is not available, then give up now
1155 	 */
1156 	if (!vm_pager_has_page(object, pindex, &cbehind, &cahead)) {
1157 		return 0;
1158 	}
1159 
1160 	if ((cbehind == 0) && (cahead == 0)) {
1161 		*reqpage = 0;
1162 		marray[0] = m;
1163 		return 1;
1164 	}
1165 
1166 	if (rahead > cahead) {
1167 		rahead = cahead;
1168 	}
1169 
1170 	if (rbehind > cbehind) {
1171 		rbehind = cbehind;
1172 	}
1173 
1174 	/*
1175 	 * try to do any readahead that we might have free pages for.
1176 	 */
1177 	if ((rahead + rbehind) >
1178 		((cnt.v_free_count + cnt.v_cache_count) - cnt.v_free_reserved)) {
1179 		pagedaemon_wakeup();
1180 		marray[0] = m;
1181 		*reqpage = 0;
1182 		return 1;
1183 	}
1184 
1185 	/*
1186 	 * scan backward for the read behind pages -- in memory
1187 	 */
1188 	if (pindex > 0) {
1189 		if (rbehind > pindex) {
1190 			rbehind = pindex;
1191 			startpindex = 0;
1192 		} else {
1193 			startpindex = pindex - rbehind;
1194 		}
1195 
1196 		for (tpindex = pindex - 1; tpindex >= startpindex; tpindex -= 1) {
1197 			if (vm_page_lookup(object, tpindex)) {
1198 				startpindex = tpindex + 1;
1199 				break;
1200 			}
1201 			if (tpindex == 0)
1202 				break;
1203 		}
1204 
1205 		for (i = 0, tpindex = startpindex; tpindex < pindex; i++, tpindex++) {
1206 
1207 			rtm = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL);
1208 			if (rtm == NULL) {
1209 				vm_page_lock_queues();
1210 				for (j = 0; j < i; j++) {
1211 					vm_page_free(marray[j]);
1212 				}
1213 				vm_page_unlock_queues();
1214 				marray[0] = m;
1215 				*reqpage = 0;
1216 				return 1;
1217 			}
1218 
1219 			marray[i] = rtm;
1220 		}
1221 	} else {
1222 		startpindex = 0;
1223 		i = 0;
1224 	}
1225 
1226 	marray[i] = m;
1227 	/* page offset of the required page */
1228 	*reqpage = i;
1229 
1230 	tpindex = pindex + 1;
1231 	i++;
1232 
1233 	/*
1234 	 * scan forward for the read ahead pages
1235 	 */
1236 	endpindex = tpindex + rahead;
1237 	if (endpindex > object->size)
1238 		endpindex = object->size;
1239 
1240 	for (; tpindex < endpindex; i++, tpindex++) {
1241 
1242 		if (vm_page_lookup(object, tpindex)) {
1243 			break;
1244 		}
1245 
1246 		rtm = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL);
1247 		if (rtm == NULL) {
1248 			break;
1249 		}
1250 
1251 		marray[i] = rtm;
1252 	}
1253 
1254 	/* return number of bytes of pages */
1255 	return i;
1256 }
1257