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