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