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