Merge branch 'master' of ssh://crater.dragonflybsd.org/repository/git/dragonfly
[dragonfly.git] / sys / vm / vm_fault.c
1 /*
2  * (MPSAFE)
3  *
4  * Copyright (c) 1991, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  * Copyright (c) 1994 John S. Dyson
7  * All rights reserved.
8  * Copyright (c) 1994 David Greenman
9  * All rights reserved.
10  *
11  *
12  * This code is derived from software contributed to Berkeley by
13  * The Mach Operating System project at Carnegie-Mellon University.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  * 3. All advertising materials mentioning features or use of this software
24  *    must display the following acknowledgement:
25  *      This product includes software developed by the University of
26  *      California, Berkeley and its contributors.
27  * 4. Neither the name of the University nor the names of its contributors
28  *    may be used to endorse or promote products derived from this software
29  *    without specific prior written permission.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
32  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
35  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
37  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
39  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
40  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
41  * SUCH DAMAGE.
42  *
43  *      from: @(#)vm_fault.c    8.4 (Berkeley) 1/12/94
44  *
45  *
46  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
47  * All rights reserved.
48  *
49  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
50  *
51  * Permission to use, copy, modify and distribute this software and
52  * its documentation is hereby granted, provided that both the copyright
53  * notice and this permission notice appear in all copies of the
54  * software, derivative works or modified versions, and any portions
55  * thereof, and that both notices appear in supporting documentation.
56  *
57  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
58  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
59  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
60  *
61  * Carnegie Mellon requests users of this software to return to
62  *
63  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
64  *  School of Computer Science
65  *  Carnegie Mellon University
66  *  Pittsburgh PA 15213-3890
67  *
68  * any improvements or extensions that they make and grant Carnegie the
69  * rights to redistribute these changes.
70  *
71  * $FreeBSD: src/sys/vm/vm_fault.c,v 1.108.2.8 2002/02/26 05:49:27 silby Exp $
72  * $DragonFly: src/sys/vm/vm_fault.c,v 1.47 2008/07/01 02:02:56 dillon Exp $
73  */
74
75 /*
76  *      Page fault handling module.
77  */
78
79 #include <sys/param.h>
80 #include <sys/systm.h>
81 #include <sys/kernel.h>
82 #include <sys/proc.h>
83 #include <sys/vnode.h>
84 #include <sys/resourcevar.h>
85 #include <sys/vmmeter.h>
86 #include <sys/vkernel.h>
87 #include <sys/lock.h>
88 #include <sys/sysctl.h>
89
90 #include <cpu/lwbuf.h>
91
92 #include <vm/vm.h>
93 #include <vm/vm_param.h>
94 #include <vm/pmap.h>
95 #include <vm/vm_map.h>
96 #include <vm/vm_object.h>
97 #include <vm/vm_page.h>
98 #include <vm/vm_pageout.h>
99 #include <vm/vm_kern.h>
100 #include <vm/vm_pager.h>
101 #include <vm/vnode_pager.h>
102 #include <vm/vm_extern.h>
103
104 #include <sys/thread2.h>
105 #include <vm/vm_page2.h>
106
107 struct faultstate {
108         vm_page_t m;
109         vm_object_t object;
110         vm_pindex_t pindex;
111         vm_prot_t prot;
112         vm_page_t first_m;
113         vm_object_t first_object;
114         vm_prot_t first_prot;
115         vm_map_t map;
116         vm_map_entry_t entry;
117         int lookup_still_valid;
118         int didlimit;
119         int hardfault;
120         int fault_flags;
121         int map_generation;
122         boolean_t wired;
123         struct vnode *vp;
124 };
125
126 static int vm_fast_fault = 1;
127 SYSCTL_INT(_vm, OID_AUTO, fast_fault, CTLFLAG_RW, &vm_fast_fault, 0, 
128            "Burst fault zero-fill regions");
129 static int debug_cluster = 0;
130 SYSCTL_INT(_vm, OID_AUTO, debug_cluster, CTLFLAG_RW, &debug_cluster, 0, "");
131
132 static int vm_fault_object(struct faultstate *, vm_pindex_t, vm_prot_t);
133 static int vm_fault_vpagetable(struct faultstate *, vm_pindex_t *, vpte_t, int);
134 #if 0
135 static int vm_fault_additional_pages (vm_page_t, int, int, vm_page_t *, int *);
136 #endif
137 static int vm_fault_ratelimit(struct vmspace *);
138 static void vm_prefault(pmap_t pmap, vm_offset_t addra, vm_map_entry_t entry,
139                         int prot);
140
141 /*
142  * The caller must hold vm_token.
143  */
144 static __inline void
145 release_page(struct faultstate *fs)
146 {
147         vm_page_deactivate(fs->m);
148         vm_page_wakeup(fs->m);
149         fs->m = NULL;
150 }
151
152 /*
153  * The caller must hold vm_token.
154  */
155 static __inline void
156 unlock_map(struct faultstate *fs)
157 {
158         if (fs->lookup_still_valid && fs->map) {
159                 vm_map_lookup_done(fs->map, fs->entry, 0);
160                 fs->lookup_still_valid = FALSE;
161         }
162 }
163
164 /*
165  * Clean up after a successful call to vm_fault_object() so another call
166  * to vm_fault_object() can be made.
167  *
168  * The caller must hold vm_token.
169  */
170 static void
171 _cleanup_successful_fault(struct faultstate *fs, int relock)
172 {
173         if (fs->object != fs->first_object) {
174                 vm_page_free(fs->first_m);
175                 vm_object_pip_wakeup(fs->object);
176                 fs->first_m = NULL;
177         }
178         fs->object = fs->first_object;
179         if (relock && fs->lookup_still_valid == FALSE) {
180                 if (fs->map)
181                         vm_map_lock_read(fs->map);
182                 fs->lookup_still_valid = TRUE;
183         }
184 }
185
186 /*
187  * The caller must hold vm_token.
188  */
189 static void
190 _unlock_things(struct faultstate *fs, int dealloc)
191 {
192         vm_object_pip_wakeup(fs->first_object);
193         _cleanup_successful_fault(fs, 0);
194         if (dealloc) {
195                 vm_object_deallocate(fs->first_object);
196                 fs->first_object = NULL;
197         }
198         unlock_map(fs); 
199         if (fs->vp != NULL) { 
200                 vput(fs->vp);
201                 fs->vp = NULL;
202         }
203 }
204
205 #define unlock_things(fs) _unlock_things(fs, 0)
206 #define unlock_and_deallocate(fs) _unlock_things(fs, 1)
207 #define cleanup_successful_fault(fs) _cleanup_successful_fault(fs, 1)
208
209 /*
210  * TRYPAGER 
211  *
212  * Determine if the pager for the current object *might* contain the page.
213  *
214  * We only need to try the pager if this is not a default object (default
215  * objects are zero-fill and have no real pager), and if we are not taking
216  * a wiring fault or if the FS entry is wired.
217  */
218 #define TRYPAGER(fs)    \
219                 (fs->object->type != OBJT_DEFAULT && \
220                 (((fs->fault_flags & VM_FAULT_WIRE_MASK) == 0) || fs->wired))
221
222 /*
223  * vm_fault:
224  *
225  * Handle a page fault occuring at the given address, requiring the given
226  * permissions, in the map specified.  If successful, the page is inserted
227  * into the associated physical map.
228  *
229  * NOTE: The given address should be truncated to the proper page address.
230  *
231  * KERN_SUCCESS is returned if the page fault is handled; otherwise,
232  * a standard error specifying why the fault is fatal is returned.
233  *
234  * The map in question must be referenced, and remains so.
235  * The caller may hold no locks.
236  * No other requirements.
237  */
238 int
239 vm_fault(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type, int fault_flags)
240 {
241         int result;
242         vm_pindex_t first_pindex;
243         struct faultstate fs;
244         int growstack;
245
246         mycpu->gd_cnt.v_vm_faults++;
247
248         fs.didlimit = 0;
249         fs.hardfault = 0;
250         fs.fault_flags = fault_flags;
251         growstack = 1;
252
253 RetryFault:
254         /*
255          * Find the vm_map_entry representing the backing store and resolve
256          * the top level object and page index.  This may have the side
257          * effect of executing a copy-on-write on the map entry and/or
258          * creating a shadow object, but will not COW any actual VM pages.
259          *
260          * On success fs.map is left read-locked and various other fields 
261          * are initialized but not otherwise referenced or locked.
262          *
263          * NOTE!  vm_map_lookup will try to upgrade the fault_type to
264          * VM_FAULT_WRITE if the map entry is a virtual page table and also
265          * writable, so we can set the 'A'accessed bit in the virtual page
266          * table entry.
267          */
268         fs.map = map;
269         result = vm_map_lookup(&fs.map, vaddr, fault_type,
270                                &fs.entry, &fs.first_object,
271                                &first_pindex, &fs.first_prot, &fs.wired);
272
273         /*
274          * If the lookup failed or the map protections are incompatible,
275          * the fault generally fails.  However, if the caller is trying
276          * to do a user wiring we have more work to do.
277          */
278         if (result != KERN_SUCCESS) {
279                 if (result != KERN_PROTECTION_FAILURE ||
280                     (fs.fault_flags & VM_FAULT_WIRE_MASK) != VM_FAULT_USER_WIRE)
281                 {
282                         if (result == KERN_INVALID_ADDRESS && growstack &&
283                             map != &kernel_map && curproc != NULL) {
284                                 result = vm_map_growstack(curproc, vaddr);
285                                 if (result != KERN_SUCCESS)
286                                         return (KERN_FAILURE);
287                                 growstack = 0;
288                                 goto RetryFault;
289                         }
290                         return (result);
291                 }
292
293                 /*
294                  * If we are user-wiring a r/w segment, and it is COW, then
295                  * we need to do the COW operation.  Note that we don't
296                  * currently COW RO sections now, because it is NOT desirable
297                  * to COW .text.  We simply keep .text from ever being COW'ed
298                  * and take the heat that one cannot debug wired .text sections.
299                  */
300                 result = vm_map_lookup(&fs.map, vaddr,
301                                        VM_PROT_READ|VM_PROT_WRITE|
302                                         VM_PROT_OVERRIDE_WRITE,
303                                        &fs.entry, &fs.first_object,
304                                        &first_pindex, &fs.first_prot,
305                                        &fs.wired);
306                 if (result != KERN_SUCCESS)
307                         return result;
308
309                 /*
310                  * If we don't COW now, on a user wire, the user will never
311                  * be able to write to the mapping.  If we don't make this
312                  * restriction, the bookkeeping would be nearly impossible.
313                  */
314                 if ((fs.entry->protection & VM_PROT_WRITE) == 0)
315                         fs.entry->max_protection &= ~VM_PROT_WRITE;
316         }
317
318         /*
319          * fs.map is read-locked
320          *
321          * Misc checks.  Save the map generation number to detect races.
322          */
323         fs.map_generation = fs.map->timestamp;
324
325         if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
326                 panic("vm_fault: fault on nofault entry, addr: %lx",
327                     (u_long)vaddr);
328         }
329
330         /*
331          * A system map entry may return a NULL object.  No object means
332          * no pager means an unrecoverable kernel fault.
333          */
334         if (fs.first_object == NULL) {
335                 panic("vm_fault: unrecoverable fault at %p in entry %p",
336                         (void *)vaddr, fs.entry);
337         }
338
339         /*
340          * Make a reference to this object to prevent its disposal while we
341          * are messing with it.  Once we have the reference, the map is free
342          * to be diddled.  Since objects reference their shadows (and copies),
343          * they will stay around as well.
344          *
345          * Bump the paging-in-progress count to prevent size changes (e.g.
346          * truncation operations) during I/O.  This must be done after
347          * obtaining the vnode lock in order to avoid possible deadlocks.
348          *
349          * The vm_token is needed to manipulate the vm_object
350          */
351         lwkt_gettoken(&vm_token);
352         vm_object_reference(fs.first_object);
353         fs.vp = vnode_pager_lock(fs.first_object);
354         vm_object_pip_add(fs.first_object, 1);
355         lwkt_reltoken(&vm_token);
356
357         fs.lookup_still_valid = TRUE;
358         fs.first_m = NULL;
359         fs.object = fs.first_object;    /* so unlock_and_deallocate works */
360
361         /*
362          * If the entry is wired we cannot change the page protection.
363          */
364         if (fs.wired)
365                 fault_type = fs.first_prot;
366
367         /*
368          * The page we want is at (first_object, first_pindex), but if the
369          * vm_map_entry is VM_MAPTYPE_VPAGETABLE we have to traverse the
370          * page table to figure out the actual pindex.
371          *
372          * NOTE!  DEVELOPMENT IN PROGRESS, THIS IS AN INITIAL IMPLEMENTATION
373          * ONLY
374          */
375         if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
376                 result = vm_fault_vpagetable(&fs, &first_pindex,
377                                              fs.entry->aux.master_pde,
378                                              fault_type);
379                 if (result == KERN_TRY_AGAIN)
380                         goto RetryFault;
381                 if (result != KERN_SUCCESS)
382                         return (result);
383         }
384
385         /*
386          * Now we have the actual (object, pindex), fault in the page.  If
387          * vm_fault_object() fails it will unlock and deallocate the FS
388          * data.   If it succeeds everything remains locked and fs->object
389          * will have an additional PIP count if it is not equal to
390          * fs->first_object
391          *
392          * vm_fault_object will set fs->prot for the pmap operation.  It is
393          * allowed to set VM_PROT_WRITE if fault_type == VM_PROT_READ if the
394          * page can be safely written.  However, it will force a read-only
395          * mapping for a read fault if the memory is managed by a virtual
396          * page table.
397          */
398         result = vm_fault_object(&fs, first_pindex, fault_type);
399
400         if (result == KERN_TRY_AGAIN)
401                 goto RetryFault;
402         if (result != KERN_SUCCESS)
403                 return (result);
404
405         /*
406          * On success vm_fault_object() does not unlock or deallocate, and fs.m
407          * will contain a busied page.
408          *
409          * Enter the page into the pmap and do pmap-related adjustments.
410          */
411         pmap_enter(fs.map->pmap, vaddr, fs.m, fs.prot, fs.wired);
412
413         /*
414          * Burst in a few more pages if possible.  The fs.map should still
415          * be locked.
416          */
417         if (fault_flags & VM_FAULT_BURST) {
418                 if ((fs.fault_flags & VM_FAULT_WIRE_MASK) == 0 &&
419                     fs.wired == 0) {
420                         vm_prefault(fs.map->pmap, vaddr, fs.entry, fs.prot);
421                 }
422         }
423         unlock_things(&fs);
424
425         vm_page_flag_clear(fs.m, PG_ZERO);
426         vm_page_flag_set(fs.m, PG_REFERENCED);
427
428         /*
429          * If the page is not wired down, then put it where the pageout daemon
430          * can find it.
431          *
432          * We do not really need to get vm_token here but since all the
433          * vm_*() calls have to doing it here improves efficiency.
434          */
435         lwkt_gettoken(&vm_token);
436         if (fs.fault_flags & VM_FAULT_WIRE_MASK) {
437                 if (fs.wired)
438                         vm_page_wire(fs.m);
439                 else
440                         vm_page_unwire(fs.m, 1);
441         } else {
442                 vm_page_activate(fs.m);
443         }
444
445         if (curthread->td_lwp) {
446                 if (fs.hardfault) {
447                         curthread->td_lwp->lwp_ru.ru_majflt++;
448                 } else {
449                         curthread->td_lwp->lwp_ru.ru_minflt++;
450                 }
451         }
452
453         /*
454          * Unlock everything, and return
455          */
456         vm_page_wakeup(fs.m);
457         vm_object_deallocate(fs.first_object);
458         lwkt_reltoken(&vm_token);
459
460         return (KERN_SUCCESS);
461 }
462
463 /*
464  * Fault in the specified virtual address in the current process map, 
465  * returning a held VM page or NULL.  See vm_fault_page() for more 
466  * information.
467  *
468  * No requirements.
469  */
470 vm_page_t
471 vm_fault_page_quick(vm_offset_t va, vm_prot_t fault_type, int *errorp)
472 {
473         struct lwp *lp = curthread->td_lwp;
474         vm_page_t m;
475
476         m = vm_fault_page(&lp->lwp_vmspace->vm_map, va, 
477                           fault_type, VM_FAULT_NORMAL, errorp);
478         return(m);
479 }
480
481 /*
482  * Fault in the specified virtual address in the specified map, doing all
483  * necessary manipulation of the object store and all necessary I/O.  Return
484  * a held VM page or NULL, and set *errorp.  The related pmap is not
485  * updated.
486  *
487  * The returned page will be properly dirtied if VM_PROT_WRITE was specified,
488  * and marked PG_REFERENCED as well.
489  *
490  * If the page cannot be faulted writable and VM_PROT_WRITE was specified, an
491  * error will be returned.
492  *
493  * No requirements.
494  */
495 vm_page_t
496 vm_fault_page(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
497               int fault_flags, int *errorp)
498 {
499         vm_pindex_t first_pindex;
500         struct faultstate fs;
501         int result;
502         vm_prot_t orig_fault_type = fault_type;
503
504         mycpu->gd_cnt.v_vm_faults++;
505
506         fs.didlimit = 0;
507         fs.hardfault = 0;
508         fs.fault_flags = fault_flags;
509         KKASSERT((fault_flags & VM_FAULT_WIRE_MASK) == 0);
510
511 RetryFault:
512         /*
513          * Find the vm_map_entry representing the backing store and resolve
514          * the top level object and page index.  This may have the side
515          * effect of executing a copy-on-write on the map entry and/or
516          * creating a shadow object, but will not COW any actual VM pages.
517          *
518          * On success fs.map is left read-locked and various other fields 
519          * are initialized but not otherwise referenced or locked.
520          *
521          * NOTE!  vm_map_lookup will upgrade the fault_type to VM_FAULT_WRITE
522          * if the map entry is a virtual page table and also writable,
523          * so we can set the 'A'accessed bit in the virtual page table entry.
524          */
525         fs.map = map;
526         result = vm_map_lookup(&fs.map, vaddr, fault_type,
527                                &fs.entry, &fs.first_object,
528                                &first_pindex, &fs.first_prot, &fs.wired);
529
530         if (result != KERN_SUCCESS) {
531                 *errorp = result;
532                 return (NULL);
533         }
534
535         /*
536          * fs.map is read-locked
537          *
538          * Misc checks.  Save the map generation number to detect races.
539          */
540         fs.map_generation = fs.map->timestamp;
541
542         if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
543                 panic("vm_fault: fault on nofault entry, addr: %lx",
544                     (u_long)vaddr);
545         }
546
547         /*
548          * A system map entry may return a NULL object.  No object means
549          * no pager means an unrecoverable kernel fault.
550          */
551         if (fs.first_object == NULL) {
552                 panic("vm_fault: unrecoverable fault at %p in entry %p",
553                         (void *)vaddr, fs.entry);
554         }
555
556         /*
557          * Make a reference to this object to prevent its disposal while we
558          * are messing with it.  Once we have the reference, the map is free
559          * to be diddled.  Since objects reference their shadows (and copies),
560          * they will stay around as well.
561          *
562          * Bump the paging-in-progress count to prevent size changes (e.g.
563          * truncation operations) during I/O.  This must be done after
564          * obtaining the vnode lock in order to avoid possible deadlocks.
565          *
566          * The vm_token is needed to manipulate the vm_object
567          */
568         lwkt_gettoken(&vm_token);
569         vm_object_reference(fs.first_object);
570         fs.vp = vnode_pager_lock(fs.first_object);
571         vm_object_pip_add(fs.first_object, 1);
572         lwkt_reltoken(&vm_token);
573
574         fs.lookup_still_valid = TRUE;
575         fs.first_m = NULL;
576         fs.object = fs.first_object;    /* so unlock_and_deallocate works */
577
578         /*
579          * If the entry is wired we cannot change the page protection.
580          */
581         if (fs.wired)
582                 fault_type = fs.first_prot;
583
584         /*
585          * The page we want is at (first_object, first_pindex), but if the
586          * vm_map_entry is VM_MAPTYPE_VPAGETABLE we have to traverse the
587          * page table to figure out the actual pindex.
588          *
589          * NOTE!  DEVELOPMENT IN PROGRESS, THIS IS AN INITIAL IMPLEMENTATION
590          * ONLY
591          */
592         if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
593                 result = vm_fault_vpagetable(&fs, &first_pindex,
594                                              fs.entry->aux.master_pde,
595                                              fault_type);
596                 if (result == KERN_TRY_AGAIN)
597                         goto RetryFault;
598                 if (result != KERN_SUCCESS) {
599                         *errorp = result;
600                         return (NULL);
601                 }
602         }
603
604         /*
605          * Now we have the actual (object, pindex), fault in the page.  If
606          * vm_fault_object() fails it will unlock and deallocate the FS
607          * data.   If it succeeds everything remains locked and fs->object
608          * will have an additinal PIP count if it is not equal to
609          * fs->first_object
610          */
611         result = vm_fault_object(&fs, first_pindex, fault_type);
612
613         if (result == KERN_TRY_AGAIN)
614                 goto RetryFault;
615         if (result != KERN_SUCCESS) {
616                 *errorp = result;
617                 return(NULL);
618         }
619
620         if ((orig_fault_type & VM_PROT_WRITE) &&
621             (fs.prot & VM_PROT_WRITE) == 0) {
622                 *errorp = KERN_PROTECTION_FAILURE;
623                 unlock_and_deallocate(&fs);
624                 return(NULL);
625         }
626
627         /*
628          * On success vm_fault_object() does not unlock or deallocate, and fs.m
629          * will contain a busied page.
630          */
631         unlock_things(&fs);
632
633         /*
634          * Return a held page.  We are not doing any pmap manipulation so do
635          * not set PG_MAPPED.  However, adjust the page flags according to
636          * the fault type because the caller may not use a managed pmapping
637          * (so we don't want to lose the fact that the page will be dirtied
638          * if a write fault was specified).
639          */
640         lwkt_gettoken(&vm_token);
641         vm_page_hold(fs.m);
642         vm_page_flag_clear(fs.m, PG_ZERO);
643         if (fault_type & VM_PROT_WRITE)
644                 vm_page_dirty(fs.m);
645
646         /*
647          * Update the pmap.  We really only have to do this if a COW
648          * occured to replace the read-only page with the new page.  For
649          * now just do it unconditionally. XXX
650          */
651         pmap_enter(fs.map->pmap, vaddr, fs.m, fs.prot, fs.wired);
652         vm_page_flag_set(fs.m, PG_REFERENCED);
653
654         /*
655          * Unbusy the page by activating it.  It remains held and will not
656          * be reclaimed.
657          */
658         vm_page_activate(fs.m);
659
660         if (curthread->td_lwp) {
661                 if (fs.hardfault) {
662                         curthread->td_lwp->lwp_ru.ru_majflt++;
663                 } else {
664                         curthread->td_lwp->lwp_ru.ru_minflt++;
665                 }
666         }
667
668         /*
669          * Unlock everything, and return the held page.
670          */
671         vm_page_wakeup(fs.m);
672         vm_object_deallocate(fs.first_object);
673         lwkt_reltoken(&vm_token);
674
675         *errorp = 0;
676         return(fs.m);
677 }
678
679 /*
680  * Fault in the specified (object,offset), dirty the returned page as
681  * needed.  If the requested fault_type cannot be done NULL and an
682  * error is returned.
683  *
684  * A held (but not busied) page is returned.
685  *
686  * No requirements.
687  */
688 vm_page_t
689 vm_fault_object_page(vm_object_t object, vm_ooffset_t offset,
690                      vm_prot_t fault_type, int fault_flags, int *errorp)
691 {
692         int result;
693         vm_pindex_t first_pindex;
694         struct faultstate fs;
695         struct vm_map_entry entry;
696
697         bzero(&entry, sizeof(entry));
698         entry.object.vm_object = object;
699         entry.maptype = VM_MAPTYPE_NORMAL;
700         entry.protection = entry.max_protection = fault_type;
701
702         fs.didlimit = 0;
703         fs.hardfault = 0;
704         fs.fault_flags = fault_flags;
705         fs.map = NULL;
706         KKASSERT((fault_flags & VM_FAULT_WIRE_MASK) == 0);
707
708 RetryFault:
709         
710         fs.first_object = object;
711         first_pindex = OFF_TO_IDX(offset);
712         fs.entry = &entry;
713         fs.first_prot = fault_type;
714         fs.wired = 0;
715         /*fs.map_generation = 0; unused */
716
717         /*
718          * Make a reference to this object to prevent its disposal while we
719          * are messing with it.  Once we have the reference, the map is free
720          * to be diddled.  Since objects reference their shadows (and copies),
721          * they will stay around as well.
722          *
723          * Bump the paging-in-progress count to prevent size changes (e.g.
724          * truncation operations) during I/O.  This must be done after
725          * obtaining the vnode lock in order to avoid possible deadlocks.
726          */
727         lwkt_gettoken(&vm_token);
728         vm_object_reference(fs.first_object);
729         fs.vp = vnode_pager_lock(fs.first_object);
730         vm_object_pip_add(fs.first_object, 1);
731         lwkt_reltoken(&vm_token);
732
733         fs.lookup_still_valid = TRUE;
734         fs.first_m = NULL;
735         fs.object = fs.first_object;    /* so unlock_and_deallocate works */
736
737 #if 0
738         /* XXX future - ability to operate on VM object using vpagetable */
739         if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
740                 result = vm_fault_vpagetable(&fs, &first_pindex,
741                                              fs.entry->aux.master_pde,
742                                              fault_type);
743                 if (result == KERN_TRY_AGAIN)
744                         goto RetryFault;
745                 if (result != KERN_SUCCESS) {
746                         *errorp = result;
747                         return (NULL);
748                 }
749         }
750 #endif
751
752         /*
753          * Now we have the actual (object, pindex), fault in the page.  If
754          * vm_fault_object() fails it will unlock and deallocate the FS
755          * data.   If it succeeds everything remains locked and fs->object
756          * will have an additinal PIP count if it is not equal to
757          * fs->first_object
758          */
759         result = vm_fault_object(&fs, first_pindex, fault_type);
760
761         if (result == KERN_TRY_AGAIN)
762                 goto RetryFault;
763         if (result != KERN_SUCCESS) {
764                 *errorp = result;
765                 return(NULL);
766         }
767
768         if ((fault_type & VM_PROT_WRITE) && (fs.prot & VM_PROT_WRITE) == 0) {
769                 *errorp = KERN_PROTECTION_FAILURE;
770                 unlock_and_deallocate(&fs);
771                 return(NULL);
772         }
773
774         /*
775          * On success vm_fault_object() does not unlock or deallocate, and fs.m
776          * will contain a busied page.
777          */
778         unlock_things(&fs);
779
780         /*
781          * Return a held page.  We are not doing any pmap manipulation so do
782          * not set PG_MAPPED.  However, adjust the page flags according to
783          * the fault type because the caller may not use a managed pmapping
784          * (so we don't want to lose the fact that the page will be dirtied
785          * if a write fault was specified).
786          */
787         lwkt_gettoken(&vm_token);
788         vm_page_hold(fs.m);
789         vm_page_flag_clear(fs.m, PG_ZERO);
790         if (fault_type & VM_PROT_WRITE)
791                 vm_page_dirty(fs.m);
792
793         if (fault_flags & VM_FAULT_DIRTY)
794                 vm_page_dirty(fs.m);
795         if (fault_flags & VM_FAULT_UNSWAP)
796                 swap_pager_unswapped(fs.m);
797
798         /*
799          * Indicate that the page was accessed.
800          */
801         vm_page_flag_set(fs.m, PG_REFERENCED);
802
803         /*
804          * Unbusy the page by activating it.  It remains held and will not
805          * be reclaimed.
806          */
807         vm_page_activate(fs.m);
808
809         if (curthread->td_lwp) {
810                 if (fs.hardfault) {
811                         mycpu->gd_cnt.v_vm_faults++;
812                         curthread->td_lwp->lwp_ru.ru_majflt++;
813                 } else {
814                         curthread->td_lwp->lwp_ru.ru_minflt++;
815                 }
816         }
817
818         /*
819          * Unlock everything, and return the held page.
820          */
821         vm_page_wakeup(fs.m);
822         vm_object_deallocate(fs.first_object);
823         lwkt_reltoken(&vm_token);
824
825         *errorp = 0;
826         return(fs.m);
827 }
828
829 /*
830  * Translate the virtual page number (first_pindex) that is relative
831  * to the address space into a logical page number that is relative to the
832  * backing object.  Use the virtual page table pointed to by (vpte).
833  *
834  * This implements an N-level page table.  Any level can terminate the
835  * scan by setting VPTE_PS.   A linear mapping is accomplished by setting
836  * VPTE_PS in the master page directory entry set via mcontrol(MADV_SETMAP).
837  *
838  * No requirements (vm_token need not be held).
839  */
840 static
841 int
842 vm_fault_vpagetable(struct faultstate *fs, vm_pindex_t *pindex,
843                     vpte_t vpte, int fault_type)
844 {
845         struct lwbuf *lwb;
846         int vshift = VPTE_FRAME_END - PAGE_SHIFT; /* index bits remaining */
847         int result = KERN_SUCCESS;
848         vpte_t *ptep;
849
850         for (;;) {
851                 /*
852                  * We cannot proceed if the vpte is not valid, not readable
853                  * for a read fault, or not writable for a write fault.
854                  */
855                 if ((vpte & VPTE_V) == 0) {
856                         unlock_and_deallocate(fs);
857                         return (KERN_FAILURE);
858                 }
859                 if ((fault_type & VM_PROT_READ) && (vpte & VPTE_R) == 0) {
860                         unlock_and_deallocate(fs);
861                         return (KERN_FAILURE);
862                 }
863                 if ((fault_type & VM_PROT_WRITE) && (vpte & VPTE_W) == 0) {
864                         unlock_and_deallocate(fs);
865                         return (KERN_FAILURE);
866                 }
867                 if ((vpte & VPTE_PS) || vshift == 0)
868                         break;
869                 KKASSERT(vshift >= VPTE_PAGE_BITS);
870
871                 /*
872                  * Get the page table page.  Nominally we only read the page
873                  * table, but since we are actively setting VPTE_M and VPTE_A,
874                  * tell vm_fault_object() that we are writing it. 
875                  *
876                  * There is currently no real need to optimize this.
877                  */
878                 result = vm_fault_object(fs, (vpte & VPTE_FRAME) >> PAGE_SHIFT,
879                                          VM_PROT_READ|VM_PROT_WRITE);
880                 if (result != KERN_SUCCESS)
881                         return (result);
882
883                 /*
884                  * Process the returned fs.m and look up the page table
885                  * entry in the page table page.
886                  */
887                 vshift -= VPTE_PAGE_BITS;
888                 lwb = lwbuf_alloc(fs->m);
889                 ptep = ((vpte_t *)lwbuf_kva(lwb) +
890                         ((*pindex >> vshift) & VPTE_PAGE_MASK));
891                 vpte = *ptep;
892
893                 /*
894                  * Page table write-back.  If the vpte is valid for the
895                  * requested operation, do a write-back to the page table.
896                  *
897                  * XXX VPTE_M is not set properly for page directory pages.
898                  * It doesn't get set in the page directory if the page table
899                  * is modified during a read access.
900                  */
901                 if ((fault_type & VM_PROT_WRITE) && (vpte & VPTE_V) &&
902                     (vpte & VPTE_W)) {
903                         if ((vpte & (VPTE_M|VPTE_A)) != (VPTE_M|VPTE_A)) {
904                                 atomic_set_long(ptep, VPTE_M | VPTE_A);
905                                 vm_page_dirty(fs->m);
906                         }
907                 }
908                 if ((fault_type & VM_PROT_READ) && (vpte & VPTE_V) &&
909                     (vpte & VPTE_R)) {
910                         if ((vpte & VPTE_A) == 0) {
911                                 atomic_set_long(ptep, VPTE_A);
912                                 vm_page_dirty(fs->m);
913                         }
914                 }
915                 lwbuf_free(lwb);
916                 vm_page_flag_set(fs->m, PG_REFERENCED);
917                 vm_page_activate(fs->m);
918                 vm_page_wakeup(fs->m);
919                 cleanup_successful_fault(fs);
920         }
921         /*
922          * Combine remaining address bits with the vpte.
923          */
924         /* JG how many bits from each? */
925         *pindex = ((vpte & VPTE_FRAME) >> PAGE_SHIFT) +
926                   (*pindex & ((1L << vshift) - 1));
927         return (KERN_SUCCESS);
928 }
929
930
931 /*
932  * This is the core of the vm_fault code.
933  *
934  * Do all operations required to fault-in (fs.first_object, pindex).  Run
935  * through the shadow chain as necessary and do required COW or virtual
936  * copy operations.  The caller has already fully resolved the vm_map_entry
937  * and, if appropriate, has created a copy-on-write layer.  All we need to
938  * do is iterate the object chain.
939  *
940  * On failure (fs) is unlocked and deallocated and the caller may return or
941  * retry depending on the failure code.  On success (fs) is NOT unlocked or
942  * deallocated, fs.m will contained a resolved, busied page, and fs.object
943  * will have an additional PIP count if it is not equal to fs.first_object.
944  *
945  * No requirements.
946  */
947 static
948 int
949 vm_fault_object(struct faultstate *fs,
950                 vm_pindex_t first_pindex, vm_prot_t fault_type)
951 {
952         vm_object_t next_object;
953         vm_pindex_t pindex;
954
955         fs->prot = fs->first_prot;
956         fs->object = fs->first_object;
957         pindex = first_pindex;
958
959         /* 
960          * If a read fault occurs we try to make the page writable if
961          * possible.  There are three cases where we cannot make the
962          * page mapping writable:
963          *
964          * (1) The mapping is read-only or the VM object is read-only,
965          *     fs->prot above will simply not have VM_PROT_WRITE set.
966          *
967          * (2) If the mapping is a virtual page table we need to be able
968          *     to detect writes so we can set VPTE_M in the virtual page
969          *     table.
970          *
971          * (3) If the VM page is read-only or copy-on-write, upgrading would
972          *     just result in an unnecessary COW fault.
973          *
974          * VM_PROT_VPAGED is set if faulting via a virtual page table and
975          * causes adjustments to the 'M'odify bit to also turn off write
976          * access to force a re-fault.
977          */
978         if (fs->entry->maptype == VM_MAPTYPE_VPAGETABLE) {
979                 if ((fault_type & VM_PROT_WRITE) == 0)
980                         fs->prot &= ~VM_PROT_WRITE;
981         }
982
983         lwkt_gettoken(&vm_token);
984
985         for (;;) {
986                 /*
987                  * If the object is dead, we stop here
988                  */
989                 if (fs->object->flags & OBJ_DEAD) {
990                         unlock_and_deallocate(fs);
991                         lwkt_reltoken(&vm_token);
992                         return (KERN_PROTECTION_FAILURE);
993                 }
994
995                 /*
996                  * See if page is resident.  spl protection is required
997                  * to avoid an interrupt unbusy/free race against our
998                  * lookup.  We must hold the protection through a page
999                  * allocation or busy.
1000                  */
1001                 crit_enter();
1002                 fs->m = vm_page_lookup(fs->object, pindex);
1003                 if (fs->m != NULL) {
1004                         int queue;
1005                         /*
1006                          * Wait/Retry if the page is busy.  We have to do this
1007                          * if the page is busy via either PG_BUSY or 
1008                          * vm_page_t->busy because the vm_pager may be using
1009                          * vm_page_t->busy for pageouts ( and even pageins if
1010                          * it is the vnode pager ), and we could end up trying
1011                          * to pagein and pageout the same page simultaneously.
1012                          *
1013                          * We can theoretically allow the busy case on a read
1014                          * fault if the page is marked valid, but since such
1015                          * pages are typically already pmap'd, putting that
1016                          * special case in might be more effort then it is 
1017                          * worth.  We cannot under any circumstances mess
1018                          * around with a vm_page_t->busy page except, perhaps,
1019                          * to pmap it.
1020                          */
1021                         if ((fs->m->flags & PG_BUSY) || fs->m->busy) {
1022                                 unlock_things(fs);
1023                                 vm_page_sleep_busy(fs->m, TRUE, "vmpfw");
1024                                 mycpu->gd_cnt.v_intrans++;
1025                                 vm_object_deallocate(fs->first_object);
1026                                 fs->first_object = NULL;
1027                                 lwkt_reltoken(&vm_token);
1028                                 crit_exit();
1029                                 return (KERN_TRY_AGAIN);
1030                         }
1031
1032                         /*
1033                          * If reactivating a page from PQ_CACHE we may have
1034                          * to rate-limit.
1035                          */
1036                         queue = fs->m->queue;
1037                         vm_page_unqueue_nowakeup(fs->m);
1038
1039                         if ((queue - fs->m->pc) == PQ_CACHE && 
1040                             vm_page_count_severe()) {
1041                                 vm_page_activate(fs->m);
1042                                 unlock_and_deallocate(fs);
1043                                 vm_waitpfault();
1044                                 lwkt_reltoken(&vm_token);
1045                                 crit_exit();
1046                                 return (KERN_TRY_AGAIN);
1047                         }
1048
1049                         /*
1050                          * Mark page busy for other processes, and the 
1051                          * pagedaemon.  If it still isn't completely valid
1052                          * (readable), or if a read-ahead-mark is set on
1053                          * the VM page, jump to readrest, else we found the
1054                          * page and can return.
1055                          *
1056                          * We can release the spl once we have marked the
1057                          * page busy.
1058                          */
1059                         vm_page_busy(fs->m);
1060                         crit_exit();
1061
1062                         if (fs->m->object != &kernel_object) {
1063                                 if ((fs->m->valid & VM_PAGE_BITS_ALL) !=
1064                                     VM_PAGE_BITS_ALL) {
1065                                         goto readrest;
1066                                 }
1067                                 if (fs->m->flags & PG_RAM) {
1068                                         if (debug_cluster)
1069                                                 kprintf("R");
1070                                         vm_page_flag_clear(fs->m, PG_RAM);
1071                                         goto readrest;
1072                                 }
1073                         }
1074                         break; /* break to PAGE HAS BEEN FOUND */
1075                 }
1076
1077                 /*
1078                  * Page is not resident, If this is the search termination
1079                  * or the pager might contain the page, allocate a new page.
1080                  *
1081                  * NOTE: We are still in a critical section.
1082                  */
1083                 if (TRYPAGER(fs) || fs->object == fs->first_object) {
1084                         /*
1085                          * If the page is beyond the object size we fail
1086                          */
1087                         if (pindex >= fs->object->size) {
1088                                 lwkt_reltoken(&vm_token);
1089                                 crit_exit();
1090                                 unlock_and_deallocate(fs);
1091                                 return (KERN_PROTECTION_FAILURE);
1092                         }
1093
1094                         /*
1095                          * Ratelimit.
1096                          */
1097                         if (fs->didlimit == 0 && curproc != NULL) {
1098                                 int limticks;
1099
1100                                 limticks = vm_fault_ratelimit(curproc->p_vmspace);
1101                                 if (limticks) {
1102                                         lwkt_reltoken(&vm_token);
1103                                         crit_exit();
1104                                         unlock_and_deallocate(fs);
1105                                         tsleep(curproc, 0, "vmrate", limticks);
1106                                         fs->didlimit = 1;
1107                                         return (KERN_TRY_AGAIN);
1108                                 }
1109                         }
1110
1111                         /*
1112                          * Allocate a new page for this object/offset pair.
1113                          */
1114                         fs->m = NULL;
1115                         if (!vm_page_count_severe()) {
1116                                 fs->m = vm_page_alloc(fs->object, pindex,
1117                                     (fs->vp || fs->object->backing_object) ? VM_ALLOC_NORMAL : VM_ALLOC_NORMAL | VM_ALLOC_ZERO);
1118                         }
1119                         if (fs->m == NULL) {
1120                                 lwkt_reltoken(&vm_token);
1121                                 crit_exit();
1122                                 unlock_and_deallocate(fs);
1123                                 vm_waitpfault();
1124                                 return (KERN_TRY_AGAIN);
1125                         }
1126                 }
1127                 crit_exit();
1128
1129 readrest:
1130                 /*
1131                  * We have found an invalid or partially valid page, a
1132                  * page with a read-ahead mark which might be partially or
1133                  * fully valid (and maybe dirty too), or we have allocated
1134                  * a new page.
1135                  *
1136                  * Attempt to fault-in the page if there is a chance that the
1137                  * pager has it, and potentially fault in additional pages
1138                  * at the same time.
1139                  *
1140                  * We are NOT in splvm here and if TRYPAGER is true then
1141                  * fs.m will be non-NULL and will be PG_BUSY for us.
1142                  */
1143                 if (TRYPAGER(fs)) {
1144                         int rv;
1145                         int seqaccess;
1146                         u_char behavior = vm_map_entry_behavior(fs->entry);
1147
1148                         if (behavior == MAP_ENTRY_BEHAV_RANDOM)
1149                                 seqaccess = 0;
1150                         else
1151                                 seqaccess = -1;
1152
1153                         /*
1154                          * If sequential access is detected then attempt
1155                          * to deactivate/cache pages behind the scan to
1156                          * prevent resource hogging.
1157                          *
1158                          * Use of PG_RAM to detect sequential access
1159                          * also simulates multi-zone sequential access
1160                          * detection for free.
1161                          *
1162                          * NOTE: Partially valid dirty pages cannot be
1163                          *       deactivated without causing NFS picemeal
1164                          *       writes to barf.
1165                          */
1166                         if ((fs->first_object->type != OBJT_DEVICE) &&
1167                             (behavior == MAP_ENTRY_BEHAV_SEQUENTIAL ||
1168                                 (behavior != MAP_ENTRY_BEHAV_RANDOM &&
1169                                  (fs->m->flags & PG_RAM)))
1170                         ) {
1171                                 vm_pindex_t scan_pindex;
1172                                 int scan_count = 16;
1173
1174                                 if (first_pindex < 16) {
1175                                         scan_pindex = 0;
1176                                         scan_count = 0;
1177                                 } else {
1178                                         scan_pindex = first_pindex - 16;
1179                                         if (scan_pindex < 16)
1180                                                 scan_count = scan_pindex;
1181                                         else
1182                                                 scan_count = 16;
1183                                 }
1184
1185                                 crit_enter();
1186                                 while (scan_count) {
1187                                         vm_page_t mt;
1188
1189                                         mt = vm_page_lookup(fs->first_object,
1190                                                             scan_pindex);
1191                                         if (mt == NULL ||
1192                                             (mt->valid != VM_PAGE_BITS_ALL)) {
1193                                                 break;
1194                                         }
1195                                         if (mt->busy ||
1196                                             (mt->flags & (PG_BUSY | PG_FICTITIOUS | PG_UNMANAGED)) ||
1197                                             mt->hold_count ||
1198                                             mt->wire_count)  {
1199                                                 goto skip;
1200                                         }
1201                                         if (mt->dirty == 0)
1202                                                 vm_page_test_dirty(mt);
1203                                         if (mt->dirty) {
1204                                                 vm_page_busy(mt);
1205                                                 vm_page_protect(mt,
1206                                                                 VM_PROT_NONE);
1207                                                 vm_page_deactivate(mt);
1208                                                 vm_page_wakeup(mt);
1209                                         } else {
1210                                                 vm_page_cache(mt);
1211                                         }
1212 skip:
1213                                         --scan_count;
1214                                         --scan_pindex;
1215                                 }
1216                                 crit_exit();
1217
1218                                 seqaccess = 1;
1219                         }
1220
1221                         /*
1222                          * Avoid deadlocking against the map when doing I/O.
1223                          * fs.object and the page is PG_BUSY'd.
1224                          */
1225                         unlock_map(fs);
1226
1227                         /*
1228                          * Acquire the page data.  We still hold a ref on
1229                          * fs.object and the page has been PG_BUSY's.
1230                          *
1231                          * The pager may replace the page (for example, in
1232                          * order to enter a fictitious page into the
1233                          * object).  If it does so it is responsible for
1234                          * cleaning up the passed page and properly setting
1235                          * the new page PG_BUSY.
1236                          *
1237                          * If we got here through a PG_RAM read-ahead
1238                          * mark the page may be partially dirty and thus
1239                          * not freeable.  Don't bother checking to see
1240                          * if the pager has the page because we can't free
1241                          * it anyway.  We have to depend on the get_page
1242                          * operation filling in any gaps whether there is
1243                          * backing store or not.
1244                          */
1245                         rv = vm_pager_get_page(fs->object, &fs->m, seqaccess);
1246
1247                         if (rv == VM_PAGER_OK) {
1248                                 /*
1249                                  * Relookup in case pager changed page. Pager
1250                                  * is responsible for disposition of old page
1251                                  * if moved.
1252                                  *
1253                                  * XXX other code segments do relookups too.
1254                                  * It's a bad abstraction that needs to be
1255                                  * fixed/removed.
1256                                  */
1257                                 fs->m = vm_page_lookup(fs->object, pindex);
1258                                 if (fs->m == NULL) {
1259                                         lwkt_reltoken(&vm_token);
1260                                         unlock_and_deallocate(fs);
1261                                         return (KERN_TRY_AGAIN);
1262                                 }
1263
1264                                 ++fs->hardfault;
1265                                 break; /* break to PAGE HAS BEEN FOUND */
1266                         }
1267
1268                         /*
1269                          * Remove the bogus page (which does not exist at this
1270                          * object/offset); before doing so, we must get back
1271                          * our object lock to preserve our invariant.
1272                          *
1273                          * Also wake up any other process that may want to bring
1274                          * in this page.
1275                          *
1276                          * If this is the top-level object, we must leave the
1277                          * busy page to prevent another process from rushing
1278                          * past us, and inserting the page in that object at
1279                          * the same time that we are.
1280                          */
1281                         if (rv == VM_PAGER_ERROR) {
1282                                 if (curproc)
1283                                         kprintf("vm_fault: pager read error, pid %d (%s)\n", curproc->p_pid, curproc->p_comm);
1284                                 else
1285                                         kprintf("vm_fault: pager read error, thread %p (%s)\n", curthread, curproc->p_comm);
1286                         }
1287
1288                         /*
1289                          * Data outside the range of the pager or an I/O error
1290                          *
1291                          * The page may have been wired during the pagein,
1292                          * e.g. by the buffer cache, and cannot simply be
1293                          * freed.  Call vnode_pager_freepage() to deal with it.
1294                          */
1295                         /*
1296                          * XXX - the check for kernel_map is a kludge to work
1297                          * around having the machine panic on a kernel space
1298                          * fault w/ I/O error.
1299                          */
1300                         if (((fs->map != &kernel_map) &&
1301                             (rv == VM_PAGER_ERROR)) || (rv == VM_PAGER_BAD)) {
1302                                 vnode_pager_freepage(fs->m);
1303                                 lwkt_reltoken(&vm_token);
1304                                 fs->m = NULL;
1305                                 unlock_and_deallocate(fs);
1306                                 if (rv == VM_PAGER_ERROR)
1307                                         return (KERN_FAILURE);
1308                                 else
1309                                         return (KERN_PROTECTION_FAILURE);
1310                                 /* NOT REACHED */
1311                         }
1312                         if (fs->object != fs->first_object) {
1313                                 vnode_pager_freepage(fs->m);
1314                                 fs->m = NULL;
1315                                 /*
1316                                  * XXX - we cannot just fall out at this
1317                                  * point, m has been freed and is invalid!
1318                                  */
1319                         }
1320                 }
1321
1322                 /*
1323                  * We get here if the object has a default pager (or unwiring) 
1324                  * or the pager doesn't have the page.
1325                  */
1326                 if (fs->object == fs->first_object)
1327                         fs->first_m = fs->m;
1328
1329                 /*
1330                  * Move on to the next object.  Lock the next object before
1331                  * unlocking the current one.
1332                  */
1333                 pindex += OFF_TO_IDX(fs->object->backing_object_offset);
1334                 next_object = fs->object->backing_object;
1335                 if (next_object == NULL) {
1336                         /*
1337                          * If there's no object left, fill the page in the top
1338                          * object with zeros.
1339                          */
1340                         if (fs->object != fs->first_object) {
1341                                 vm_object_pip_wakeup(fs->object);
1342
1343                                 fs->object = fs->first_object;
1344                                 pindex = first_pindex;
1345                                 fs->m = fs->first_m;
1346                         }
1347                         fs->first_m = NULL;
1348
1349                         /*
1350                          * Zero the page if necessary and mark it valid.
1351                          */
1352                         if ((fs->m->flags & PG_ZERO) == 0) {
1353                                 vm_page_zero_fill(fs->m);
1354                         } else {
1355                                 mycpu->gd_cnt.v_ozfod++;
1356                         }
1357                         mycpu->gd_cnt.v_zfod++;
1358                         fs->m->valid = VM_PAGE_BITS_ALL;
1359                         break;  /* break to PAGE HAS BEEN FOUND */
1360                 }
1361                 if (fs->object != fs->first_object) {
1362                         vm_object_pip_wakeup(fs->object);
1363                 }
1364                 KASSERT(fs->object != next_object,
1365                         ("object loop %p", next_object));
1366                 fs->object = next_object;
1367                 vm_object_pip_add(fs->object, 1);
1368         }
1369
1370         /*
1371          * PAGE HAS BEEN FOUND. [Loop invariant still holds -- the object lock
1372          * is held.]
1373          *
1374          * vm_token is still held
1375          *
1376          * If the page is being written, but isn't already owned by the
1377          * top-level object, we have to copy it into a new page owned by the
1378          * top-level object.
1379          */
1380         KASSERT((fs->m->flags & PG_BUSY) != 0,
1381                 ("vm_fault: not busy after main loop"));
1382
1383         if (fs->object != fs->first_object) {
1384                 /*
1385                  * We only really need to copy if we want to write it.
1386                  */
1387                 if (fault_type & VM_PROT_WRITE) {
1388                         /*
1389                          * This allows pages to be virtually copied from a 
1390                          * backing_object into the first_object, where the 
1391                          * backing object has no other refs to it, and cannot
1392                          * gain any more refs.  Instead of a bcopy, we just 
1393                          * move the page from the backing object to the 
1394                          * first object.  Note that we must mark the page 
1395                          * dirty in the first object so that it will go out 
1396                          * to swap when needed.
1397                          */
1398                         if (
1399                                 /*
1400                                  * Map, if present, has not changed
1401                                  */
1402                                 (fs->map == NULL ||
1403                                 fs->map_generation == fs->map->timestamp) &&
1404                                 /*
1405                                  * Only one shadow object
1406                                  */
1407                                 (fs->object->shadow_count == 1) &&
1408                                 /*
1409                                  * No COW refs, except us
1410                                  */
1411                                 (fs->object->ref_count == 1) &&
1412                                 /*
1413                                  * No one else can look this object up
1414                                  */
1415                                 (fs->object->handle == NULL) &&
1416                                 /*
1417                                  * No other ways to look the object up
1418                                  */
1419                                 ((fs->object->type == OBJT_DEFAULT) ||
1420                                  (fs->object->type == OBJT_SWAP)) &&
1421                                 /*
1422                                  * We don't chase down the shadow chain
1423                                  */
1424                                 (fs->object == fs->first_object->backing_object) &&
1425
1426                                 /*
1427                                  * grab the lock if we need to
1428                                  */
1429                                 (fs->lookup_still_valid ||
1430                                  fs->map == NULL ||
1431                                  lockmgr(&fs->map->lock, LK_EXCLUSIVE|LK_NOWAIT) == 0)
1432                             ) {
1433                                 
1434                                 fs->lookup_still_valid = 1;
1435                                 /*
1436                                  * get rid of the unnecessary page
1437                                  */
1438                                 vm_page_protect(fs->first_m, VM_PROT_NONE);
1439                                 vm_page_free(fs->first_m);
1440                                 fs->first_m = NULL;
1441
1442                                 /*
1443                                  * grab the page and put it into the 
1444                                  * process'es object.  The page is 
1445                                  * automatically made dirty.
1446                                  */
1447                                 vm_page_rename(fs->m, fs->first_object, first_pindex);
1448                                 fs->first_m = fs->m;
1449                                 vm_page_busy(fs->first_m);
1450                                 fs->m = NULL;
1451                                 mycpu->gd_cnt.v_cow_optim++;
1452                         } else {
1453                                 /*
1454                                  * Oh, well, lets copy it.
1455                                  */
1456                                 vm_page_copy(fs->m, fs->first_m);
1457                                 vm_page_event(fs->m, VMEVENT_COW);
1458                         }
1459
1460                         if (fs->m) {
1461                                 /*
1462                                  * We no longer need the old page or object.
1463                                  */
1464                                 release_page(fs);
1465                         }
1466
1467                         /*
1468                          * fs->object != fs->first_object due to above 
1469                          * conditional
1470                          */
1471                         vm_object_pip_wakeup(fs->object);
1472
1473                         /*
1474                          * Only use the new page below...
1475                          */
1476
1477                         mycpu->gd_cnt.v_cow_faults++;
1478                         fs->m = fs->first_m;
1479                         fs->object = fs->first_object;
1480                         pindex = first_pindex;
1481                 } else {
1482                         /*
1483                          * If it wasn't a write fault avoid having to copy
1484                          * the page by mapping it read-only.
1485                          */
1486                         fs->prot &= ~VM_PROT_WRITE;
1487                 }
1488         }
1489
1490         /*
1491          * We may have had to unlock a map to do I/O.  If we did then
1492          * lookup_still_valid will be FALSE.  If the map generation count
1493          * also changed then all sorts of things could have happened while
1494          * we were doing the I/O and we need to retry.
1495          */
1496
1497         if (!fs->lookup_still_valid &&
1498             fs->map != NULL &&
1499             (fs->map->timestamp != fs->map_generation)) {
1500                 release_page(fs);
1501                 lwkt_reltoken(&vm_token);
1502                 unlock_and_deallocate(fs);
1503                 return (KERN_TRY_AGAIN);
1504         }
1505
1506         /*
1507          * If the fault is a write, we know that this page is being
1508          * written NOW so dirty it explicitly to save on pmap_is_modified()
1509          * calls later.
1510          *
1511          * If this is a NOSYNC mmap we do not want to set PG_NOSYNC
1512          * if the page is already dirty to prevent data written with
1513          * the expectation of being synced from not being synced.
1514          * Likewise if this entry does not request NOSYNC then make
1515          * sure the page isn't marked NOSYNC.  Applications sharing
1516          * data should use the same flags to avoid ping ponging.
1517          *
1518          * Also tell the backing pager, if any, that it should remove
1519          * any swap backing since the page is now dirty.
1520          */
1521         if (fs->prot & VM_PROT_WRITE) {
1522                 vm_object_set_writeable_dirty(fs->m->object);
1523                 if (fs->entry->eflags & MAP_ENTRY_NOSYNC) {
1524                         if (fs->m->dirty == 0)
1525                                 vm_page_flag_set(fs->m, PG_NOSYNC);
1526                 } else {
1527                         vm_page_flag_clear(fs->m, PG_NOSYNC);
1528                 }
1529                 if (fs->fault_flags & VM_FAULT_DIRTY) {
1530                         crit_enter();
1531                         vm_page_dirty(fs->m);
1532                         swap_pager_unswapped(fs->m);
1533                         crit_exit();
1534                 }
1535         }
1536
1537         lwkt_reltoken(&vm_token);
1538
1539         /*
1540          * Page had better still be busy.  We are still locked up and 
1541          * fs->object will have another PIP reference if it is not equal
1542          * to fs->first_object.
1543          */
1544         KASSERT(fs->m->flags & PG_BUSY,
1545                 ("vm_fault: page %p not busy!", fs->m));
1546
1547         /*
1548          * Sanity check: page must be completely valid or it is not fit to
1549          * map into user space.  vm_pager_get_pages() ensures this.
1550          */
1551         if (fs->m->valid != VM_PAGE_BITS_ALL) {
1552                 vm_page_zero_invalid(fs->m, TRUE);
1553                 kprintf("Warning: page %p partially invalid on fault\n", fs->m);
1554         }
1555
1556         return (KERN_SUCCESS);
1557 }
1558
1559 /*
1560  * Wire down a range of virtual addresses in a map.  The entry in question
1561  * should be marked in-transition and the map must be locked.  We must
1562  * release the map temporarily while faulting-in the page to avoid a
1563  * deadlock.  Note that the entry may be clipped while we are blocked but
1564  * will never be freed.
1565  *
1566  * No requirements.
1567  */
1568 int
1569 vm_fault_wire(vm_map_t map, vm_map_entry_t entry, boolean_t user_wire)
1570 {
1571         boolean_t fictitious;
1572         vm_offset_t start;
1573         vm_offset_t end;
1574         vm_offset_t va;
1575         vm_paddr_t pa;
1576         pmap_t pmap;
1577         int rv;
1578
1579         pmap = vm_map_pmap(map);
1580         start = entry->start;
1581         end = entry->end;
1582         fictitious = entry->object.vm_object &&
1583                         (entry->object.vm_object->type == OBJT_DEVICE);
1584
1585         lwkt_gettoken(&vm_token);
1586         vm_map_unlock(map);
1587         map->timestamp++;
1588
1589         /*
1590          * We simulate a fault to get the page and enter it in the physical
1591          * map.
1592          */
1593         for (va = start; va < end; va += PAGE_SIZE) {
1594                 if (user_wire) {
1595                         rv = vm_fault(map, va, VM_PROT_READ, 
1596                                         VM_FAULT_USER_WIRE);
1597                 } else {
1598                         rv = vm_fault(map, va, VM_PROT_READ|VM_PROT_WRITE,
1599                                         VM_FAULT_CHANGE_WIRING);
1600                 }
1601                 if (rv) {
1602                         while (va > start) {
1603                                 va -= PAGE_SIZE;
1604                                 if ((pa = pmap_extract(pmap, va)) == 0)
1605                                         continue;
1606                                 pmap_change_wiring(pmap, va, FALSE);
1607                                 if (!fictitious)
1608                                         vm_page_unwire(PHYS_TO_VM_PAGE(pa), 1);
1609                         }
1610                         vm_map_lock(map);
1611                         lwkt_reltoken(&vm_token);
1612                         return (rv);
1613                 }
1614         }
1615         vm_map_lock(map);
1616         lwkt_reltoken(&vm_token);
1617         return (KERN_SUCCESS);
1618 }
1619
1620 /*
1621  * Unwire a range of virtual addresses in a map.  The map should be
1622  * locked.
1623  */
1624 void
1625 vm_fault_unwire(vm_map_t map, vm_map_entry_t entry)
1626 {
1627         boolean_t fictitious;
1628         vm_offset_t start;
1629         vm_offset_t end;
1630         vm_offset_t va;
1631         vm_paddr_t pa;
1632         pmap_t pmap;
1633
1634         pmap = vm_map_pmap(map);
1635         start = entry->start;
1636         end = entry->end;
1637         fictitious = entry->object.vm_object &&
1638                         (entry->object.vm_object->type == OBJT_DEVICE);
1639
1640         /*
1641          * Since the pages are wired down, we must be able to get their
1642          * mappings from the physical map system.
1643          */
1644         lwkt_gettoken(&vm_token);
1645         for (va = start; va < end; va += PAGE_SIZE) {
1646                 pa = pmap_extract(pmap, va);
1647                 if (pa != 0) {
1648                         pmap_change_wiring(pmap, va, FALSE);
1649                         if (!fictitious)
1650                                 vm_page_unwire(PHYS_TO_VM_PAGE(pa), 1);
1651                 }
1652         }
1653         lwkt_reltoken(&vm_token);
1654 }
1655
1656 /*
1657  * Reduce the rate at which memory is allocated to a process based
1658  * on the perceived load on the VM system. As the load increases
1659  * the allocation burst rate goes down and the delay increases. 
1660  *
1661  * Rate limiting does not apply when faulting active or inactive
1662  * pages.  When faulting 'cache' pages, rate limiting only applies
1663  * if the system currently has a severe page deficit.
1664  *
1665  * XXX vm_pagesupply should be increased when a page is freed.
1666  *
1667  * We sleep up to 1/10 of a second.
1668  */
1669 static int
1670 vm_fault_ratelimit(struct vmspace *vmspace)
1671 {
1672         if (vm_load_enable == 0)
1673                 return(0);
1674         if (vmspace->vm_pagesupply > 0) {
1675                 --vmspace->vm_pagesupply;       /* SMP race ok */
1676                 return(0);
1677         }
1678 #ifdef INVARIANTS
1679         if (vm_load_debug) {
1680                 kprintf("load %-4d give %d pgs, wait %d, pid %-5d (%s)\n",
1681                         vm_load, 
1682                         (1000 - vm_load ) / 10, vm_load * hz / 10000,
1683                         curproc->p_pid, curproc->p_comm);
1684         }
1685 #endif
1686         vmspace->vm_pagesupply = (1000 - vm_load) / 10;
1687         return(vm_load * hz / 10000);
1688 }
1689
1690 /*
1691  * Copy all of the pages from a wired-down map entry to another.
1692  *
1693  * The source and destination maps must be locked for write.
1694  * The source map entry must be wired down (or be a sharing map
1695  * entry corresponding to a main map entry that is wired down).
1696  *
1697  * No other requirements.
1698  */
1699 void
1700 vm_fault_copy_entry(vm_map_t dst_map, vm_map_t src_map,
1701                     vm_map_entry_t dst_entry, vm_map_entry_t src_entry)
1702 {
1703         vm_object_t dst_object;
1704         vm_object_t src_object;
1705         vm_ooffset_t dst_offset;
1706         vm_ooffset_t src_offset;
1707         vm_prot_t prot;
1708         vm_offset_t vaddr;
1709         vm_page_t dst_m;
1710         vm_page_t src_m;
1711
1712 #ifdef  lint
1713         src_map++;
1714 #endif  /* lint */
1715
1716         src_object = src_entry->object.vm_object;
1717         src_offset = src_entry->offset;
1718
1719         /*
1720          * Create the top-level object for the destination entry. (Doesn't
1721          * actually shadow anything - we copy the pages directly.)
1722          */
1723         vm_map_entry_allocate_object(dst_entry);
1724         dst_object = dst_entry->object.vm_object;
1725
1726         prot = dst_entry->max_protection;
1727
1728         /*
1729          * Loop through all of the pages in the entry's range, copying each
1730          * one from the source object (it should be there) to the destination
1731          * object.
1732          */
1733         for (vaddr = dst_entry->start, dst_offset = 0;
1734             vaddr < dst_entry->end;
1735             vaddr += PAGE_SIZE, dst_offset += PAGE_SIZE) {
1736
1737                 /*
1738                  * Allocate a page in the destination object
1739                  */
1740                 do {
1741                         dst_m = vm_page_alloc(dst_object,
1742                                 OFF_TO_IDX(dst_offset), VM_ALLOC_NORMAL);
1743                         if (dst_m == NULL) {
1744                                 vm_wait(0);
1745                         }
1746                 } while (dst_m == NULL);
1747
1748                 /*
1749                  * Find the page in the source object, and copy it in.
1750                  * (Because the source is wired down, the page will be in
1751                  * memory.)
1752                  */
1753                 src_m = vm_page_lookup(src_object,
1754                         OFF_TO_IDX(dst_offset + src_offset));
1755                 if (src_m == NULL)
1756                         panic("vm_fault_copy_wired: page missing");
1757
1758                 vm_page_copy(src_m, dst_m);
1759                 vm_page_event(src_m, VMEVENT_COW);
1760
1761                 /*
1762                  * Enter it in the pmap...
1763                  */
1764
1765                 vm_page_flag_clear(dst_m, PG_ZERO);
1766                 pmap_enter(dst_map->pmap, vaddr, dst_m, prot, FALSE);
1767
1768                 /*
1769                  * Mark it no longer busy, and put it on the active list.
1770                  */
1771                 vm_page_activate(dst_m);
1772                 vm_page_wakeup(dst_m);
1773         }
1774 }
1775
1776 #if 0
1777
1778 /*
1779  * This routine checks around the requested page for other pages that
1780  * might be able to be faulted in.  This routine brackets the viable
1781  * pages for the pages to be paged in.
1782  *
1783  * Inputs:
1784  *      m, rbehind, rahead
1785  *
1786  * Outputs:
1787  *  marray (array of vm_page_t), reqpage (index of requested page)
1788  *
1789  * Return value:
1790  *  number of pages in marray
1791  */
1792 static int
1793 vm_fault_additional_pages(vm_page_t m, int rbehind, int rahead,
1794                           vm_page_t *marray, int *reqpage)
1795 {
1796         int i,j;
1797         vm_object_t object;
1798         vm_pindex_t pindex, startpindex, endpindex, tpindex;
1799         vm_page_t rtm;
1800         int cbehind, cahead;
1801
1802         object = m->object;
1803         pindex = m->pindex;
1804
1805         /*
1806          * we don't fault-ahead for device pager
1807          */
1808         if (object->type == OBJT_DEVICE) {
1809                 *reqpage = 0;
1810                 marray[0] = m;
1811                 return 1;
1812         }
1813
1814         /*
1815          * if the requested page is not available, then give up now
1816          */
1817         if (!vm_pager_has_page(object, pindex, &cbehind, &cahead)) {
1818                 *reqpage = 0;   /* not used by caller, fix compiler warn */
1819                 return 0;
1820         }
1821
1822         if ((cbehind == 0) && (cahead == 0)) {
1823                 *reqpage = 0;
1824                 marray[0] = m;
1825                 return 1;
1826         }
1827
1828         if (rahead > cahead) {
1829                 rahead = cahead;
1830         }
1831
1832         if (rbehind > cbehind) {
1833                 rbehind = cbehind;
1834         }
1835
1836         /*
1837          * Do not do any readahead if we have insufficient free memory.
1838          *
1839          * XXX code was broken disabled before and has instability
1840          * with this conditonal fixed, so shortcut for now.
1841          */
1842         if (burst_fault == 0 || vm_page_count_severe()) {
1843                 marray[0] = m;
1844                 *reqpage = 0;
1845                 return 1;
1846         }
1847
1848         /*
1849          * scan backward for the read behind pages -- in memory 
1850          *
1851          * Assume that if the page is not found an interrupt will not
1852          * create it.  Theoretically interrupts can only remove (busy)
1853          * pages, not create new associations.
1854          */
1855         if (pindex > 0) {
1856                 if (rbehind > pindex) {
1857                         rbehind = pindex;
1858                         startpindex = 0;
1859                 } else {
1860                         startpindex = pindex - rbehind;
1861                 }
1862
1863                 crit_enter();
1864                 lwkt_gettoken(&vm_token);
1865                 for (tpindex = pindex; tpindex > startpindex; --tpindex) {
1866                         if (vm_page_lookup(object, tpindex - 1))
1867                                 break;
1868                 }
1869
1870                 i = 0;
1871                 while (tpindex < pindex) {
1872                         rtm = vm_page_alloc(object, tpindex, VM_ALLOC_SYSTEM);
1873                         if (rtm == NULL) {
1874                                 lwkt_reltoken(&vm_token);
1875                                 crit_exit();
1876                                 for (j = 0; j < i; j++) {
1877                                         vm_page_free(marray[j]);
1878                                 }
1879                                 marray[0] = m;
1880                                 *reqpage = 0;
1881                                 return 1;
1882                         }
1883                         marray[i] = rtm;
1884                         ++i;
1885                         ++tpindex;
1886                 }
1887                 lwkt_reltoken(&vm_token);
1888                 crit_exit();
1889         } else {
1890                 i = 0;
1891         }
1892
1893         /*
1894          * Assign requested page
1895          */
1896         marray[i] = m;
1897         *reqpage = i;
1898         ++i;
1899
1900         /*
1901          * Scan forwards for read-ahead pages
1902          */
1903         tpindex = pindex + 1;
1904         endpindex = tpindex + rahead;
1905         if (endpindex > object->size)
1906                 endpindex = object->size;
1907
1908         crit_enter();
1909         lwkt_gettoken(&vm_token);
1910         while (tpindex < endpindex) {
1911                 if (vm_page_lookup(object, tpindex))
1912                         break;
1913                 rtm = vm_page_alloc(object, tpindex, VM_ALLOC_SYSTEM);
1914                 if (rtm == NULL)
1915                         break;
1916                 marray[i] = rtm;
1917                 ++i;
1918                 ++tpindex;
1919         }
1920         lwkt_reltoken(&vm_token);
1921         crit_exit();
1922
1923         return (i);
1924 }
1925
1926 #endif
1927
1928 /*
1929  * vm_prefault() provides a quick way of clustering pagefaults into a
1930  * processes address space.  It is a "cousin" of pmap_object_init_pt,
1931  * except it runs at page fault time instead of mmap time.
1932  *
1933  * This code used to be per-platform pmap_prefault().  It is now
1934  * machine-independent and enhanced to also pre-fault zero-fill pages
1935  * (see vm.fast_fault) as well as make them writable, which greatly
1936  * reduces the number of page faults programs incur.
1937  *
1938  * Application performance when pre-faulting zero-fill pages is heavily
1939  * dependent on the application.  Very tiny applications like /bin/echo
1940  * lose a little performance while applications of any appreciable size
1941  * gain performance.  Prefaulting multiple pages also reduces SMP
1942  * congestion and can improve SMP performance significantly.
1943  *
1944  * NOTE!  prot may allow writing but this only applies to the top level
1945  *        object.  If we wind up mapping a page extracted from a backing
1946  *        object we have to make sure it is read-only.
1947  *
1948  * NOTE!  The caller has already handled any COW operations on the
1949  *        vm_map_entry via the normal fault code.  Do NOT call this
1950  *        shortcut unless the normal fault code has run on this entry.
1951  *
1952  * No other requirements.
1953  */
1954 #define PFBAK 4
1955 #define PFFOR 4
1956 #define PAGEORDER_SIZE (PFBAK+PFFOR)
1957
1958 static int vm_prefault_pageorder[] = {
1959         -PAGE_SIZE, PAGE_SIZE,
1960         -2 * PAGE_SIZE, 2 * PAGE_SIZE,
1961         -3 * PAGE_SIZE, 3 * PAGE_SIZE,
1962         -4 * PAGE_SIZE, 4 * PAGE_SIZE
1963 };
1964
1965 static void
1966 vm_prefault(pmap_t pmap, vm_offset_t addra, vm_map_entry_t entry, int prot)
1967 {
1968         struct lwp *lp;
1969         vm_page_t m;
1970         vm_offset_t starta;
1971         vm_offset_t addr;
1972         vm_pindex_t index;
1973         vm_pindex_t pindex;
1974         vm_object_t object;
1975         int pprot;
1976         int i;
1977
1978         /*
1979          * We do not currently prefault mappings that use virtual page
1980          * tables.  We do not prefault foreign pmaps.
1981          */
1982         if (entry->maptype == VM_MAPTYPE_VPAGETABLE)
1983                 return;
1984         lp = curthread->td_lwp;
1985         if (lp == NULL || (pmap != vmspace_pmap(lp->lwp_vmspace)))
1986                 return;
1987
1988         object = entry->object.vm_object;
1989
1990         starta = addra - PFBAK * PAGE_SIZE;
1991         if (starta < entry->start)
1992                 starta = entry->start;
1993         else if (starta > addra)
1994                 starta = 0;
1995
1996         /*
1997          * critical section protection is required to maintain the
1998          * page/object association, interrupts can free pages and remove
1999          * them from their objects.
2000          */
2001         crit_enter();
2002         lwkt_gettoken(&vm_token);
2003         for (i = 0; i < PAGEORDER_SIZE; i++) {
2004                 vm_object_t lobject;
2005                 int allocated = 0;
2006
2007                 addr = addra + vm_prefault_pageorder[i];
2008                 if (addr > addra + (PFFOR * PAGE_SIZE))
2009                         addr = 0;
2010
2011                 if (addr < starta || addr >= entry->end)
2012                         continue;
2013
2014                 if (pmap_prefault_ok(pmap, addr) == 0)
2015                         continue;
2016
2017                 /*
2018                  * Follow the VM object chain to obtain the page to be mapped
2019                  * into the pmap.
2020                  *
2021                  * If we reach the terminal object without finding a page
2022                  * and we determine it would be advantageous, then allocate
2023                  * a zero-fill page for the base object.  The base object
2024                  * is guaranteed to be OBJT_DEFAULT for this case.
2025                  *
2026                  * In order to not have to check the pager via *haspage*()
2027                  * we stop if any non-default object is encountered.  e.g.
2028                  * a vnode or swap object would stop the loop.
2029                  */
2030                 index = ((addr - entry->start) + entry->offset) >> PAGE_SHIFT;
2031                 lobject = object;
2032                 pindex = index;
2033                 pprot = prot;
2034
2035                 while ((m = vm_page_lookup(lobject, pindex)) == NULL) {
2036                         if (lobject->type != OBJT_DEFAULT)
2037                                 break;
2038                         if (lobject->backing_object == NULL) {
2039                                 if (vm_fast_fault == 0)
2040                                         break;
2041                                 if (vm_prefault_pageorder[i] < 0 ||
2042                                     (prot & VM_PROT_WRITE) == 0 ||
2043                                     vm_page_count_min(0)) {
2044                                         break;
2045                                 }
2046                                 /* note: allocate from base object */
2047                                 m = vm_page_alloc(object, index,
2048                                               VM_ALLOC_NORMAL | VM_ALLOC_ZERO);
2049
2050                                 if ((m->flags & PG_ZERO) == 0) {
2051                                         vm_page_zero_fill(m);
2052                                 } else {
2053                                         vm_page_flag_clear(m, PG_ZERO);
2054                                         mycpu->gd_cnt.v_ozfod++;
2055                                 }
2056                                 mycpu->gd_cnt.v_zfod++;
2057                                 m->valid = VM_PAGE_BITS_ALL;
2058                                 allocated = 1;
2059                                 pprot = prot;
2060                                 /* lobject = object .. not needed */
2061                                 break;
2062                         }
2063                         if (lobject->backing_object_offset & PAGE_MASK)
2064                                 break;
2065                         pindex += lobject->backing_object_offset >> PAGE_SHIFT;
2066                         lobject = lobject->backing_object;
2067                         pprot &= ~VM_PROT_WRITE;
2068                 }
2069                 /*
2070                  * NOTE: lobject now invalid (if we did a zero-fill we didn't
2071                  *       bother assigning lobject = object).
2072                  *
2073                  * Give-up if the page is not available.
2074                  */
2075                 if (m == NULL)
2076                         break;
2077
2078                 /*
2079                  * Do not conditionalize on PG_RAM.  If pages are present in
2080                  * the VM system we assume optimal caching.  If caching is
2081                  * not optimal the I/O gravy train will be restarted when we
2082                  * hit an unavailable page.  We do not want to try to restart
2083                  * the gravy train now because we really don't know how much
2084                  * of the object has been cached.  The cost for restarting
2085                  * the gravy train should be low (since accesses will likely
2086                  * be I/O bound anyway).
2087                  *
2088                  * The object must be marked dirty if we are mapping a
2089                  * writable page.
2090                  */
2091                 if (pprot & VM_PROT_WRITE)
2092                         vm_object_set_writeable_dirty(m->object);
2093
2094                 /*
2095                  * Enter the page into the pmap if appropriate.  If we had
2096                  * allocated the page we have to place it on a queue.  If not
2097                  * we just have to make sure it isn't on the cache queue
2098                  * (pages on the cache queue are not allowed to be mapped).
2099                  */
2100                 if (allocated) {
2101                         pmap_enter(pmap, addr, m, pprot, 0);
2102                         vm_page_deactivate(m);
2103                         vm_page_wakeup(m);
2104                 } else if (((m->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
2105                     (m->busy == 0) &&
2106                     (m->flags & (PG_BUSY | PG_FICTITIOUS)) == 0) {
2107
2108                         if ((m->queue - m->pc) == PQ_CACHE) {
2109                                 vm_page_deactivate(m);
2110                         }
2111                         vm_page_busy(m);
2112                         pmap_enter(pmap, addr, m, pprot, 0);
2113                         vm_page_wakeup(m);
2114                 }
2115         }
2116         lwkt_reltoken(&vm_token);
2117         crit_exit();
2118 }