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