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