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