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