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