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