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