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