xref: /dragonfly/sys/vm/vm_fault.c (revision f746689a)
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.47 2008/07/01 02:02:56 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 #include <sys/vkernel.h>
85 #include <sys/sfbuf.h>
86 #include <sys/lock.h>
87 #include <sys/sysctl.h>
88 
89 #include <vm/vm.h>
90 #include <vm/vm_param.h>
91 #include <vm/pmap.h>
92 #include <vm/vm_map.h>
93 #include <vm/vm_object.h>
94 #include <vm/vm_page.h>
95 #include <vm/vm_pageout.h>
96 #include <vm/vm_kern.h>
97 #include <vm/vm_pager.h>
98 #include <vm/vnode_pager.h>
99 #include <vm/vm_extern.h>
100 
101 #include <sys/thread2.h>
102 #include <vm/vm_page2.h>
103 
104 #define VM_FAULT_READ_AHEAD 8
105 #define VM_FAULT_READ_BEHIND 7
106 #define VM_FAULT_READ (VM_FAULT_READ_AHEAD+VM_FAULT_READ_BEHIND+1)
107 
108 struct faultstate {
109 	vm_page_t m;
110 	vm_object_t object;
111 	vm_pindex_t pindex;
112 	vm_prot_t prot;
113 	vm_page_t first_m;
114 	vm_object_t first_object;
115 	vm_prot_t first_prot;
116 	vm_map_t map;
117 	vm_map_entry_t entry;
118 	int lookup_still_valid;
119 	int didlimit;
120 	int hardfault;
121 	int fault_flags;
122 	int map_generation;
123 	boolean_t wired;
124 	struct vnode *vp;
125 };
126 
127 static int burst_fault = 1;
128 SYSCTL_INT(_vm, OID_AUTO, burst_fault, CTLFLAG_RW, &burst_fault, 0, "");
129 
130 static int vm_fault_object(struct faultstate *, vm_pindex_t, vm_prot_t);
131 static int vm_fault_vpagetable(struct faultstate *, vm_pindex_t *, vpte_t, int);
132 static int vm_fault_additional_pages (vm_page_t, int, int, vm_page_t *, int *);
133 static int vm_fault_ratelimit(struct vmspace *);
134 
135 static __inline void
136 release_page(struct faultstate *fs)
137 {
138 	vm_page_deactivate(fs->m);
139 	vm_page_wakeup(fs->m);
140 	fs->m = NULL;
141 }
142 
143 static __inline void
144 unlock_map(struct faultstate *fs)
145 {
146 	if (fs->lookup_still_valid && fs->map) {
147 		vm_map_lookup_done(fs->map, fs->entry, 0);
148 		fs->lookup_still_valid = FALSE;
149 	}
150 }
151 
152 /*
153  * Clean up after a successful call to vm_fault_object() so another call
154  * to vm_fault_object() can be made.
155  */
156 static void
157 _cleanup_successful_fault(struct faultstate *fs, int relock)
158 {
159 	if (fs->object != fs->first_object) {
160 		vm_page_free(fs->first_m);
161 		vm_object_pip_wakeup(fs->object);
162 		fs->first_m = NULL;
163 	}
164 	fs->object = fs->first_object;
165 	if (relock && fs->lookup_still_valid == FALSE) {
166 		if (fs->map)
167 			vm_map_lock_read(fs->map);
168 		fs->lookup_still_valid = TRUE;
169 	}
170 }
171 
172 static void
173 _unlock_things(struct faultstate *fs, int dealloc)
174 {
175 	vm_object_pip_wakeup(fs->first_object);
176 	_cleanup_successful_fault(fs, 0);
177 	if (dealloc) {
178 		vm_object_deallocate(fs->first_object);
179 		fs->first_object = NULL;
180 	}
181 	unlock_map(fs);
182 	if (fs->vp != NULL) {
183 		vput(fs->vp);
184 		fs->vp = NULL;
185 	}
186 }
187 
188 #define unlock_things(fs) _unlock_things(fs, 0)
189 #define unlock_and_deallocate(fs) _unlock_things(fs, 1)
190 #define cleanup_successful_fault(fs) _cleanup_successful_fault(fs, 1)
191 
192 /*
193  * TRYPAGER
194  *
195  * Determine if the pager for the current object *might* contain the page.
196  *
197  * We only need to try the pager if this is not a default object (default
198  * objects are zero-fill and have no real pager), and if we are not taking
199  * a wiring fault or if the FS entry is wired.
200  */
201 #define TRYPAGER(fs)	\
202 		(fs->object->type != OBJT_DEFAULT && \
203 		(((fs->fault_flags & VM_FAULT_WIRE_MASK) == 0) || fs->wired))
204 
205 /*
206  * vm_fault:
207  *
208  * Handle a page fault occuring at the given address, requiring the given
209  * permissions, in the map specified.  If successful, the page is inserted
210  * into the associated physical map.
211  *
212  * NOTE: The given address should be truncated to the proper page address.
213  *
214  * KERN_SUCCESS is returned if the page fault is handled; otherwise,
215  * a standard error specifying why the fault is fatal is returned.
216  *
217  * The map in question must be referenced, and remains so.
218  * The caller may hold no locks.
219  */
220 int
221 vm_fault(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type, int fault_flags)
222 {
223 	int result;
224 	vm_pindex_t first_pindex;
225 	struct faultstate fs;
226 
227 	mycpu->gd_cnt.v_vm_faults++;
228 
229 	fs.didlimit = 0;
230 	fs.hardfault = 0;
231 	fs.fault_flags = fault_flags;
232 
233 RetryFault:
234 	/*
235 	 * Find the vm_map_entry representing the backing store and resolve
236 	 * the top level object and page index.  This may have the side
237 	 * effect of executing a copy-on-write on the map entry and/or
238 	 * creating a shadow object, but will not COW any actual VM pages.
239 	 *
240 	 * On success fs.map is left read-locked and various other fields
241 	 * are initialized but not otherwise referenced or locked.
242 	 *
243 	 * NOTE!  vm_map_lookup will try to upgrade the fault_type to
244 	 * VM_FAULT_WRITE if the map entry is a virtual page table and also
245 	 * writable, so we can set the 'A'accessed bit in the virtual page
246 	 * table entry.
247 	 */
248 	fs.map = map;
249 	result = vm_map_lookup(&fs.map, vaddr, fault_type,
250 			       &fs.entry, &fs.first_object,
251 			       &first_pindex, &fs.first_prot, &fs.wired);
252 
253 	/*
254 	 * If the lookup failed or the map protections are incompatible,
255 	 * the fault generally fails.  However, if the caller is trying
256 	 * to do a user wiring we have more work to do.
257 	 */
258 	if (result != KERN_SUCCESS) {
259 		if (result != KERN_PROTECTION_FAILURE)
260 			return result;
261 		if ((fs.fault_flags & VM_FAULT_WIRE_MASK) != VM_FAULT_USER_WIRE)
262 			return result;
263 
264 		/*
265    		 * If we are user-wiring a r/w segment, and it is COW, then
266    		 * we need to do the COW operation.  Note that we don't
267 		 * currently COW RO sections now, because it is NOT desirable
268    		 * to COW .text.  We simply keep .text from ever being COW'ed
269    		 * and take the heat that one cannot debug wired .text sections.
270    		 */
271 		result = vm_map_lookup(&fs.map, vaddr,
272 				       VM_PROT_READ|VM_PROT_WRITE|
273 				        VM_PROT_OVERRIDE_WRITE,
274 				       &fs.entry, &fs.first_object,
275 				       &first_pindex, &fs.first_prot,
276 				       &fs.wired);
277 		if (result != KERN_SUCCESS)
278 			return result;
279 
280 		/*
281 		 * If we don't COW now, on a user wire, the user will never
282 		 * be able to write to the mapping.  If we don't make this
283 		 * restriction, the bookkeeping would be nearly impossible.
284 		 */
285 		if ((fs.entry->protection & VM_PROT_WRITE) == 0)
286 			fs.entry->max_protection &= ~VM_PROT_WRITE;
287 	}
288 
289 	/*
290 	 * fs.map is read-locked
291 	 *
292 	 * Misc checks.  Save the map generation number to detect races.
293 	 */
294 	fs.map_generation = fs.map->timestamp;
295 
296 	if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
297 		panic("vm_fault: fault on nofault entry, addr: %lx",
298 		    (u_long)vaddr);
299 	}
300 
301 	/*
302 	 * A system map entry may return a NULL object.  No object means
303 	 * no pager means an unrecoverable kernel fault.
304 	 */
305 	if (fs.first_object == NULL) {
306 		panic("vm_fault: unrecoverable fault at %p in entry %p",
307 			(void *)vaddr, fs.entry);
308 	}
309 
310 	/*
311 	 * Make a reference to this object to prevent its disposal while we
312 	 * are messing with it.  Once we have the reference, the map is free
313 	 * to be diddled.  Since objects reference their shadows (and copies),
314 	 * they will stay around as well.
315 	 *
316 	 * Bump the paging-in-progress count to prevent size changes (e.g.
317 	 * truncation operations) during I/O.  This must be done after
318 	 * obtaining the vnode lock in order to avoid possible deadlocks.
319 	 */
320 	vm_object_reference(fs.first_object);
321 	fs.vp = vnode_pager_lock(fs.first_object);
322 	vm_object_pip_add(fs.first_object, 1);
323 
324 	fs.lookup_still_valid = TRUE;
325 	fs.first_m = NULL;
326 	fs.object = fs.first_object;	/* so unlock_and_deallocate works */
327 
328 	/*
329 	 * If the entry is wired we cannot change the page protection.
330 	 */
331 	if (fs.wired)
332 		fault_type = fs.first_prot;
333 
334 	/*
335 	 * The page we want is at (first_object, first_pindex), but if the
336 	 * vm_map_entry is VM_MAPTYPE_VPAGETABLE we have to traverse the
337 	 * page table to figure out the actual pindex.
338 	 *
339 	 * NOTE!  DEVELOPMENT IN PROGRESS, THIS IS AN INITIAL IMPLEMENTATION
340 	 * ONLY
341 	 */
342 	if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
343 		result = vm_fault_vpagetable(&fs, &first_pindex,
344 					     fs.entry->aux.master_pde,
345 					     fault_type);
346 		if (result == KERN_TRY_AGAIN)
347 			goto RetryFault;
348 		if (result != KERN_SUCCESS)
349 			return (result);
350 	}
351 
352 	/*
353 	 * Now we have the actual (object, pindex), fault in the page.  If
354 	 * vm_fault_object() fails it will unlock and deallocate the FS
355 	 * data.   If it succeeds everything remains locked and fs->object
356 	 * will have an additinal PIP count if it is not equal to
357 	 * fs->first_object
358 	 *
359 	 * vm_fault_object will set fs->prot for the pmap operation.  It is
360 	 * allowed to set VM_PROT_WRITE if fault_type == VM_PROT_READ if the
361 	 * page can be safely written.  However, it will force a read-only
362 	 * mapping for a read fault if the memory is managed by a virtual
363 	 * page table.
364 	 */
365 	result = vm_fault_object(&fs, first_pindex, fault_type);
366 
367 	if (result == KERN_TRY_AGAIN)
368 		goto RetryFault;
369 	if (result != KERN_SUCCESS)
370 		return (result);
371 
372 	/*
373 	 * On success vm_fault_object() does not unlock or deallocate, and fs.m
374 	 * will contain a busied page.
375 	 *
376 	 * Enter the page into the pmap and do pmap-related adjustments.
377 	 */
378 	unlock_things(&fs);
379 	pmap_enter(fs.map->pmap, vaddr, fs.m, fs.prot, fs.wired);
380 
381 	if (((fs.fault_flags & VM_FAULT_WIRE_MASK) == 0) && (fs.wired == 0)) {
382 		pmap_prefault(fs.map->pmap, vaddr, fs.entry);
383 	}
384 
385 	vm_page_flag_clear(fs.m, PG_ZERO);
386 	vm_page_flag_set(fs.m, PG_REFERENCED);
387 
388 	/*
389 	 * If the page is not wired down, then put it where the pageout daemon
390 	 * can find it.
391 	 */
392 	if (fs.fault_flags & VM_FAULT_WIRE_MASK) {
393 		if (fs.wired)
394 			vm_page_wire(fs.m);
395 		else
396 			vm_page_unwire(fs.m, 1);
397 	} else {
398 		vm_page_activate(fs.m);
399 	}
400 
401 	if (curthread->td_lwp) {
402 		if (fs.hardfault) {
403 			curthread->td_lwp->lwp_ru.ru_majflt++;
404 		} else {
405 			curthread->td_lwp->lwp_ru.ru_minflt++;
406 		}
407 	}
408 
409 	/*
410 	 * Unlock everything, and return
411 	 */
412 	vm_page_wakeup(fs.m);
413 	vm_object_deallocate(fs.first_object);
414 
415 	return (KERN_SUCCESS);
416 }
417 
418 /*
419  * Fault in the specified virtual address in the current process map,
420  * returning a held VM page or NULL.  See vm_fault_page() for more
421  * information.
422  */
423 vm_page_t
424 vm_fault_page_quick(vm_offset_t va, vm_prot_t fault_type, int *errorp)
425 {
426 	struct lwp *lp = curthread->td_lwp;
427 	vm_page_t m;
428 
429 	m = vm_fault_page(&lp->lwp_vmspace->vm_map, va,
430 			  fault_type, VM_FAULT_NORMAL, errorp);
431 	return(m);
432 }
433 
434 /*
435  * Fault in the specified virtual address in the specified map, doing all
436  * necessary manipulation of the object store and all necessary I/O.  Return
437  * a held VM page or NULL, and set *errorp.  The related pmap is not
438  * updated.
439  *
440  * The returned page will be properly dirtied if VM_PROT_WRITE was specified,
441  * and marked PG_REFERENCED as well.
442  *
443  * If the page cannot be faulted writable and VM_PROT_WRITE was specified, an
444  * error will be returned.
445  */
446 vm_page_t
447 vm_fault_page(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
448 	      int fault_flags, int *errorp)
449 {
450 	vm_pindex_t first_pindex;
451 	struct faultstate fs;
452 	int result;
453 	vm_prot_t orig_fault_type = fault_type;
454 
455 	mycpu->gd_cnt.v_vm_faults++;
456 
457 	fs.didlimit = 0;
458 	fs.hardfault = 0;
459 	fs.fault_flags = fault_flags;
460 	KKASSERT((fault_flags & VM_FAULT_WIRE_MASK) == 0);
461 
462 RetryFault:
463 	/*
464 	 * Find the vm_map_entry representing the backing store and resolve
465 	 * the top level object and page index.  This may have the side
466 	 * effect of executing a copy-on-write on the map entry and/or
467 	 * creating a shadow object, but will not COW any actual VM pages.
468 	 *
469 	 * On success fs.map is left read-locked and various other fields
470 	 * are initialized but not otherwise referenced or locked.
471 	 *
472 	 * NOTE!  vm_map_lookup will upgrade the fault_type to VM_FAULT_WRITE
473 	 * if the map entry is a virtual page table and also writable,
474 	 * so we can set the 'A'accessed bit in the virtual page table entry.
475 	 */
476 	fs.map = map;
477 	result = vm_map_lookup(&fs.map, vaddr, fault_type,
478 			       &fs.entry, &fs.first_object,
479 			       &first_pindex, &fs.first_prot, &fs.wired);
480 
481 	if (result != KERN_SUCCESS) {
482 		*errorp = result;
483 		return (NULL);
484 	}
485 
486 	/*
487 	 * fs.map is read-locked
488 	 *
489 	 * Misc checks.  Save the map generation number to detect races.
490 	 */
491 	fs.map_generation = fs.map->timestamp;
492 
493 	if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
494 		panic("vm_fault: fault on nofault entry, addr: %lx",
495 		    (u_long)vaddr);
496 	}
497 
498 	/*
499 	 * A system map entry may return a NULL object.  No object means
500 	 * no pager means an unrecoverable kernel fault.
501 	 */
502 	if (fs.first_object == NULL) {
503 		panic("vm_fault: unrecoverable fault at %p in entry %p",
504 			(void *)vaddr, fs.entry);
505 	}
506 
507 	/*
508 	 * Make a reference to this object to prevent its disposal while we
509 	 * are messing with it.  Once we have the reference, the map is free
510 	 * to be diddled.  Since objects reference their shadows (and copies),
511 	 * they will stay around as well.
512 	 *
513 	 * Bump the paging-in-progress count to prevent size changes (e.g.
514 	 * truncation operations) during I/O.  This must be done after
515 	 * obtaining the vnode lock in order to avoid possible deadlocks.
516 	 */
517 	vm_object_reference(fs.first_object);
518 	fs.vp = vnode_pager_lock(fs.first_object);
519 	vm_object_pip_add(fs.first_object, 1);
520 
521 	fs.lookup_still_valid = TRUE;
522 	fs.first_m = NULL;
523 	fs.object = fs.first_object;	/* so unlock_and_deallocate works */
524 
525 	/*
526 	 * If the entry is wired we cannot change the page protection.
527 	 */
528 	if (fs.wired)
529 		fault_type = fs.first_prot;
530 
531 	/*
532 	 * The page we want is at (first_object, first_pindex), but if the
533 	 * vm_map_entry is VM_MAPTYPE_VPAGETABLE we have to traverse the
534 	 * page table to figure out the actual pindex.
535 	 *
536 	 * NOTE!  DEVELOPMENT IN PROGRESS, THIS IS AN INITIAL IMPLEMENTATION
537 	 * ONLY
538 	 */
539 	if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
540 		result = vm_fault_vpagetable(&fs, &first_pindex,
541 					     fs.entry->aux.master_pde,
542 					     fault_type);
543 		if (result == KERN_TRY_AGAIN)
544 			goto RetryFault;
545 		if (result != KERN_SUCCESS) {
546 			*errorp = result;
547 			return (NULL);
548 		}
549 	}
550 
551 	/*
552 	 * Now we have the actual (object, pindex), fault in the page.  If
553 	 * vm_fault_object() fails it will unlock and deallocate the FS
554 	 * data.   If it succeeds everything remains locked and fs->object
555 	 * will have an additinal PIP count if it is not equal to
556 	 * fs->first_object
557 	 */
558 	result = vm_fault_object(&fs, first_pindex, fault_type);
559 
560 	if (result == KERN_TRY_AGAIN)
561 		goto RetryFault;
562 	if (result != KERN_SUCCESS) {
563 		*errorp = result;
564 		return(NULL);
565 	}
566 
567 	if ((orig_fault_type & VM_PROT_WRITE) &&
568 	    (fs.prot & VM_PROT_WRITE) == 0) {
569 		*errorp = KERN_PROTECTION_FAILURE;
570 		unlock_and_deallocate(&fs);
571 		return(NULL);
572 	}
573 
574 	/*
575 	 * On success vm_fault_object() does not unlock or deallocate, and fs.m
576 	 * will contain a busied page.
577 	 */
578 	unlock_things(&fs);
579 
580 	/*
581 	 * Return a held page.  We are not doing any pmap manipulation so do
582 	 * not set PG_MAPPED.  However, adjust the page flags according to
583 	 * the fault type because the caller may not use a managed pmapping
584 	 * (so we don't want to lose the fact that the page will be dirtied
585 	 * if a write fault was specified).
586 	 */
587 	vm_page_hold(fs.m);
588 	vm_page_flag_clear(fs.m, PG_ZERO);
589 	if (fault_type & VM_PROT_WRITE)
590 		vm_page_dirty(fs.m);
591 
592 	/*
593 	 * Update the pmap.  We really only have to do this if a COW
594 	 * occured to replace the read-only page with the new page.  For
595 	 * now just do it unconditionally. XXX
596 	 */
597 	pmap_enter(fs.map->pmap, vaddr, fs.m, fs.prot, fs.wired);
598 	vm_page_flag_set(fs.m, PG_REFERENCED);
599 
600 	/*
601 	 * Unbusy the page by activating it.  It remains held and will not
602 	 * be reclaimed.
603 	 */
604 	vm_page_activate(fs.m);
605 
606 	if (curthread->td_lwp) {
607 		if (fs.hardfault) {
608 			curthread->td_lwp->lwp_ru.ru_majflt++;
609 		} else {
610 			curthread->td_lwp->lwp_ru.ru_minflt++;
611 		}
612 	}
613 
614 	/*
615 	 * Unlock everything, and return the held page.
616 	 */
617 	vm_page_wakeup(fs.m);
618 	vm_object_deallocate(fs.first_object);
619 
620 	*errorp = 0;
621 	return(fs.m);
622 }
623 
624 /*
625  * Fault in the specified (object,offset), dirty the returned page as
626  * needed.  If the requested fault_type cannot be done NULL and an
627  * error is returned.
628  */
629 vm_page_t
630 vm_fault_object_page(vm_object_t object, vm_ooffset_t offset,
631 		     vm_prot_t fault_type, int fault_flags, int *errorp)
632 {
633 	int result;
634 	vm_pindex_t first_pindex;
635 	struct faultstate fs;
636 	struct vm_map_entry entry;
637 
638 	bzero(&entry, sizeof(entry));
639 	entry.object.vm_object = object;
640 	entry.maptype = VM_MAPTYPE_NORMAL;
641 	entry.protection = entry.max_protection = fault_type;
642 
643 	fs.didlimit = 0;
644 	fs.hardfault = 0;
645 	fs.fault_flags = fault_flags;
646 	fs.map = NULL;
647 	KKASSERT((fault_flags & VM_FAULT_WIRE_MASK) == 0);
648 
649 RetryFault:
650 
651 	fs.first_object = object;
652 	first_pindex = OFF_TO_IDX(offset);
653 	fs.entry = &entry;
654 	fs.first_prot = fault_type;
655 	fs.wired = 0;
656 	/*fs.map_generation = 0; unused */
657 
658 	/*
659 	 * Make a reference to this object to prevent its disposal while we
660 	 * are messing with it.  Once we have the reference, the map is free
661 	 * to be diddled.  Since objects reference their shadows (and copies),
662 	 * they will stay around as well.
663 	 *
664 	 * Bump the paging-in-progress count to prevent size changes (e.g.
665 	 * truncation operations) during I/O.  This must be done after
666 	 * obtaining the vnode lock in order to avoid possible deadlocks.
667 	 */
668 	vm_object_reference(fs.first_object);
669 	fs.vp = vnode_pager_lock(fs.first_object);
670 	vm_object_pip_add(fs.first_object, 1);
671 
672 	fs.lookup_still_valid = TRUE;
673 	fs.first_m = NULL;
674 	fs.object = fs.first_object;	/* so unlock_and_deallocate works */
675 
676 #if 0
677 	/* XXX future - ability to operate on VM object using vpagetable */
678 	if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
679 		result = vm_fault_vpagetable(&fs, &first_pindex,
680 					     fs.entry->aux.master_pde,
681 					     fault_type);
682 		if (result == KERN_TRY_AGAIN)
683 			goto RetryFault;
684 		if (result != KERN_SUCCESS) {
685 			*errorp = result;
686 			return (NULL);
687 		}
688 	}
689 #endif
690 
691 	/*
692 	 * Now we have the actual (object, pindex), fault in the page.  If
693 	 * vm_fault_object() fails it will unlock and deallocate the FS
694 	 * data.   If it succeeds everything remains locked and fs->object
695 	 * will have an additinal PIP count if it is not equal to
696 	 * fs->first_object
697 	 */
698 	result = vm_fault_object(&fs, first_pindex, fault_type);
699 
700 	if (result == KERN_TRY_AGAIN)
701 		goto RetryFault;
702 	if (result != KERN_SUCCESS) {
703 		*errorp = result;
704 		return(NULL);
705 	}
706 
707 	if ((fault_type & VM_PROT_WRITE) && (fs.prot & VM_PROT_WRITE) == 0) {
708 		*errorp = KERN_PROTECTION_FAILURE;
709 		unlock_and_deallocate(&fs);
710 		return(NULL);
711 	}
712 
713 	/*
714 	 * On success vm_fault_object() does not unlock or deallocate, and fs.m
715 	 * will contain a busied page.
716 	 */
717 	unlock_things(&fs);
718 
719 	/*
720 	 * Return a held page.  We are not doing any pmap manipulation so do
721 	 * not set PG_MAPPED.  However, adjust the page flags according to
722 	 * the fault type because the caller may not use a managed pmapping
723 	 * (so we don't want to lose the fact that the page will be dirtied
724 	 * if a write fault was specified).
725 	 */
726 	vm_page_hold(fs.m);
727 	vm_page_flag_clear(fs.m, PG_ZERO);
728 	if (fault_type & VM_PROT_WRITE)
729 		vm_page_dirty(fs.m);
730 
731 	/*
732 	 * Indicate that the page was accessed.
733 	 */
734 	vm_page_flag_set(fs.m, PG_REFERENCED);
735 
736 	/*
737 	 * Unbusy the page by activating it.  It remains held and will not
738 	 * be reclaimed.
739 	 */
740 	vm_page_activate(fs.m);
741 
742 	if (curthread->td_lwp) {
743 		if (fs.hardfault) {
744 			mycpu->gd_cnt.v_vm_faults++;
745 			curthread->td_lwp->lwp_ru.ru_majflt++;
746 		} else {
747 			curthread->td_lwp->lwp_ru.ru_minflt++;
748 		}
749 	}
750 
751 	/*
752 	 * Unlock everything, and return the held page.
753 	 */
754 	vm_page_wakeup(fs.m);
755 	vm_object_deallocate(fs.first_object);
756 
757 	*errorp = 0;
758 	return(fs.m);
759 }
760 
761 /*
762  * Translate the virtual page number (first_pindex) that is relative
763  * to the address space into a logical page number that is relative to the
764  * backing object.  Use the virtual page table pointed to by (vpte).
765  *
766  * This implements an N-level page table.  Any level can terminate the
767  * scan by setting VPTE_PS.   A linear mapping is accomplished by setting
768  * VPTE_PS in the master page directory entry set via mcontrol(MADV_SETMAP).
769  */
770 static
771 int
772 vm_fault_vpagetable(struct faultstate *fs, vm_pindex_t *pindex,
773 		    vpte_t vpte, int fault_type)
774 {
775 	struct sf_buf *sf;
776 	int vshift = 32 - PAGE_SHIFT;	/* page index bits remaining */
777 	int result = KERN_SUCCESS;
778 	vpte_t *ptep;
779 
780 	for (;;) {
781 		/*
782 		 * We cannot proceed if the vpte is not valid, not readable
783 		 * for a read fault, or not writable for a write fault.
784 		 */
785 		if ((vpte & VPTE_V) == 0) {
786 			unlock_and_deallocate(fs);
787 			return (KERN_FAILURE);
788 		}
789 		if ((fault_type & VM_PROT_READ) && (vpte & VPTE_R) == 0) {
790 			unlock_and_deallocate(fs);
791 			return (KERN_FAILURE);
792 		}
793 		if ((fault_type & VM_PROT_WRITE) && (vpte & VPTE_W) == 0) {
794 			unlock_and_deallocate(fs);
795 			return (KERN_FAILURE);
796 		}
797 		if ((vpte & VPTE_PS) || vshift == 0)
798 			break;
799 		KKASSERT(vshift >= VPTE_PAGE_BITS);
800 
801 		/*
802 		 * Get the page table page.  Nominally we only read the page
803 		 * table, but since we are actively setting VPTE_M and VPTE_A,
804 		 * tell vm_fault_object() that we are writing it.
805 		 *
806 		 * There is currently no real need to optimize this.
807 		 */
808 		result = vm_fault_object(fs, vpte >> PAGE_SHIFT,
809 					 VM_PROT_READ|VM_PROT_WRITE);
810 		if (result != KERN_SUCCESS)
811 			return (result);
812 
813 		/*
814 		 * Process the returned fs.m and look up the page table
815 		 * entry in the page table page.
816 		 */
817 		vshift -= VPTE_PAGE_BITS;
818 		sf = sf_buf_alloc(fs->m, SFB_CPUPRIVATE);
819 		ptep = ((vpte_t *)sf_buf_kva(sf) +
820 		        ((*pindex >> vshift) & VPTE_PAGE_MASK));
821 		vpte = *ptep;
822 
823 		/*
824 		 * Page table write-back.  If the vpte is valid for the
825 		 * requested operation, do a write-back to the page table.
826 		 *
827 		 * XXX VPTE_M is not set properly for page directory pages.
828 		 * It doesn't get set in the page directory if the page table
829 		 * is modified during a read access.
830 		 */
831 		if ((fault_type & VM_PROT_WRITE) && (vpte & VPTE_V) &&
832 		    (vpte & VPTE_W)) {
833 			if ((vpte & (VPTE_M|VPTE_A)) != (VPTE_M|VPTE_A)) {
834 				atomic_set_int(ptep, VPTE_M|VPTE_A);
835 				vm_page_dirty(fs->m);
836 			}
837 		}
838 		if ((fault_type & VM_PROT_READ) && (vpte & VPTE_V) &&
839 		    (vpte & VPTE_R)) {
840 			if ((vpte & VPTE_A) == 0) {
841 				atomic_set_int(ptep, VPTE_A);
842 				vm_page_dirty(fs->m);
843 			}
844 		}
845 		sf_buf_free(sf);
846 		vm_page_flag_set(fs->m, PG_REFERENCED);
847 		vm_page_activate(fs->m);
848 		vm_page_wakeup(fs->m);
849 		cleanup_successful_fault(fs);
850 	}
851 	/*
852 	 * Combine remaining address bits with the vpte.
853 	 */
854 	*pindex = (vpte >> PAGE_SHIFT) +
855 		  (*pindex & ((1 << vshift) - 1));
856 	return (KERN_SUCCESS);
857 }
858 
859 
860 /*
861  * Do all operations required to fault-in (fs.first_object, pindex).  Run
862  * through the shadow chain as necessary and do required COW or virtual
863  * copy operations.  The caller has already fully resolved the vm_map_entry
864  * and, if appropriate, has created a copy-on-write layer.  All we need to
865  * do is iterate the object chain.
866  *
867  * On failure (fs) is unlocked and deallocated and the caller may return or
868  * retry depending on the failure code.  On success (fs) is NOT unlocked or
869  * deallocated, fs.m will contained a resolved, busied page, and fs.object
870  * will have an additional PIP count if it is not equal to fs.first_object.
871  */
872 static
873 int
874 vm_fault_object(struct faultstate *fs,
875 		vm_pindex_t first_pindex, vm_prot_t fault_type)
876 {
877 	vm_object_t next_object;
878 	vm_page_t marray[VM_FAULT_READ];
879 	vm_pindex_t pindex;
880 	int faultcount;
881 
882 	fs->prot = fs->first_prot;
883 	fs->object = fs->first_object;
884 	pindex = first_pindex;
885 
886 	/*
887 	 * If a read fault occurs we try to make the page writable if
888 	 * possible.  There are three cases where we cannot make the
889 	 * page mapping writable:
890 	 *
891 	 * (1) The mapping is read-only or the VM object is read-only,
892 	 *     fs->prot above will simply not have VM_PROT_WRITE set.
893 	 *
894 	 * (2) If the mapping is a virtual page table we need to be able
895 	 *     to detect writes so we can set VPTE_M in the virtual page
896 	 *     table.
897 	 *
898 	 * (3) If the VM page is read-only or copy-on-write, upgrading would
899 	 *     just result in an unnecessary COW fault.
900 	 *
901 	 * VM_PROT_VPAGED is set if faulting via a virtual page table and
902 	 * causes adjustments to the 'M'odify bit to also turn off write
903 	 * access to force a re-fault.
904 	 */
905 	if (fs->entry->maptype == VM_MAPTYPE_VPAGETABLE) {
906 		if ((fault_type & VM_PROT_WRITE) == 0)
907 			fs->prot &= ~VM_PROT_WRITE;
908 	}
909 
910 	for (;;) {
911 		/*
912 		 * If the object is dead, we stop here
913 		 */
914 		if (fs->object->flags & OBJ_DEAD) {
915 			unlock_and_deallocate(fs);
916 			return (KERN_PROTECTION_FAILURE);
917 		}
918 
919 		/*
920 		 * See if page is resident.  spl protection is required
921 		 * to avoid an interrupt unbusy/free race against our
922 		 * lookup.  We must hold the protection through a page
923 		 * allocation or busy.
924 		 */
925 		crit_enter();
926 		fs->m = vm_page_lookup(fs->object, pindex);
927 		if (fs->m != NULL) {
928 			int queue;
929 			/*
930 			 * Wait/Retry if the page is busy.  We have to do this
931 			 * if the page is busy via either PG_BUSY or
932 			 * vm_page_t->busy because the vm_pager may be using
933 			 * vm_page_t->busy for pageouts ( and even pageins if
934 			 * it is the vnode pager ), and we could end up trying
935 			 * to pagein and pageout the same page simultaneously.
936 			 *
937 			 * We can theoretically allow the busy case on a read
938 			 * fault if the page is marked valid, but since such
939 			 * pages are typically already pmap'd, putting that
940 			 * special case in might be more effort then it is
941 			 * worth.  We cannot under any circumstances mess
942 			 * around with a vm_page_t->busy page except, perhaps,
943 			 * to pmap it.
944 			 */
945 			if ((fs->m->flags & PG_BUSY) || fs->m->busy) {
946 				unlock_things(fs);
947 				vm_page_sleep_busy(fs->m, TRUE, "vmpfw");
948 				mycpu->gd_cnt.v_intrans++;
949 				vm_object_deallocate(fs->first_object);
950 				fs->first_object = NULL;
951 				crit_exit();
952 				return (KERN_TRY_AGAIN);
953 			}
954 
955 			/*
956 			 * If reactivating a page from PQ_CACHE we may have
957 			 * to rate-limit.
958 			 */
959 			queue = fs->m->queue;
960 			vm_page_unqueue_nowakeup(fs->m);
961 
962 			if ((queue - fs->m->pc) == PQ_CACHE &&
963 			    vm_page_count_severe()) {
964 				vm_page_activate(fs->m);
965 				unlock_and_deallocate(fs);
966 				vm_waitpfault();
967 				crit_exit();
968 				return (KERN_TRY_AGAIN);
969 			}
970 
971 			/*
972 			 * Mark page busy for other processes, and the
973 			 * pagedaemon.  If it still isn't completely valid
974 			 * (readable), jump to readrest, else we found the
975 			 * page and can return.
976 			 *
977 			 * We can release the spl once we have marked the
978 			 * page busy.
979 			 */
980 			vm_page_busy(fs->m);
981 			crit_exit();
982 
983 			if (((fs->m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) &&
984 			    fs->m->object != &kernel_object) {
985 				goto readrest;
986 			}
987 			break; /* break to PAGE HAS BEEN FOUND */
988 		}
989 
990 		/*
991 		 * Page is not resident, If this is the search termination
992 		 * or the pager might contain the page, allocate a new page.
993 		 *
994 		 * NOTE: We are still in a critical section.
995 		 */
996 		if (TRYPAGER(fs) || fs->object == fs->first_object) {
997 			/*
998 			 * If the page is beyond the object size we fail
999 			 */
1000 			if (pindex >= fs->object->size) {
1001 				crit_exit();
1002 				unlock_and_deallocate(fs);
1003 				return (KERN_PROTECTION_FAILURE);
1004 			}
1005 
1006 			/*
1007 			 * Ratelimit.
1008 			 */
1009 			if (fs->didlimit == 0 && curproc != NULL) {
1010 				int limticks;
1011 
1012 				limticks = vm_fault_ratelimit(curproc->p_vmspace);
1013 				if (limticks) {
1014 					crit_exit();
1015 					unlock_and_deallocate(fs);
1016 					tsleep(curproc, 0, "vmrate", limticks);
1017 					fs->didlimit = 1;
1018 					return (KERN_TRY_AGAIN);
1019 				}
1020 			}
1021 
1022 			/*
1023 			 * Allocate a new page for this object/offset pair.
1024 			 */
1025 			fs->m = NULL;
1026 			if (!vm_page_count_severe()) {
1027 				fs->m = vm_page_alloc(fs->object, pindex,
1028 				    (fs->vp || fs->object->backing_object) ? VM_ALLOC_NORMAL : VM_ALLOC_NORMAL | VM_ALLOC_ZERO);
1029 			}
1030 			if (fs->m == NULL) {
1031 				crit_exit();
1032 				unlock_and_deallocate(fs);
1033 				vm_waitpfault();
1034 				return (KERN_TRY_AGAIN);
1035 			}
1036 		}
1037 		crit_exit();
1038 
1039 readrest:
1040 		/*
1041 		 * We have found a valid page or we have allocated a new page.
1042 		 * The page thus may not be valid or may not be entirely
1043 		 * valid.
1044 		 *
1045 		 * Attempt to fault-in the page if there is a chance that the
1046 		 * pager has it, and potentially fault in additional pages
1047 		 * at the same time.
1048 		 *
1049 		 * We are NOT in splvm here and if TRYPAGER is true then
1050 		 * fs.m will be non-NULL and will be PG_BUSY for us.
1051 		 */
1052 
1053 		if (TRYPAGER(fs)) {
1054 			int rv;
1055 			int reqpage;
1056 			int ahead, behind;
1057 			u_char behavior = vm_map_entry_behavior(fs->entry);
1058 
1059 			if (behavior == MAP_ENTRY_BEHAV_RANDOM) {
1060 				ahead = 0;
1061 				behind = 0;
1062 			} else {
1063 				behind = pindex;
1064 				KKASSERT(behind >= 0);
1065 				if (behind > VM_FAULT_READ_BEHIND)
1066 					behind = VM_FAULT_READ_BEHIND;
1067 
1068 				ahead = fs->object->size - pindex;
1069 				if (ahead < 1)
1070 					ahead = 1;
1071 				if (ahead > VM_FAULT_READ_AHEAD)
1072 					ahead = VM_FAULT_READ_AHEAD;
1073 			}
1074 
1075 			if ((fs->first_object->type != OBJT_DEVICE) &&
1076 			    (behavior == MAP_ENTRY_BEHAV_SEQUENTIAL ||
1077                                 (behavior != MAP_ENTRY_BEHAV_RANDOM &&
1078                                 pindex >= fs->entry->lastr &&
1079                                 pindex < fs->entry->lastr + VM_FAULT_READ))
1080 			) {
1081 				vm_pindex_t firstpindex, tmppindex;
1082 
1083 				if (first_pindex < 2 * VM_FAULT_READ)
1084 					firstpindex = 0;
1085 				else
1086 					firstpindex = first_pindex - 2 * VM_FAULT_READ;
1087 
1088 				/*
1089 				 * note: partially valid pages cannot be
1090 				 * included in the lookahead - NFS piecemeal
1091 				 * writes will barf on it badly.
1092 				 *
1093 				 * spl protection is required to avoid races
1094 				 * between the lookup and an interrupt
1095 				 * unbusy/free sequence occuring prior to
1096 				 * our busy check.
1097 				 */
1098 				crit_enter();
1099 				for (tmppindex = first_pindex - 1;
1100 				    tmppindex >= firstpindex;
1101 				    --tmppindex
1102 				) {
1103 					vm_page_t mt;
1104 
1105 					mt = vm_page_lookup(fs->first_object, tmppindex);
1106 					if (mt == NULL || (mt->valid != VM_PAGE_BITS_ALL))
1107 						break;
1108 					if (mt->busy ||
1109 						(mt->flags & (PG_BUSY | PG_FICTITIOUS | PG_UNMANAGED)) ||
1110 						mt->hold_count ||
1111 						mt->wire_count)
1112 						continue;
1113 					if (mt->dirty == 0)
1114 						vm_page_test_dirty(mt);
1115 					if (mt->dirty) {
1116 						vm_page_busy(mt);
1117 						vm_page_protect(mt, VM_PROT_NONE);
1118 						vm_page_deactivate(mt);
1119 						vm_page_wakeup(mt);
1120 					} else {
1121 						vm_page_cache(mt);
1122 					}
1123 				}
1124 				crit_exit();
1125 
1126 				ahead += behind;
1127 				behind = 0;
1128 			}
1129 
1130 			/*
1131 			 * now we find out if any other pages should be paged
1132 			 * in at this time this routine checks to see if the
1133 			 * pages surrounding this fault reside in the same
1134 			 * object as the page for this fault.  If they do,
1135 			 * then they are faulted in also into the object.  The
1136 			 * array "marray" returned contains an array of
1137 			 * vm_page_t structs where one of them is the
1138 			 * vm_page_t passed to the routine.  The reqpage
1139 			 * return value is the index into the marray for the
1140 			 * vm_page_t passed to the routine.
1141 			 *
1142 			 * fs.m plus the additional pages are PG_BUSY'd.
1143 			 */
1144 			faultcount = vm_fault_additional_pages(
1145 			    fs->m, behind, ahead, marray, &reqpage);
1146 
1147 			/*
1148 			 * update lastr imperfectly (we do not know how much
1149 			 * getpages will actually read), but good enough.
1150 			 */
1151 			fs->entry->lastr = pindex + faultcount - behind;
1152 
1153 			/*
1154 			 * Call the pager to retrieve the data, if any, after
1155 			 * releasing the lock on the map.  We hold a ref on
1156 			 * fs.object and the pages are PG_BUSY'd.
1157 			 */
1158 			unlock_map(fs);
1159 
1160 			if (faultcount) {
1161 				rv = vm_pager_get_pages(fs->object, marray,
1162 							faultcount, reqpage);
1163 			} else {
1164 				rv = VM_PAGER_FAIL;
1165 			}
1166 
1167 			if (rv == VM_PAGER_OK) {
1168 				/*
1169 				 * Found the page. Leave it busy while we play
1170 				 * with it.
1171 				 */
1172 
1173 				/*
1174 				 * Relookup in case pager changed page. Pager
1175 				 * is responsible for disposition of old page
1176 				 * if moved.
1177 				 *
1178 				 * XXX other code segments do relookups too.
1179 				 * It's a bad abstraction that needs to be
1180 				 * fixed/removed.
1181 				 */
1182 				fs->m = vm_page_lookup(fs->object, pindex);
1183 				if (fs->m == NULL) {
1184 					unlock_and_deallocate(fs);
1185 					return (KERN_TRY_AGAIN);
1186 				}
1187 
1188 				++fs->hardfault;
1189 				break; /* break to PAGE HAS BEEN FOUND */
1190 			}
1191 
1192 			/*
1193 			 * Remove the bogus page (which does not exist at this
1194 			 * object/offset); before doing so, we must get back
1195 			 * our object lock to preserve our invariant.
1196 			 *
1197 			 * Also wake up any other process that may want to bring
1198 			 * in this page.
1199 			 *
1200 			 * If this is the top-level object, we must leave the
1201 			 * busy page to prevent another process from rushing
1202 			 * past us, and inserting the page in that object at
1203 			 * the same time that we are.
1204 			 */
1205 			if (rv == VM_PAGER_ERROR) {
1206 				if (curproc)
1207 					kprintf("vm_fault: pager read error, pid %d (%s)\n", curproc->p_pid, curproc->p_comm);
1208 				else
1209 					kprintf("vm_fault: pager read error, thread %p (%s)\n", curthread, curproc->p_comm);
1210 			}
1211 			/*
1212 			 * Data outside the range of the pager or an I/O error
1213 			 *
1214 			 * The page may have been wired during the pagein,
1215 			 * e.g. by the buffer cache, and cannot simply be
1216 			 * freed.  Call vnode_pager_freepag() to deal with it.
1217 			 */
1218 			/*
1219 			 * XXX - the check for kernel_map is a kludge to work
1220 			 * around having the machine panic on a kernel space
1221 			 * fault w/ I/O error.
1222 			 */
1223 			if (((fs->map != &kernel_map) && (rv == VM_PAGER_ERROR)) ||
1224 				(rv == VM_PAGER_BAD)) {
1225 				vnode_pager_freepage(fs->m);
1226 				fs->m = NULL;
1227 				unlock_and_deallocate(fs);
1228 				if (rv == VM_PAGER_ERROR)
1229 					return (KERN_FAILURE);
1230 				else
1231 					return (KERN_PROTECTION_FAILURE);
1232 				/* NOT REACHED */
1233 			}
1234 			if (fs->object != fs->first_object) {
1235 				vnode_pager_freepage(fs->m);
1236 				fs->m = NULL;
1237 				/*
1238 				 * XXX - we cannot just fall out at this
1239 				 * point, m has been freed and is invalid!
1240 				 */
1241 			}
1242 		}
1243 
1244 		/*
1245 		 * We get here if the object has a default pager (or unwiring)
1246 		 * or the pager doesn't have the page.
1247 		 */
1248 		if (fs->object == fs->first_object)
1249 			fs->first_m = fs->m;
1250 
1251 		/*
1252 		 * Move on to the next object.  Lock the next object before
1253 		 * unlocking the current one.
1254 		 */
1255 		pindex += OFF_TO_IDX(fs->object->backing_object_offset);
1256 		next_object = fs->object->backing_object;
1257 		if (next_object == NULL) {
1258 			/*
1259 			 * If there's no object left, fill the page in the top
1260 			 * object with zeros.
1261 			 */
1262 			if (fs->object != fs->first_object) {
1263 				vm_object_pip_wakeup(fs->object);
1264 
1265 				fs->object = fs->first_object;
1266 				pindex = first_pindex;
1267 				fs->m = fs->first_m;
1268 			}
1269 			fs->first_m = NULL;
1270 
1271 			/*
1272 			 * Zero the page if necessary and mark it valid.
1273 			 */
1274 			if ((fs->m->flags & PG_ZERO) == 0) {
1275 				vm_page_zero_fill(fs->m);
1276 			} else {
1277 				mycpu->gd_cnt.v_ozfod++;
1278 			}
1279 			mycpu->gd_cnt.v_zfod++;
1280 			fs->m->valid = VM_PAGE_BITS_ALL;
1281 			break;	/* break to PAGE HAS BEEN FOUND */
1282 		} else {
1283 			if (fs->object != fs->first_object) {
1284 				vm_object_pip_wakeup(fs->object);
1285 			}
1286 			KASSERT(fs->object != next_object, ("object loop %p", next_object));
1287 			fs->object = next_object;
1288 			vm_object_pip_add(fs->object, 1);
1289 		}
1290 	}
1291 
1292 	KASSERT((fs->m->flags & PG_BUSY) != 0,
1293 		("vm_fault: not busy after main loop"));
1294 
1295 	/*
1296 	 * PAGE HAS BEEN FOUND. [Loop invariant still holds -- the object lock
1297 	 * is held.]
1298 	 */
1299 
1300 	/*
1301 	 * If the page is being written, but isn't already owned by the
1302 	 * top-level object, we have to copy it into a new page owned by the
1303 	 * top-level object.
1304 	 */
1305 	if (fs->object != fs->first_object) {
1306 		/*
1307 		 * We only really need to copy if we want to write it.
1308 		 */
1309 		if (fault_type & VM_PROT_WRITE) {
1310 			/*
1311 			 * This allows pages to be virtually copied from a
1312 			 * backing_object into the first_object, where the
1313 			 * backing object has no other refs to it, and cannot
1314 			 * gain any more refs.  Instead of a bcopy, we just
1315 			 * move the page from the backing object to the
1316 			 * first object.  Note that we must mark the page
1317 			 * dirty in the first object so that it will go out
1318 			 * to swap when needed.
1319 			 */
1320 			if (
1321 				/*
1322 				 * Map, if present, has not changed
1323 				 */
1324 				(fs->map == NULL ||
1325 				fs->map_generation == fs->map->timestamp) &&
1326 				/*
1327 				 * Only one shadow object
1328 				 */
1329 				(fs->object->shadow_count == 1) &&
1330 				/*
1331 				 * No COW refs, except us
1332 				 */
1333 				(fs->object->ref_count == 1) &&
1334 				/*
1335 				 * No one else can look this object up
1336 				 */
1337 				(fs->object->handle == NULL) &&
1338 				/*
1339 				 * No other ways to look the object up
1340 				 */
1341 				((fs->object->type == OBJT_DEFAULT) ||
1342 				 (fs->object->type == OBJT_SWAP)) &&
1343 				/*
1344 				 * We don't chase down the shadow chain
1345 				 */
1346 				(fs->object == fs->first_object->backing_object) &&
1347 
1348 				/*
1349 				 * grab the lock if we need to
1350 				 */
1351 				(fs->lookup_still_valid ||
1352 				 fs->map == NULL ||
1353 				 lockmgr(&fs->map->lock, LK_EXCLUSIVE|LK_NOWAIT) == 0)
1354 			    ) {
1355 
1356 				fs->lookup_still_valid = 1;
1357 				/*
1358 				 * get rid of the unnecessary page
1359 				 */
1360 				vm_page_protect(fs->first_m, VM_PROT_NONE);
1361 				vm_page_free(fs->first_m);
1362 				fs->first_m = NULL;
1363 
1364 				/*
1365 				 * grab the page and put it into the
1366 				 * process'es object.  The page is
1367 				 * automatically made dirty.
1368 				 */
1369 				vm_page_rename(fs->m, fs->first_object, first_pindex);
1370 				fs->first_m = fs->m;
1371 				vm_page_busy(fs->first_m);
1372 				fs->m = NULL;
1373 				mycpu->gd_cnt.v_cow_optim++;
1374 			} else {
1375 				/*
1376 				 * Oh, well, lets copy it.
1377 				 */
1378 				vm_page_copy(fs->m, fs->first_m);
1379 				vm_page_event(fs->m, VMEVENT_COW);
1380 			}
1381 
1382 			if (fs->m) {
1383 				/*
1384 				 * We no longer need the old page or object.
1385 				 */
1386 				release_page(fs);
1387 			}
1388 
1389 			/*
1390 			 * fs->object != fs->first_object due to above
1391 			 * conditional
1392 			 */
1393 			vm_object_pip_wakeup(fs->object);
1394 
1395 			/*
1396 			 * Only use the new page below...
1397 			 */
1398 
1399 			mycpu->gd_cnt.v_cow_faults++;
1400 			fs->m = fs->first_m;
1401 			fs->object = fs->first_object;
1402 			pindex = first_pindex;
1403 		} else {
1404 			/*
1405 			 * If it wasn't a write fault avoid having to copy
1406 			 * the page by mapping it read-only.
1407 			 */
1408 			fs->prot &= ~VM_PROT_WRITE;
1409 		}
1410 	}
1411 
1412 	/*
1413 	 * We may have had to unlock a map to do I/O.  If we did then
1414 	 * lookup_still_valid will be FALSE.  If the map generation count
1415 	 * also changed then all sorts of things could have happened while
1416 	 * we were doing the I/O and we need to retry.
1417 	 */
1418 
1419 	if (!fs->lookup_still_valid &&
1420 	    fs->map != NULL &&
1421 	    (fs->map->timestamp != fs->map_generation)) {
1422 		release_page(fs);
1423 		unlock_and_deallocate(fs);
1424 		return (KERN_TRY_AGAIN);
1425 	}
1426 
1427 	/*
1428 	 * If the fault is a write, we know that this page is being
1429 	 * written NOW so dirty it explicitly to save on pmap_is_modified()
1430 	 * calls later.
1431 	 *
1432 	 * If this is a NOSYNC mmap we do not want to set PG_NOSYNC
1433 	 * if the page is already dirty to prevent data written with
1434 	 * the expectation of being synced from not being synced.
1435 	 * Likewise if this entry does not request NOSYNC then make
1436 	 * sure the page isn't marked NOSYNC.  Applications sharing
1437 	 * data should use the same flags to avoid ping ponging.
1438 	 *
1439 	 * Also tell the backing pager, if any, that it should remove
1440 	 * any swap backing since the page is now dirty.
1441 	 */
1442 	if (fs->prot & VM_PROT_WRITE) {
1443 		vm_object_set_writeable_dirty(fs->m->object);
1444 		if (fs->entry->eflags & MAP_ENTRY_NOSYNC) {
1445 			if (fs->m->dirty == 0)
1446 				vm_page_flag_set(fs->m, PG_NOSYNC);
1447 		} else {
1448 			vm_page_flag_clear(fs->m, PG_NOSYNC);
1449 		}
1450 		if (fs->fault_flags & VM_FAULT_DIRTY) {
1451 			crit_enter();
1452 			vm_page_dirty(fs->m);
1453 			vm_pager_page_unswapped(fs->m);
1454 			crit_exit();
1455 		}
1456 	}
1457 
1458 	/*
1459 	 * Page had better still be busy.  We are still locked up and
1460 	 * fs->object will have another PIP reference if it is not equal
1461 	 * to fs->first_object.
1462 	 */
1463 	KASSERT(fs->m->flags & PG_BUSY,
1464 		("vm_fault: page %p not busy!", fs->m));
1465 
1466 	/*
1467 	 * Sanity check: page must be completely valid or it is not fit to
1468 	 * map into user space.  vm_pager_get_pages() ensures this.
1469 	 */
1470 	if (fs->m->valid != VM_PAGE_BITS_ALL) {
1471 		vm_page_zero_invalid(fs->m, TRUE);
1472 		kprintf("Warning: page %p partially invalid on fault\n", fs->m);
1473 	}
1474 
1475 	return (KERN_SUCCESS);
1476 }
1477 
1478 /*
1479  * Wire down a range of virtual addresses in a map.  The entry in question
1480  * should be marked in-transition and the map must be locked.  We must
1481  * release the map temporarily while faulting-in the page to avoid a
1482  * deadlock.  Note that the entry may be clipped while we are blocked but
1483  * will never be freed.
1484  */
1485 int
1486 vm_fault_wire(vm_map_t map, vm_map_entry_t entry, boolean_t user_wire)
1487 {
1488 	boolean_t fictitious;
1489 	vm_offset_t start;
1490 	vm_offset_t end;
1491 	vm_offset_t va;
1492 	vm_paddr_t pa;
1493 	pmap_t pmap;
1494 	int rv;
1495 
1496 	pmap = vm_map_pmap(map);
1497 	start = entry->start;
1498 	end = entry->end;
1499 	fictitious = entry->object.vm_object &&
1500 			(entry->object.vm_object->type == OBJT_DEVICE);
1501 
1502 	vm_map_unlock(map);
1503 	map->timestamp++;
1504 
1505 	/*
1506 	 * We simulate a fault to get the page and enter it in the physical
1507 	 * map.
1508 	 */
1509 	for (va = start; va < end; va += PAGE_SIZE) {
1510 		if (user_wire) {
1511 			rv = vm_fault(map, va, VM_PROT_READ,
1512 					VM_FAULT_USER_WIRE);
1513 		} else {
1514 			rv = vm_fault(map, va, VM_PROT_READ|VM_PROT_WRITE,
1515 					VM_FAULT_CHANGE_WIRING);
1516 		}
1517 		if (rv) {
1518 			while (va > start) {
1519 				va -= PAGE_SIZE;
1520 				if ((pa = pmap_extract(pmap, va)) == 0)
1521 					continue;
1522 				pmap_change_wiring(pmap, va, FALSE);
1523 				if (!fictitious)
1524 					vm_page_unwire(PHYS_TO_VM_PAGE(pa), 1);
1525 			}
1526 			vm_map_lock(map);
1527 			return (rv);
1528 		}
1529 	}
1530 	vm_map_lock(map);
1531 	return (KERN_SUCCESS);
1532 }
1533 
1534 /*
1535  * Unwire a range of virtual addresses in a map.  The map should be
1536  * locked.
1537  */
1538 void
1539 vm_fault_unwire(vm_map_t map, vm_map_entry_t entry)
1540 {
1541 	boolean_t fictitious;
1542 	vm_offset_t start;
1543 	vm_offset_t end;
1544 	vm_offset_t va;
1545 	vm_paddr_t pa;
1546 	pmap_t pmap;
1547 
1548 	pmap = vm_map_pmap(map);
1549 	start = entry->start;
1550 	end = entry->end;
1551 	fictitious = entry->object.vm_object &&
1552 			(entry->object.vm_object->type == OBJT_DEVICE);
1553 
1554 	/*
1555 	 * Since the pages are wired down, we must be able to get their
1556 	 * mappings from the physical map system.
1557 	 */
1558 	for (va = start; va < end; va += PAGE_SIZE) {
1559 		pa = pmap_extract(pmap, va);
1560 		if (pa != 0) {
1561 			pmap_change_wiring(pmap, va, FALSE);
1562 			if (!fictitious)
1563 				vm_page_unwire(PHYS_TO_VM_PAGE(pa), 1);
1564 		}
1565 	}
1566 }
1567 
1568 /*
1569  * Reduce the rate at which memory is allocated to a process based
1570  * on the perceived load on the VM system. As the load increases
1571  * the allocation burst rate goes down and the delay increases.
1572  *
1573  * Rate limiting does not apply when faulting active or inactive
1574  * pages.  When faulting 'cache' pages, rate limiting only applies
1575  * if the system currently has a severe page deficit.
1576  *
1577  * XXX vm_pagesupply should be increased when a page is freed.
1578  *
1579  * We sleep up to 1/10 of a second.
1580  */
1581 static int
1582 vm_fault_ratelimit(struct vmspace *vmspace)
1583 {
1584 	if (vm_load_enable == 0)
1585 		return(0);
1586 	if (vmspace->vm_pagesupply > 0) {
1587 		--vmspace->vm_pagesupply;
1588 		return(0);
1589 	}
1590 #ifdef INVARIANTS
1591 	if (vm_load_debug) {
1592 		kprintf("load %-4d give %d pgs, wait %d, pid %-5d (%s)\n",
1593 			vm_load,
1594 			(1000 - vm_load ) / 10, vm_load * hz / 10000,
1595 			curproc->p_pid, curproc->p_comm);
1596 	}
1597 #endif
1598 	vmspace->vm_pagesupply = (1000 - vm_load) / 10;
1599 	return(vm_load * hz / 10000);
1600 }
1601 
1602 /*
1603  *	Routine:
1604  *		vm_fault_copy_entry
1605  *	Function:
1606  *		Copy all of the pages from a wired-down map entry to another.
1607  *
1608  *	In/out conditions:
1609  *		The source and destination maps must be locked for write.
1610  *		The source map entry must be wired down (or be a sharing map
1611  *		entry corresponding to a main map entry that is wired down).
1612  */
1613 
1614 void
1615 vm_fault_copy_entry(vm_map_t dst_map, vm_map_t src_map,
1616     vm_map_entry_t dst_entry, vm_map_entry_t src_entry)
1617 {
1618 	vm_object_t dst_object;
1619 	vm_object_t src_object;
1620 	vm_ooffset_t dst_offset;
1621 	vm_ooffset_t src_offset;
1622 	vm_prot_t prot;
1623 	vm_offset_t vaddr;
1624 	vm_page_t dst_m;
1625 	vm_page_t src_m;
1626 
1627 #ifdef	lint
1628 	src_map++;
1629 #endif	/* lint */
1630 
1631 	src_object = src_entry->object.vm_object;
1632 	src_offset = src_entry->offset;
1633 
1634 	/*
1635 	 * Create the top-level object for the destination entry. (Doesn't
1636 	 * actually shadow anything - we copy the pages directly.)
1637 	 */
1638 	vm_map_entry_allocate_object(dst_entry);
1639 	dst_object = dst_entry->object.vm_object;
1640 
1641 	prot = dst_entry->max_protection;
1642 
1643 	/*
1644 	 * Loop through all of the pages in the entry's range, copying each
1645 	 * one from the source object (it should be there) to the destination
1646 	 * object.
1647 	 */
1648 	for (vaddr = dst_entry->start, dst_offset = 0;
1649 	    vaddr < dst_entry->end;
1650 	    vaddr += PAGE_SIZE, dst_offset += PAGE_SIZE) {
1651 
1652 		/*
1653 		 * Allocate a page in the destination object
1654 		 */
1655 		do {
1656 			dst_m = vm_page_alloc(dst_object,
1657 				OFF_TO_IDX(dst_offset), VM_ALLOC_NORMAL);
1658 			if (dst_m == NULL) {
1659 				vm_wait(0);
1660 			}
1661 		} while (dst_m == NULL);
1662 
1663 		/*
1664 		 * Find the page in the source object, and copy it in.
1665 		 * (Because the source is wired down, the page will be in
1666 		 * memory.)
1667 		 */
1668 		src_m = vm_page_lookup(src_object,
1669 			OFF_TO_IDX(dst_offset + src_offset));
1670 		if (src_m == NULL)
1671 			panic("vm_fault_copy_wired: page missing");
1672 
1673 		vm_page_copy(src_m, dst_m);
1674 		vm_page_event(src_m, VMEVENT_COW);
1675 
1676 		/*
1677 		 * Enter it in the pmap...
1678 		 */
1679 
1680 		vm_page_flag_clear(dst_m, PG_ZERO);
1681 		pmap_enter(dst_map->pmap, vaddr, dst_m, prot, FALSE);
1682 
1683 		/*
1684 		 * Mark it no longer busy, and put it on the active list.
1685 		 */
1686 		vm_page_activate(dst_m);
1687 		vm_page_wakeup(dst_m);
1688 	}
1689 }
1690 
1691 
1692 /*
1693  * This routine checks around the requested page for other pages that
1694  * might be able to be faulted in.  This routine brackets the viable
1695  * pages for the pages to be paged in.
1696  *
1697  * Inputs:
1698  *	m, rbehind, rahead
1699  *
1700  * Outputs:
1701  *  marray (array of vm_page_t), reqpage (index of requested page)
1702  *
1703  * Return value:
1704  *  number of pages in marray
1705  */
1706 static int
1707 vm_fault_additional_pages(vm_page_t m, int rbehind, int rahead,
1708 			  vm_page_t *marray, int *reqpage)
1709 {
1710 	int i,j;
1711 	vm_object_t object;
1712 	vm_pindex_t pindex, startpindex, endpindex, tpindex;
1713 	vm_page_t rtm;
1714 	int cbehind, cahead;
1715 
1716 	object = m->object;
1717 	pindex = m->pindex;
1718 
1719 	/*
1720 	 * we don't fault-ahead for device pager
1721 	 */
1722 	if (object->type == OBJT_DEVICE) {
1723 		*reqpage = 0;
1724 		marray[0] = m;
1725 		return 1;
1726 	}
1727 
1728 	/*
1729 	 * if the requested page is not available, then give up now
1730 	 */
1731 	if (!vm_pager_has_page(object, pindex, &cbehind, &cahead)) {
1732 		*reqpage = 0;	/* not used by caller, fix compiler warn */
1733 		return 0;
1734 	}
1735 
1736 	if ((cbehind == 0) && (cahead == 0)) {
1737 		*reqpage = 0;
1738 		marray[0] = m;
1739 		return 1;
1740 	}
1741 
1742 	if (rahead > cahead) {
1743 		rahead = cahead;
1744 	}
1745 
1746 	if (rbehind > cbehind) {
1747 		rbehind = cbehind;
1748 	}
1749 
1750 	/*
1751 	 * Do not do any readahead if we have insufficient free memory.
1752 	 *
1753 	 * XXX code was broken disabled before and has instability
1754 	 * with this conditonal fixed, so shortcut for now.
1755 	 */
1756 	if (burst_fault == 0 || vm_page_count_severe()) {
1757 		marray[0] = m;
1758 		*reqpage = 0;
1759 		return 1;
1760 	}
1761 
1762 	/*
1763 	 * scan backward for the read behind pages -- in memory
1764 	 *
1765 	 * Assume that if the page is not found an interrupt will not
1766 	 * create it.  Theoretically interrupts can only remove (busy)
1767 	 * pages, not create new associations.
1768 	 */
1769 	if (pindex > 0) {
1770 		if (rbehind > pindex) {
1771 			rbehind = pindex;
1772 			startpindex = 0;
1773 		} else {
1774 			startpindex = pindex - rbehind;
1775 		}
1776 
1777 		crit_enter();
1778 		for (tpindex = pindex; tpindex > startpindex; --tpindex) {
1779 			if (vm_page_lookup(object, tpindex - 1))
1780 				break;
1781 		}
1782 
1783 		i = 0;
1784 		while (tpindex < pindex) {
1785 			rtm = vm_page_alloc(object, tpindex, VM_ALLOC_SYSTEM);
1786 			if (rtm == NULL) {
1787 				crit_exit();
1788 				for (j = 0; j < i; j++) {
1789 					vm_page_free(marray[j]);
1790 				}
1791 				marray[0] = m;
1792 				*reqpage = 0;
1793 				return 1;
1794 			}
1795 			marray[i] = rtm;
1796 			++i;
1797 			++tpindex;
1798 		}
1799 		crit_exit();
1800 	} else {
1801 		i = 0;
1802 	}
1803 
1804 	/*
1805 	 * Assign requested page
1806 	 */
1807 	marray[i] = m;
1808 	*reqpage = i;
1809 	++i;
1810 
1811 	/*
1812 	 * Scan forwards for read-ahead pages
1813 	 */
1814 	tpindex = pindex + 1;
1815 	endpindex = tpindex + rahead;
1816 	if (endpindex > object->size)
1817 		endpindex = object->size;
1818 
1819 	crit_enter();
1820 	while (tpindex < endpindex) {
1821 		if (vm_page_lookup(object, tpindex))
1822 			break;
1823 		rtm = vm_page_alloc(object, tpindex, VM_ALLOC_SYSTEM);
1824 		if (rtm == NULL)
1825 			break;
1826 		marray[i] = rtm;
1827 		++i;
1828 		++tpindex;
1829 	}
1830 	crit_exit();
1831 
1832 	return (i);
1833 }
1834