xref: /freebsd/sys/vm/vm_fault.c (revision 7660b554bc59a07be0431c17e0e33815818baa69)
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 	VM_OBJECT_LOCK(fs.first_object);
286 	fs.vp = vnode_pager_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 			is_first_object_locked = FALSE;
450 			if ((behavior == MAP_ENTRY_BEHAV_SEQUENTIAL ||
451 			     (behavior != MAP_ENTRY_BEHAV_RANDOM &&
452 			      fs.pindex >= fs.entry->lastr &&
453 			      fs.pindex < fs.entry->lastr + VM_FAULT_READ)) &&
454 			    (fs.first_object == fs.object ||
455 			     (is_first_object_locked = VM_OBJECT_TRYLOCK(fs.first_object))) &&
456 			    fs.first_object->type != OBJT_DEVICE) {
457 				vm_pindex_t firstpindex, tmppindex;
458 
459 				if (fs.first_pindex < 2 * VM_FAULT_READ)
460 					firstpindex = 0;
461 				else
462 					firstpindex = fs.first_pindex - 2 * VM_FAULT_READ;
463 
464 				vm_page_lock_queues();
465 				/*
466 				 * note: partially valid pages cannot be
467 				 * included in the lookahead - NFS piecemeal
468 				 * writes will barf on it badly.
469 				 */
470 				for (tmppindex = fs.first_pindex - 1;
471 					tmppindex >= firstpindex;
472 					--tmppindex) {
473 					vm_page_t mt;
474 
475 					mt = vm_page_lookup(fs.first_object, tmppindex);
476 					if (mt == NULL || (mt->valid != VM_PAGE_BITS_ALL))
477 						break;
478 					if (mt->busy ||
479 						(mt->flags & (PG_BUSY | PG_FICTITIOUS | PG_UNMANAGED)) ||
480 						mt->hold_count ||
481 						mt->wire_count)
482 						continue;
483 					if (mt->dirty == 0)
484 						vm_page_test_dirty(mt);
485 					if (mt->dirty) {
486 						pmap_remove_all(mt);
487 						vm_page_deactivate(mt);
488 					} else {
489 						vm_page_cache(mt);
490 					}
491 				}
492 				vm_page_unlock_queues();
493 				ahead += behind;
494 				behind = 0;
495 			}
496 			if (is_first_object_locked)
497 				VM_OBJECT_UNLOCK(fs.first_object);
498 			/*
499 			 * now we find out if any other pages should be paged
500 			 * in at this time this routine checks to see if the
501 			 * pages surrounding this fault reside in the same
502 			 * object as the page for this fault.  If they do,
503 			 * then they are faulted in also into the object.  The
504 			 * array "marray" returned contains an array of
505 			 * vm_page_t structs where one of them is the
506 			 * vm_page_t passed to the routine.  The reqpage
507 			 * return value is the index into the marray for the
508 			 * vm_page_t passed to the routine.
509 			 *
510 			 * fs.m plus the additional pages are PG_BUSY'd.
511 			 *
512 			 * XXX vm_fault_additional_pages() can block
513 			 * without releasing the map lock.
514 			 */
515 			faultcount = vm_fault_additional_pages(
516 			    fs.m, behind, ahead, marray, &reqpage);
517 
518 			/*
519 			 * update lastr imperfectly (we do not know how much
520 			 * getpages will actually read), but good enough.
521 			 *
522 			 * XXX The following assignment modifies the map
523 			 * without holding a write lock on it.
524 			 */
525 			fs.entry->lastr = fs.pindex + faultcount - behind;
526 
527 			/*
528 			 * Call the pager to retrieve the data, if any, after
529 			 * releasing the lock on the map.  We hold a ref on
530 			 * fs.object and the pages are PG_BUSY'd.
531 			 */
532 			unlock_map(&fs);
533 
534 			rv = faultcount ?
535 			    vm_pager_get_pages(fs.object, marray, faultcount,
536 				reqpage) : VM_PAGER_FAIL;
537 
538 			if (rv == VM_PAGER_OK) {
539 				/*
540 				 * Found the page. Leave it busy while we play
541 				 * with it.
542 				 */
543 
544 				/*
545 				 * Relookup in case pager changed page. Pager
546 				 * is responsible for disposition of old page
547 				 * if moved.
548 				 */
549 				fs.m = vm_page_lookup(fs.object, fs.pindex);
550 				if (!fs.m) {
551 					unlock_and_deallocate(&fs);
552 					goto RetryFault;
553 				}
554 
555 				hardfault++;
556 				break; /* break to PAGE HAS BEEN FOUND */
557 			}
558 			/*
559 			 * Remove the bogus page (which does not exist at this
560 			 * object/offset); before doing so, we must get back
561 			 * our object lock to preserve our invariant.
562 			 *
563 			 * Also wake up any other process that may want to bring
564 			 * in this page.
565 			 *
566 			 * If this is the top-level object, we must leave the
567 			 * busy page to prevent another process from rushing
568 			 * past us, and inserting the page in that object at
569 			 * the same time that we are.
570 			 */
571 			if (rv == VM_PAGER_ERROR)
572 				printf("vm_fault: pager read error, pid %d (%s)\n",
573 				    curproc->p_pid, curproc->p_comm);
574 			/*
575 			 * Data outside the range of the pager or an I/O error
576 			 */
577 			/*
578 			 * XXX - the check for kernel_map is a kludge to work
579 			 * around having the machine panic on a kernel space
580 			 * fault w/ I/O error.
581 			 */
582 			if (((fs.map != kernel_map) && (rv == VM_PAGER_ERROR)) ||
583 				(rv == VM_PAGER_BAD)) {
584 				vm_page_lock_queues();
585 				vm_page_free(fs.m);
586 				vm_page_unlock_queues();
587 				fs.m = NULL;
588 				unlock_and_deallocate(&fs);
589 				mtx_unlock(&Giant);
590 				return ((rv == VM_PAGER_ERROR) ? KERN_FAILURE : KERN_PROTECTION_FAILURE);
591 			}
592 			if (fs.object != fs.first_object) {
593 				vm_page_lock_queues();
594 				vm_page_free(fs.m);
595 				vm_page_unlock_queues();
596 				fs.m = NULL;
597 				/*
598 				 * XXX - we cannot just fall out at this
599 				 * point, m has been freed and is invalid!
600 				 */
601 			}
602 		}
603 
604 		/*
605 		 * We get here if the object has default pager (or unwiring)
606 		 * or the pager doesn't have the page.
607 		 */
608 		if (fs.object == fs.first_object)
609 			fs.first_m = fs.m;
610 
611 		/*
612 		 * Move on to the next object.  Lock the next object before
613 		 * unlocking the current one.
614 		 */
615 		fs.pindex += OFF_TO_IDX(fs.object->backing_object_offset);
616 		next_object = fs.object->backing_object;
617 		if (next_object == NULL) {
618 			/*
619 			 * If there's no object left, fill the page in the top
620 			 * object with zeros.
621 			 */
622 			if (fs.object != fs.first_object) {
623 				vm_object_pip_wakeup(fs.object);
624 				VM_OBJECT_UNLOCK(fs.object);
625 
626 				fs.object = fs.first_object;
627 				fs.pindex = fs.first_pindex;
628 				fs.m = fs.first_m;
629 				VM_OBJECT_LOCK(fs.object);
630 			}
631 			fs.first_m = NULL;
632 
633 			/*
634 			 * Zero the page if necessary and mark it valid.
635 			 */
636 			if ((fs.m->flags & PG_ZERO) == 0) {
637 				pmap_zero_page(fs.m);
638 			} else {
639 				cnt.v_ozfod++;
640 			}
641 			cnt.v_zfod++;
642 			fs.m->valid = VM_PAGE_BITS_ALL;
643 			break;	/* break to PAGE HAS BEEN FOUND */
644 		} else {
645 			KASSERT(fs.object != next_object,
646 			    ("object loop %p", next_object));
647 			VM_OBJECT_LOCK(next_object);
648 			vm_object_pip_add(next_object, 1);
649 			if (fs.object != fs.first_object)
650 				vm_object_pip_wakeup(fs.object);
651 			VM_OBJECT_UNLOCK(fs.object);
652 			fs.object = next_object;
653 		}
654 	}
655 
656 	KASSERT((fs.m->flags & PG_BUSY) != 0,
657 	    ("vm_fault: not busy after main loop"));
658 
659 	/*
660 	 * PAGE HAS BEEN FOUND. [Loop invariant still holds -- the object lock
661 	 * is held.]
662 	 */
663 
664 	/*
665 	 * If the page is being written, but isn't already owned by the
666 	 * top-level object, we have to copy it into a new page owned by the
667 	 * top-level object.
668 	 */
669 	if (fs.object != fs.first_object) {
670 		/*
671 		 * We only really need to copy if we want to write it.
672 		 */
673 		if (fault_type & VM_PROT_WRITE) {
674 			/*
675 			 * This allows pages to be virtually copied from a
676 			 * backing_object into the first_object, where the
677 			 * backing object has no other refs to it, and cannot
678 			 * gain any more refs.  Instead of a bcopy, we just
679 			 * move the page from the backing object to the
680 			 * first object.  Note that we must mark the page
681 			 * dirty in the first object so that it will go out
682 			 * to swap when needed.
683 			 */
684 			is_first_object_locked = FALSE;
685 			if (
686 				/*
687 				 * Only one shadow object
688 				 */
689 				(fs.object->shadow_count == 1) &&
690 				/*
691 				 * No COW refs, except us
692 				 */
693 				(fs.object->ref_count == 1) &&
694 				/*
695 				 * No one else can look this object up
696 				 */
697 				(fs.object->handle == NULL) &&
698 				/*
699 				 * No other ways to look the object up
700 				 */
701 				((fs.object->type == OBJT_DEFAULT) ||
702 				 (fs.object->type == OBJT_SWAP)) &&
703 			    (is_first_object_locked = VM_OBJECT_TRYLOCK(fs.first_object)) &&
704 				/*
705 				 * We don't chase down the shadow chain
706 				 */
707 			    fs.object == fs.first_object->backing_object) {
708 				vm_page_lock_queues();
709 				/*
710 				 * get rid of the unnecessary page
711 				 */
712 				pmap_remove_all(fs.first_m);
713 				vm_page_free(fs.first_m);
714 				/*
715 				 * grab the page and put it into the
716 				 * process'es object.  The page is
717 				 * automatically made dirty.
718 				 */
719 				vm_page_rename(fs.m, fs.first_object, fs.first_pindex);
720 				vm_page_busy(fs.m);
721 				vm_page_unlock_queues();
722 				fs.first_m = fs.m;
723 				fs.m = NULL;
724 				cnt.v_cow_optim++;
725 			} else {
726 				/*
727 				 * Oh, well, lets copy it.
728 				 */
729 				vm_page_copy(fs.m, fs.first_m);
730 			}
731 			if (fs.m) {
732 				/*
733 				 * We no longer need the old page or object.
734 				 */
735 				release_page(&fs);
736 			}
737 			/*
738 			 * fs.object != fs.first_object due to above
739 			 * conditional
740 			 */
741 			vm_object_pip_wakeup(fs.object);
742 			VM_OBJECT_UNLOCK(fs.object);
743 			/*
744 			 * Only use the new page below...
745 			 */
746 			fs.object = fs.first_object;
747 			fs.pindex = fs.first_pindex;
748 			fs.m = fs.first_m;
749 			if (!is_first_object_locked)
750 				VM_OBJECT_LOCK(fs.object);
751 			cnt.v_cow_faults++;
752 		} else {
753 			prot &= ~VM_PROT_WRITE;
754 		}
755 	}
756 
757 	/*
758 	 * We must verify that the maps have not changed since our last
759 	 * lookup.
760 	 */
761 	if (!fs.lookup_still_valid &&
762 		(fs.map->timestamp != map_generation)) {
763 		vm_object_t retry_object;
764 		vm_pindex_t retry_pindex;
765 		vm_prot_t retry_prot;
766 
767 		/*
768 		 * Since map entries may be pageable, make sure we can take a
769 		 * page fault on them.
770 		 */
771 
772 		/*
773 		 * Unlock vnode before the lookup to avoid deadlock.   E.G.
774 		 * avoid a deadlock between the inode and exec_map that can
775 		 * occur due to locks being obtained in different orders.
776 		 */
777 		if (fs.vp != NULL) {
778 			vput(fs.vp);
779 			fs.vp = NULL;
780 		}
781 
782 		if (fs.map->infork) {
783 			release_page(&fs);
784 			unlock_and_deallocate(&fs);
785 			goto RetryFault;
786 		}
787 		VM_OBJECT_UNLOCK(fs.object);
788 
789 		/*
790 		 * To avoid trying to write_lock the map while another process
791 		 * has it read_locked (in vm_map_pageable), we do not try for
792 		 * write permission.  If the page is still writable, we will
793 		 * get write permission.  If it is not, or has been marked
794 		 * needs_copy, we enter the mapping without write permission,
795 		 * and will merely take another fault.
796 		 */
797 		result = vm_map_lookup(&fs.map, vaddr, fault_type & ~VM_PROT_WRITE,
798 		    &fs.entry, &retry_object, &retry_pindex, &retry_prot, &wired);
799 		map_generation = fs.map->timestamp;
800 
801 		VM_OBJECT_LOCK(fs.object);
802 		/*
803 		 * If we don't need the page any longer, put it on the active
804 		 * list (the easiest thing to do here).  If no one needs it,
805 		 * pageout will grab it eventually.
806 		 */
807 		if (result != KERN_SUCCESS) {
808 			release_page(&fs);
809 			unlock_and_deallocate(&fs);
810 			mtx_unlock(&Giant);
811 			return (result);
812 		}
813 		fs.lookup_still_valid = TRUE;
814 
815 		if ((retry_object != fs.first_object) ||
816 		    (retry_pindex != fs.first_pindex)) {
817 			release_page(&fs);
818 			unlock_and_deallocate(&fs);
819 			goto RetryFault;
820 		}
821 		/*
822 		 * Check whether the protection has changed or the object has
823 		 * been copied while we left the map unlocked. Changing from
824 		 * read to write permission is OK - we leave the page
825 		 * write-protected, and catch the write fault. Changing from
826 		 * write to read permission means that we can't mark the page
827 		 * write-enabled after all.
828 		 */
829 		prot &= retry_prot;
830 	}
831 
832 	/*
833 	 * Put this page into the physical map. We had to do the unlock above
834 	 * because pmap_enter may cause other faults.   We don't put the page
835 	 * back on the active queue until later so that the page-out daemon
836 	 * won't find us (yet).
837 	 */
838 
839 	if (prot & VM_PROT_WRITE) {
840 		vm_page_lock_queues();
841 		vm_page_flag_set(fs.m, PG_WRITEABLE);
842 		vm_object_set_writeable_dirty(fs.m->object);
843 
844 		/*
845 		 * If the fault is a write, we know that this page is being
846 		 * written NOW so dirty it explicitly to save on
847 		 * pmap_is_modified() calls later.
848 		 *
849 		 * If this is a NOSYNC mmap we do not want to set PG_NOSYNC
850 		 * if the page is already dirty to prevent data written with
851 		 * the expectation of being synced from not being synced.
852 		 * Likewise if this entry does not request NOSYNC then make
853 		 * sure the page isn't marked NOSYNC.  Applications sharing
854 		 * data should use the same flags to avoid ping ponging.
855 		 *
856 		 * Also tell the backing pager, if any, that it should remove
857 		 * any swap backing since the page is now dirty.
858 		 */
859 		if (fs.entry->eflags & MAP_ENTRY_NOSYNC) {
860 			if (fs.m->dirty == 0)
861 				vm_page_flag_set(fs.m, PG_NOSYNC);
862 		} else {
863 			vm_page_flag_clear(fs.m, PG_NOSYNC);
864 		}
865 		vm_page_unlock_queues();
866 		if (fault_flags & VM_FAULT_DIRTY) {
867 			int s;
868 			vm_page_dirty(fs.m);
869 			s = splvm();
870 			vm_pager_page_unswapped(fs.m);
871 			splx(s);
872 		}
873 	}
874 
875 	/*
876 	 * Page had better still be busy
877 	 */
878 	KASSERT(fs.m->flags & PG_BUSY,
879 		("vm_fault: page %p not busy!", fs.m));
880 	unlock_things(&fs);
881 
882 	/*
883 	 * Sanity check: page must be completely valid or it is not fit to
884 	 * map into user space.  vm_pager_get_pages() ensures this.
885 	 */
886 	if (fs.m->valid != VM_PAGE_BITS_ALL) {
887 		vm_page_zero_invalid(fs.m, TRUE);
888 		printf("Warning: page %p partially invalid on fault\n", fs.m);
889 	}
890 	pmap_enter(fs.map->pmap, vaddr, fs.m, prot, wired);
891 	if (((fault_flags & VM_FAULT_WIRE_MASK) == 0) && (wired == 0)) {
892 		pmap_prefault(fs.map->pmap, vaddr, fs.entry);
893 	}
894 	vm_page_lock_queues();
895 	vm_page_flag_clear(fs.m, PG_ZERO);
896 	vm_page_flag_set(fs.m, PG_REFERENCED);
897 
898 	/*
899 	 * If the page is not wired down, then put it where the pageout daemon
900 	 * can find it.
901 	 */
902 	if (fault_flags & VM_FAULT_WIRE_MASK) {
903 		if (wired)
904 			vm_page_wire(fs.m);
905 		else
906 			vm_page_unwire(fs.m, 1);
907 	} else {
908 		vm_page_activate(fs.m);
909 	}
910 	vm_page_wakeup(fs.m);
911 	vm_page_unlock_queues();
912 
913 	PROC_LOCK(curproc);
914 	if ((curproc->p_sflag & PS_INMEM) && curproc->p_stats) {
915 		if (hardfault) {
916 			curproc->p_stats->p_ru.ru_majflt++;
917 		} else {
918 			curproc->p_stats->p_ru.ru_minflt++;
919 		}
920 	}
921 	PROC_UNLOCK(curproc);
922 
923 	/*
924 	 * Unlock everything, and return
925 	 */
926 	vm_object_deallocate(fs.first_object);
927 	mtx_unlock(&Giant);
928 	return (KERN_SUCCESS);
929 }
930 
931 /*
932  *	vm_fault_quick:
933  *
934  *	Ensure that the requested virtual address, which may be in userland,
935  *	is valid.  Fault-in the page if necessary.  Return -1 on failure.
936  */
937 int
938 vm_fault_quick(caddr_t v, int prot)
939 {
940 	int r;
941 
942 	if (prot & VM_PROT_WRITE)
943 		r = subyte(v, fubyte(v));
944 	else
945 		r = fubyte(v);
946 	return(r);
947 }
948 
949 /*
950  *	vm_fault_wire:
951  *
952  *	Wire down a range of virtual addresses in a map.
953  */
954 int
955 vm_fault_wire(map, start, end, user_wire)
956 	vm_map_t map;
957 	vm_offset_t start, end;
958 	boolean_t user_wire;
959 {
960 	vm_offset_t va;
961 	int rv;
962 
963 	/*
964 	 * We simulate a fault to get the page and enter it in the physical
965 	 * map.  For user wiring, we only ask for read access on currently
966 	 * read-only sections.
967 	 */
968 	for (va = start; va < end; va += PAGE_SIZE) {
969 		rv = vm_fault(map, va,
970 		    user_wire ? VM_PROT_READ : VM_PROT_READ | VM_PROT_WRITE,
971 		    user_wire ? VM_FAULT_USER_WIRE : VM_FAULT_CHANGE_WIRING);
972 		if (rv) {
973 			if (va != start)
974 				vm_fault_unwire(map, start, va);
975 			return (rv);
976 		}
977 	}
978 	return (KERN_SUCCESS);
979 }
980 
981 /*
982  *	vm_fault_unwire:
983  *
984  *	Unwire a range of virtual addresses in a map.
985  */
986 void
987 vm_fault_unwire(map, start, end)
988 	vm_map_t map;
989 	vm_offset_t start, end;
990 {
991 	vm_paddr_t pa;
992 	vm_offset_t va;
993 	pmap_t pmap;
994 
995 	pmap = vm_map_pmap(map);
996 
997 	mtx_lock(&Giant);
998 	/*
999 	 * Since the pages are wired down, we must be able to get their
1000 	 * mappings from the physical map system.
1001 	 */
1002 	for (va = start; va < end; va += PAGE_SIZE) {
1003 		pa = pmap_extract(pmap, va);
1004 		if (pa != 0) {
1005 			pmap_change_wiring(pmap, va, FALSE);
1006 			vm_page_lock_queues();
1007 			vm_page_unwire(PHYS_TO_VM_PAGE(pa), 1);
1008 			vm_page_unlock_queues();
1009 		}
1010 	}
1011 	mtx_unlock(&Giant);
1012 }
1013 
1014 /*
1015  *	Routine:
1016  *		vm_fault_copy_entry
1017  *	Function:
1018  *		Copy all of the pages from a wired-down map entry to another.
1019  *
1020  *	In/out conditions:
1021  *		The source and destination maps must be locked for write.
1022  *		The source map entry must be wired down (or be a sharing map
1023  *		entry corresponding to a main map entry that is wired down).
1024  */
1025 void
1026 vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry)
1027 	vm_map_t dst_map;
1028 	vm_map_t src_map;
1029 	vm_map_entry_t dst_entry;
1030 	vm_map_entry_t src_entry;
1031 {
1032 	vm_object_t dst_object;
1033 	vm_object_t src_object;
1034 	vm_ooffset_t dst_offset;
1035 	vm_ooffset_t src_offset;
1036 	vm_prot_t prot;
1037 	vm_offset_t vaddr;
1038 	vm_page_t dst_m;
1039 	vm_page_t src_m;
1040 
1041 #ifdef	lint
1042 	src_map++;
1043 #endif	/* lint */
1044 
1045 	src_object = src_entry->object.vm_object;
1046 	src_offset = src_entry->offset;
1047 
1048 	/*
1049 	 * Create the top-level object for the destination entry. (Doesn't
1050 	 * actually shadow anything - we copy the pages directly.)
1051 	 */
1052 	dst_object = vm_object_allocate(OBJT_DEFAULT,
1053 	    (vm_size_t) OFF_TO_IDX(dst_entry->end - dst_entry->start));
1054 
1055 	dst_entry->object.vm_object = dst_object;
1056 	dst_entry->offset = 0;
1057 
1058 	prot = dst_entry->max_protection;
1059 
1060 	/*
1061 	 * Loop through all of the pages in the entry's range, copying each
1062 	 * one from the source object (it should be there) to the destination
1063 	 * object.
1064 	 */
1065 	for (vaddr = dst_entry->start, dst_offset = 0;
1066 	    vaddr < dst_entry->end;
1067 	    vaddr += PAGE_SIZE, dst_offset += PAGE_SIZE) {
1068 
1069 		/*
1070 		 * Allocate a page in the destination object
1071 		 */
1072 		do {
1073 			dst_m = vm_page_alloc(dst_object,
1074 				OFF_TO_IDX(dst_offset), VM_ALLOC_NORMAL);
1075 			if (dst_m == NULL) {
1076 				VM_WAIT;
1077 			}
1078 		} while (dst_m == NULL);
1079 
1080 		/*
1081 		 * Find the page in the source object, and copy it in.
1082 		 * (Because the source is wired down, the page will be in
1083 		 * memory.)
1084 		 */
1085 		VM_OBJECT_LOCK(src_object);
1086 		src_m = vm_page_lookup(src_object,
1087 			OFF_TO_IDX(dst_offset + src_offset));
1088 		VM_OBJECT_UNLOCK(src_object);
1089 		if (src_m == NULL)
1090 			panic("vm_fault_copy_wired: page missing");
1091 
1092 		vm_page_copy(src_m, dst_m);
1093 
1094 		/*
1095 		 * Enter it in the pmap...
1096 		 */
1097 		pmap_enter(dst_map->pmap, vaddr, dst_m, prot, FALSE);
1098 		vm_page_lock_queues();
1099 		vm_page_flag_set(dst_m, PG_WRITEABLE);
1100 
1101 		/*
1102 		 * Mark it no longer busy, and put it on the active list.
1103 		 */
1104 		vm_page_activate(dst_m);
1105 		vm_page_wakeup(dst_m);
1106 		vm_page_unlock_queues();
1107 	}
1108 }
1109 
1110 
1111 /*
1112  * This routine checks around the requested page for other pages that
1113  * might be able to be faulted in.  This routine brackets the viable
1114  * pages for the pages to be paged in.
1115  *
1116  * Inputs:
1117  *	m, rbehind, rahead
1118  *
1119  * Outputs:
1120  *  marray (array of vm_page_t), reqpage (index of requested page)
1121  *
1122  * Return value:
1123  *  number of pages in marray
1124  *
1125  * This routine can't block.
1126  */
1127 static int
1128 vm_fault_additional_pages(m, rbehind, rahead, marray, reqpage)
1129 	vm_page_t m;
1130 	int rbehind;
1131 	int rahead;
1132 	vm_page_t *marray;
1133 	int *reqpage;
1134 {
1135 	int i,j;
1136 	vm_object_t object;
1137 	vm_pindex_t pindex, startpindex, endpindex, tpindex;
1138 	vm_page_t rtm;
1139 	int cbehind, cahead;
1140 
1141 	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1142 
1143 	object = m->object;
1144 	pindex = m->pindex;
1145 
1146 	/*
1147 	 * we don't fault-ahead for device pager
1148 	 */
1149 	if (object->type == OBJT_DEVICE) {
1150 		*reqpage = 0;
1151 		marray[0] = m;
1152 		return 1;
1153 	}
1154 
1155 	/*
1156 	 * if the requested page is not available, then give up now
1157 	 */
1158 	if (!vm_pager_has_page(object, pindex, &cbehind, &cahead)) {
1159 		return 0;
1160 	}
1161 
1162 	if ((cbehind == 0) && (cahead == 0)) {
1163 		*reqpage = 0;
1164 		marray[0] = m;
1165 		return 1;
1166 	}
1167 
1168 	if (rahead > cahead) {
1169 		rahead = cahead;
1170 	}
1171 
1172 	if (rbehind > cbehind) {
1173 		rbehind = cbehind;
1174 	}
1175 
1176 	/*
1177 	 * try to do any readahead that we might have free pages for.
1178 	 */
1179 	if ((rahead + rbehind) >
1180 		((cnt.v_free_count + cnt.v_cache_count) - cnt.v_free_reserved)) {
1181 		pagedaemon_wakeup();
1182 		marray[0] = m;
1183 		*reqpage = 0;
1184 		return 1;
1185 	}
1186 
1187 	/*
1188 	 * scan backward for the read behind pages -- in memory
1189 	 */
1190 	if (pindex > 0) {
1191 		if (rbehind > pindex) {
1192 			rbehind = pindex;
1193 			startpindex = 0;
1194 		} else {
1195 			startpindex = pindex - rbehind;
1196 		}
1197 
1198 		for (tpindex = pindex - 1; tpindex >= startpindex; tpindex -= 1) {
1199 			if (vm_page_lookup(object, tpindex)) {
1200 				startpindex = tpindex + 1;
1201 				break;
1202 			}
1203 			if (tpindex == 0)
1204 				break;
1205 		}
1206 
1207 		for (i = 0, tpindex = startpindex; tpindex < pindex; i++, tpindex++) {
1208 
1209 			rtm = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL);
1210 			if (rtm == NULL) {
1211 				vm_page_lock_queues();
1212 				for (j = 0; j < i; j++) {
1213 					vm_page_free(marray[j]);
1214 				}
1215 				vm_page_unlock_queues();
1216 				marray[0] = m;
1217 				*reqpage = 0;
1218 				return 1;
1219 			}
1220 
1221 			marray[i] = rtm;
1222 		}
1223 	} else {
1224 		startpindex = 0;
1225 		i = 0;
1226 	}
1227 
1228 	marray[i] = m;
1229 	/* page offset of the required page */
1230 	*reqpage = i;
1231 
1232 	tpindex = pindex + 1;
1233 	i++;
1234 
1235 	/*
1236 	 * scan forward for the read ahead pages
1237 	 */
1238 	endpindex = tpindex + rahead;
1239 	if (endpindex > object->size)
1240 		endpindex = object->size;
1241 
1242 	for (; tpindex < endpindex; i++, tpindex++) {
1243 
1244 		if (vm_page_lookup(object, tpindex)) {
1245 			break;
1246 		}
1247 
1248 		rtm = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL);
1249 		if (rtm == NULL) {
1250 			break;
1251 		}
1252 
1253 		marray[i] = rtm;
1254 	}
1255 
1256 	/* return number of bytes of pages */
1257 	return i;
1258 }
1259