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