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