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