Merge branch 'vendor/BZIP'
[dragonfly.git] / sys / vm / vm_fault.c
1 /*
2  * Copyright (c) 2003-2020 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/swap_pager.h>
127 #include <vm/vm_extern.h>
128
129 #include <vm/vm_page2.h>
130
131 #define VM_FAULT_MAX_QUICK      16
132
133 struct faultstate {
134         vm_page_t mary[VM_FAULT_MAX_QUICK];
135         vm_map_backing_t ba;
136         vm_prot_t prot;
137         vm_page_t first_m;
138         vm_map_backing_t first_ba;
139         vm_prot_t first_prot;
140         vm_map_t map;
141         vm_map_entry_t entry;
142         int lookup_still_valid; /* 0=inv 1=valid/rel -1=valid/atomic */
143         int hardfault;
144         int fault_flags;
145         int shared;
146         int msoftonly;
147         int first_shared;
148         int wflags;
149         int first_ba_held;      /* 0=unlocked 1=locked/rel -1=lock/atomic */
150         struct vnode *vp;
151 };
152
153 __read_mostly static int debug_fault = 0;
154 SYSCTL_INT(_vm, OID_AUTO, debug_fault, CTLFLAG_RW, &debug_fault, 0, "");
155 __read_mostly static int debug_cluster = 0;
156 SYSCTL_INT(_vm, OID_AUTO, debug_cluster, CTLFLAG_RW, &debug_cluster, 0, "");
157 #if 0
158 static int virtual_copy_enable = 1;
159 SYSCTL_INT(_vm, OID_AUTO, virtual_copy_enable, CTLFLAG_RW,
160                 &virtual_copy_enable, 0, "");
161 #endif
162 __read_mostly int vm_shared_fault = 1;
163 TUNABLE_INT("vm.shared_fault", &vm_shared_fault);
164 SYSCTL_INT(_vm, OID_AUTO, shared_fault, CTLFLAG_RW,
165                 &vm_shared_fault, 0, "Allow shared token on vm_object");
166 __read_mostly static int vm_fault_bypass_count = 1;
167 TUNABLE_INT("vm.fault_bypass", &vm_fault_bypass_count);
168 SYSCTL_INT(_vm, OID_AUTO, fault_bypass, CTLFLAG_RW,
169                 &vm_fault_bypass_count, 0, "Allow fast vm_fault shortcut");
170
171 /*
172  * Define here for debugging ioctls.  Note that these are globals, so
173  * they were cause a ton of cache line bouncing.  Only use for debugging
174  * purposes.
175  */
176 /*#define VM_FAULT_QUICK_DEBUG */
177 #ifdef VM_FAULT_QUICK_DEBUG
178 static long vm_fault_bypass_success_count = 0;
179 SYSCTL_LONG(_vm, OID_AUTO, fault_bypass_success_count, CTLFLAG_RW,
180                 &vm_fault_bypass_success_count, 0, "");
181 static long vm_fault_bypass_failure_count1 = 0;
182 SYSCTL_LONG(_vm, OID_AUTO, fault_bypass_failure_count1, CTLFLAG_RW,
183                 &vm_fault_bypass_failure_count1, 0, "");
184 static long vm_fault_bypass_failure_count2 = 0;
185 SYSCTL_LONG(_vm, OID_AUTO, fault_bypass_failure_count2, CTLFLAG_RW,
186                 &vm_fault_bypass_failure_count2, 0, "");
187 static long vm_fault_bypass_failure_count3 = 0;
188 SYSCTL_LONG(_vm, OID_AUTO, fault_bypass_failure_count3, CTLFLAG_RW,
189                 &vm_fault_bypass_failure_count3, 0, "");
190 static long vm_fault_bypass_failure_count4 = 0;
191 SYSCTL_LONG(_vm, OID_AUTO, fault_bypass_failure_count4, CTLFLAG_RW,
192                 &vm_fault_bypass_failure_count4, 0, "");
193 #endif
194
195 static int vm_fault_bypass(struct faultstate *fs, vm_pindex_t first_pindex,
196                         vm_pindex_t first_count, int *mextcountp,
197                         vm_prot_t fault_type);
198 static int vm_fault_object(struct faultstate *, vm_pindex_t, vm_prot_t, int);
199 static int vm_fault_vpagetable(struct faultstate *, vm_pindex_t *,
200                         vpte_t, int, int);
201 #if 0
202 static int vm_fault_additional_pages (vm_page_t, int, int, vm_page_t *, int *);
203 #endif
204 static void vm_set_nosync(vm_page_t m, vm_map_entry_t entry);
205 static void vm_prefault(pmap_t pmap, vm_offset_t addra,
206                         vm_map_entry_t entry, int prot, int fault_flags);
207 static void vm_prefault_quick(pmap_t pmap, vm_offset_t addra,
208                         vm_map_entry_t entry, int prot, int fault_flags);
209
210 static __inline void
211 release_page(struct faultstate *fs)
212 {
213         vm_page_deactivate(fs->mary[0]);
214         vm_page_wakeup(fs->mary[0]);
215         fs->mary[0] = NULL;
216 }
217
218 static __inline void
219 unlock_map(struct faultstate *fs)
220 {
221         if (fs->ba != fs->first_ba)
222                 vm_object_drop(fs->ba->object);
223         if (fs->first_ba && fs->first_ba_held == 1) {
224                 vm_object_drop(fs->first_ba->object);
225                 fs->first_ba_held = 0;
226                 fs->first_ba = NULL;
227         }
228         fs->ba = NULL;
229
230         /*
231          * NOTE: If lookup_still_valid == -1 the map is assumed to be locked
232          *       and caller expects it to remain locked atomically.
233          */
234         if (fs->lookup_still_valid == 1 && fs->map) {
235                 vm_map_lookup_done(fs->map, fs->entry, 0);
236                 fs->lookup_still_valid = 0;
237                 fs->entry = NULL;
238         }
239 }
240
241 /*
242  * Clean up after a successful call to vm_fault_object() so another call
243  * to vm_fault_object() can be made.
244  */
245 static void
246 cleanup_fault(struct faultstate *fs)
247 {
248         /*
249          * We allocated a junk page for a COW operation that did
250          * not occur, the page must be freed.
251          */
252         if (fs->ba != fs->first_ba) {
253                 KKASSERT(fs->first_shared == 0);
254
255                 /*
256                  * first_m could be completely valid and we got here
257                  * because of a PG_RAM, don't mistakenly free it!
258                  */
259                 if ((fs->first_m->valid & VM_PAGE_BITS_ALL) ==
260                     VM_PAGE_BITS_ALL) {
261                         vm_page_wakeup(fs->first_m);
262                 } else {
263                         vm_page_free(fs->first_m);
264                 }
265                 vm_object_pip_wakeup(fs->ba->object);
266                 fs->first_m = NULL;
267
268                 /*
269                  * Reset fs->ba (used by vm_fault_vpagetahble() without
270                  * calling unlock_map(), so we need a little duplication.
271                  */
272                 vm_object_drop(fs->ba->object);
273                 fs->ba = fs->first_ba;
274         }
275 }
276
277 static void
278 unlock_things(struct faultstate *fs)
279 {
280         cleanup_fault(fs);
281         unlock_map(fs); 
282         if (fs->vp != NULL) { 
283                 vput(fs->vp);
284                 fs->vp = NULL;
285         }
286 }
287
288 #if 0
289 /*
290  * Virtual copy tests.   Used by the fault code to determine if a
291  * page can be moved from an orphan vm_object into its shadow
292  * instead of copying its contents.
293  */
294 static __inline int
295 virtual_copy_test(struct faultstate *fs)
296 {
297         /*
298          * Must be holding exclusive locks
299          */
300         if (fs->first_shared || fs->shared || virtual_copy_enable == 0)
301                 return 0;
302
303         /*
304          * Map, if present, has not changed
305          */
306         if (fs->map && fs->map_generation != fs->map->timestamp)
307                 return 0;
308
309         /*
310          * No refs, except us
311          */
312         if (fs->ba->object->ref_count != 1)
313                 return 0;
314
315         /*
316          * No one else can look this object up
317          */
318         if (fs->ba->object->handle != NULL)
319                 return 0;
320
321         /*
322          * No other ways to look the object up
323          */
324         if (fs->ba->object->type != OBJT_DEFAULT &&
325             fs->ba->object->type != OBJT_SWAP)
326                 return 0;
327
328         /*
329          * We don't chase down the shadow chain
330          */
331         if (fs->ba != fs->first_ba->backing_ba)
332                 return 0;
333
334         return 1;
335 }
336
337 static __inline int
338 virtual_copy_ok(struct faultstate *fs)
339 {
340         if (virtual_copy_test(fs)) {
341                 /*
342                  * Grab the lock and re-test changeable items.
343                  */
344                 if (fs->lookup_still_valid == 0 && fs->map) {
345                         if (lockmgr(&fs->map->lock, LK_EXCLUSIVE|LK_NOWAIT))
346                                 return 0;
347                         fs->lookup_still_valid = 1;
348                         if (virtual_copy_test(fs)) {
349                                 fs->map_generation = ++fs->map->timestamp;
350                                 return 1;
351                         }
352                         fs->lookup_still_valid = 0;
353                         lockmgr(&fs->map->lock, LK_RELEASE);
354                 }
355         }
356         return 0;
357 }
358 #endif
359
360 /*
361  * TRYPAGER 
362  *
363  * Determine if the pager for the current object *might* contain the page.
364  *
365  * We only need to try the pager if this is not a default object (default
366  * objects are zero-fill and have no real pager), and if we are not taking
367  * a wiring fault or if the FS entry is wired.
368  */
369 #define TRYPAGER(fs)    \
370                 (fs->ba->object->type != OBJT_DEFAULT &&                \
371                 (((fs->fault_flags & VM_FAULT_WIRE_MASK) == 0) ||       \
372                  (fs->wflags & FW_WIRED)))
373
374 /*
375  * vm_fault:
376  *
377  * Handle a page fault occuring at the given address, requiring the given
378  * permissions, in the map specified.  If successful, the page is inserted
379  * into the associated physical map.
380  *
381  * NOTE: The given address should be truncated to the proper page address.
382  *
383  * KERN_SUCCESS is returned if the page fault is handled; otherwise,
384  * a standard error specifying why the fault is fatal is returned.
385  *
386  * The map in question must be referenced, and remains so.
387  * The caller may hold no locks.
388  * No other requirements.
389  */
390 int
391 vm_fault(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type, int fault_flags)
392 {
393         vm_pindex_t first_pindex;
394         vm_pindex_t first_count;
395         struct faultstate fs;
396         struct lwp *lp;
397         struct proc *p;
398         thread_t td;
399         struct vm_map_ilock ilock;
400         int mextcount;
401         int didilock;
402         int growstack;
403         int retry = 0;
404         int inherit_prot;
405         int result;
406         int n;
407
408         inherit_prot = fault_type & VM_PROT_NOSYNC;
409         fs.hardfault = 0;
410         fs.fault_flags = fault_flags;
411         fs.vp = NULL;
412         fs.shared = vm_shared_fault;
413         fs.first_shared = vm_shared_fault;
414         growstack = 1;
415
416         /*
417          * vm_map interactions
418          */
419         td = curthread;
420         if ((lp = td->td_lwp) != NULL)
421                 lp->lwp_flags |= LWP_PAGING;
422
423 RetryFault:
424         /*
425          * vm_fault_bypass() can shortcut us.
426          */
427         fs.msoftonly = 0;
428         fs.first_ba_held = 0;
429         mextcount = 1;
430
431         /*
432          * Find the vm_map_entry representing the backing store and resolve
433          * the top level object and page index.  This may have the side
434          * effect of executing a copy-on-write on the map entry,
435          * creating a shadow object, or splitting an anonymous entry for
436          * performance, but will not COW any actual VM pages.
437          *
438          * On success fs.map is left read-locked and various other fields 
439          * are initialized but not otherwise referenced or locked.
440          *
441          * NOTE!  vm_map_lookup will try to upgrade the fault_type to
442          *        VM_FAULT_WRITE if the map entry is a virtual page table
443          *        and also writable, so we can set the 'A'accessed bit in
444          *        the virtual page table entry.
445          */
446         fs.map = map;
447         result = vm_map_lookup(&fs.map, vaddr, fault_type,
448                                &fs.entry, &fs.first_ba,
449                                &first_pindex, &first_count,
450                                &fs.first_prot, &fs.wflags);
451
452         /*
453          * If the lookup failed or the map protections are incompatible,
454          * the fault generally fails.
455          *
456          * The failure could be due to TDF_NOFAULT if vm_map_lookup()
457          * tried to do a COW fault.
458          *
459          * If the caller is trying to do a user wiring we have more work
460          * to do.
461          */
462         if (result != KERN_SUCCESS) {
463                 if (result == KERN_FAILURE_NOFAULT) {
464                         result = KERN_FAILURE;
465                         goto done;
466                 }
467                 if (result != KERN_PROTECTION_FAILURE ||
468                     (fs.fault_flags & VM_FAULT_WIRE_MASK) != VM_FAULT_USER_WIRE)
469                 {
470                         if (result == KERN_INVALID_ADDRESS && growstack &&
471                             map != &kernel_map && curproc != NULL) {
472                                 result = vm_map_growstack(map, vaddr);
473                                 if (result == KERN_SUCCESS) {
474                                         growstack = 0;
475                                         ++retry;
476                                         goto RetryFault;
477                                 }
478                                 result = KERN_FAILURE;
479                         }
480                         goto done;
481                 }
482
483                 /*
484                  * If we are user-wiring a r/w segment, and it is COW, then
485                  * we need to do the COW operation.  Note that we don't
486                  * currently COW RO sections now, because it is NOT desirable
487                  * to COW .text.  We simply keep .text from ever being COW'ed
488                  * and take the heat that one cannot debug wired .text sections.
489                  *
490                  * XXX Try to allow the above by specifying OVERRIDE_WRITE.
491                  */
492                 result = vm_map_lookup(&fs.map, vaddr,
493                                        VM_PROT_READ|VM_PROT_WRITE|
494                                         VM_PROT_OVERRIDE_WRITE,
495                                        &fs.entry, &fs.first_ba,
496                                        &first_pindex, &first_count,
497                                        &fs.first_prot, &fs.wflags);
498                 if (result != KERN_SUCCESS) {
499                         /* could also be KERN_FAILURE_NOFAULT */
500                         result = KERN_FAILURE;
501                         goto done;
502                 }
503
504                 /*
505                  * If we don't COW now, on a user wire, the user will never
506                  * be able to write to the mapping.  If we don't make this
507                  * restriction, the bookkeeping would be nearly impossible.
508                  *
509                  * XXX We have a shared lock, this will have a MP race but
510                  * I don't see how it can hurt anything.
511                  */
512                 if ((fs.entry->protection & VM_PROT_WRITE) == 0) {
513                         atomic_clear_char(&fs.entry->max_protection,
514                                           VM_PROT_WRITE);
515                 }
516         }
517
518         /*
519          * fs.map is read-locked
520          *
521          * Misc checks.  Save the map generation number to detect races.
522          */
523         fs.lookup_still_valid = 1;
524         fs.first_m = NULL;
525         fs.ba = fs.first_ba;            /* so unlock_things() works */
526         fs.prot = fs.first_prot;        /* default (used by uksmap) */
527
528         if (fs.entry->eflags & (MAP_ENTRY_NOFAULT | MAP_ENTRY_KSTACK)) {
529                 if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
530                         panic("vm_fault: fault on nofault entry, addr: %p",
531                               (void *)vaddr);
532                 }
533                 if ((fs.entry->eflags & MAP_ENTRY_KSTACK) &&
534                     vaddr >= fs.entry->ba.start &&
535                     vaddr < fs.entry->ba.start + PAGE_SIZE) {
536                         panic("vm_fault: fault on stack guard, addr: %p",
537                               (void *)vaddr);
538                 }
539         }
540
541         /*
542          * A user-kernel shared map has no VM object and bypasses
543          * everything.  We execute the uksmap function with a temporary
544          * fictitious vm_page.  The address is directly mapped with no
545          * management.
546          */
547         if (fs.entry->maptype == VM_MAPTYPE_UKSMAP) {
548                 struct vm_page fakem;
549
550                 bzero(&fakem, sizeof(fakem));
551                 fakem.pindex = first_pindex;
552                 fakem.flags = PG_FICTITIOUS | PG_UNQUEUED;
553                 fakem.busy_count = PBUSY_LOCKED;
554                 fakem.valid = VM_PAGE_BITS_ALL;
555                 fakem.pat_mode = VM_MEMATTR_DEFAULT;
556                 if (fs.entry->ba.uksmap(&fs.entry->ba, UKSMAPOP_FAULT,
557                                         fs.entry->aux.dev, &fakem)) {
558                         result = KERN_FAILURE;
559                         unlock_things(&fs);
560                         goto done2;
561                 }
562                 pmap_enter(fs.map->pmap, vaddr, &fakem, fs.prot | inherit_prot,
563                            (fs.wflags & FW_WIRED), fs.entry);
564                 goto done_success;
565         }
566
567         /*
568          * A system map entry may return a NULL object.  No object means
569          * no pager means an unrecoverable kernel fault.
570          */
571         if (fs.first_ba == NULL) {
572                 panic("vm_fault: unrecoverable fault at %p in entry %p",
573                         (void *)vaddr, fs.entry);
574         }
575
576         /*
577          * Fail here if not a trivial anonymous page fault and TDF_NOFAULT
578          * is set.
579          *
580          * Unfortunately a deadlock can occur if we are forced to page-in
581          * from swap, but diving all the way into the vm_pager_get_page()
582          * function to find out is too much.  Just check the object type.
583          *
584          * The deadlock is a CAM deadlock on a busy VM page when trying
585          * to finish an I/O if another process gets stuck in
586          * vop_helper_read_shortcut() due to a swap fault.
587          */
588         if ((td->td_flags & TDF_NOFAULT) &&
589             (retry ||
590              fs.first_ba->object->type == OBJT_VNODE ||
591              fs.first_ba->object->type == OBJT_SWAP ||
592              fs.first_ba->backing_ba)) {
593                 result = KERN_FAILURE;
594                 unlock_things(&fs);
595                 goto done2;
596         }
597
598         /*
599          * If the entry is wired we cannot change the page protection.
600          */
601         if (fs.wflags & FW_WIRED)
602                 fault_type = fs.first_prot;
603
604         /*
605          * We generally want to avoid unnecessary exclusive modes on backing
606          * and terminal objects because this can seriously interfere with
607          * heavily fork()'d processes (particularly /bin/sh scripts).
608          *
609          * However, we also want to avoid unnecessary retries due to needed
610          * shared->exclusive promotion for common faults.  Exclusive mode is
611          * always needed if any page insertion, rename, or free occurs in an
612          * object (and also indirectly if any I/O is done).
613          *
614          * The main issue here is going to be fs.first_shared.  If the
615          * first_object has a backing object which isn't shadowed and the
616          * process is single-threaded we might as well use an exclusive
617          * lock/chain right off the bat.
618          */
619 #if 0
620         /* WORK IN PROGRESS, CODE REMOVED */
621         if (fs.first_shared && fs.first_object->backing_object &&
622             LIST_EMPTY(&fs.first_object->shadow_head) &&
623             td->td_proc && td->td_proc->p_nthreads == 1) {
624                 fs.first_shared = 0;
625         }
626 #endif
627
628         /*
629          * VM_FAULT_UNSWAP - swap_pager_unswapped() needs an exclusive object
630          * VM_FAULT_DIRTY  - may require swap_pager_unswapped() later, but
631          *                   we can try shared first.
632          */
633         if (fault_flags & VM_FAULT_UNSWAP)
634                 fs.first_shared = 0;
635
636         /*
637          * Try to shortcut the entire mess and run the fault lockless.
638          * This will burst in multiple pages via fs->mary[].
639          */
640         if (vm_fault_bypass_count &&
641             vm_fault_bypass(&fs, first_pindex, first_count,
642                            &mextcount, fault_type) == KERN_SUCCESS) {
643                 didilock = 0;
644                 fault_flags &= ~VM_FAULT_BURST;
645                 goto success;
646         }
647
648         /*
649          * Exclusive heuristic (alloc page vs page exists)
650          */
651         if (fs.first_ba->flags & VM_MAP_BACK_EXCL_HEUR)
652                 fs.first_shared = 0;
653
654         /*
655          * Obtain a top-level object lock, shared or exclusive depending
656          * on fs.first_shared.  If a shared lock winds up being insufficient
657          * we will retry with an exclusive lock.
658          *
659          * The vnode pager lock is always shared.
660          */
661         if (fs.first_shared)
662                 vm_object_hold_shared(fs.first_ba->object);
663         else
664                 vm_object_hold(fs.first_ba->object);
665         if (fs.vp == NULL)
666                 fs.vp = vnode_pager_lock(fs.first_ba);
667         fs.first_ba_held = 1;
668
669         /*
670          * The page we want is at (first_object, first_pindex), but if the
671          * vm_map_entry is VM_MAPTYPE_VPAGETABLE we have to traverse the
672          * page table to figure out the actual pindex.
673          *
674          * NOTE!  DEVELOPMENT IN PROGRESS, THIS IS AN INITIAL IMPLEMENTATION
675          * ONLY
676          */
677         didilock = 0;
678         if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
679                 vm_map_interlock(fs.map, &ilock, vaddr, vaddr + PAGE_SIZE);
680                 didilock = 1;
681                 result = vm_fault_vpagetable(&fs, &first_pindex,
682                                              fs.entry->aux.master_pde,
683                                              fault_type, 1);
684                 if (result == KERN_TRY_AGAIN) {
685                         vm_map_deinterlock(fs.map, &ilock);
686                         ++retry;
687                         goto RetryFault;
688                 }
689                 if (result != KERN_SUCCESS) {
690                         vm_map_deinterlock(fs.map, &ilock);
691                         goto done;
692                 }
693         }
694
695         /*
696          * Now we have the actual (object, pindex), fault in the page.  If
697          * vm_fault_object() fails it will unlock and deallocate the FS
698          * data.   If it succeeds everything remains locked and fs->ba->object
699          * will have an additional PIP count if fs->ba != fs->first_ba.
700          *
701          * vm_fault_object will set fs->prot for the pmap operation.  It is
702          * allowed to set VM_PROT_WRITE if fault_type == VM_PROT_READ if the
703          * page can be safely written.  However, it will force a read-only
704          * mapping for a read fault if the memory is managed by a virtual
705          * page table.
706          *
707          * If the fault code uses the shared object lock shortcut
708          * we must not try to burst (we can't allocate VM pages).
709          */
710         result = vm_fault_object(&fs, first_pindex, fault_type, 1);
711
712         if (debug_fault > 0) {
713                 --debug_fault;
714                 kprintf("VM_FAULT result %d addr=%jx type=%02x flags=%02x "
715                         "fs.m=%p fs.prot=%02x fs.wflags=%02x fs.entry=%p\n",
716                         result, (intmax_t)vaddr, fault_type, fault_flags,
717                         fs.mary[0], fs.prot, fs.wflags, fs.entry);
718         }
719
720         if (result == KERN_TRY_AGAIN) {
721                 if (didilock)
722                         vm_map_deinterlock(fs.map, &ilock);
723                 ++retry;
724                 goto RetryFault;
725         }
726         if (result != KERN_SUCCESS) {
727                 if (didilock)
728                         vm_map_deinterlock(fs.map, &ilock);
729                 goto done;
730         }
731
732 success:
733         /*
734          * On success vm_fault_object() does not unlock or deallocate, and fs.m
735          * will contain a busied page.  It does drop fs->ba if appropriate.
736          *
737          * Enter the page into the pmap and do pmap-related adjustments.
738          *
739          * WARNING! Soft-busied fs.m's can only be manipulated in limited
740          *          ways.
741          */
742         KKASSERT(fs.lookup_still_valid != 0);
743         vm_page_flag_set(fs.mary[0], PG_REFERENCED);
744
745         for (n = 0; n < mextcount; ++n) {
746                 pmap_enter(fs.map->pmap, vaddr + (n << PAGE_SHIFT),
747                            fs.mary[n], fs.prot | inherit_prot,
748                            fs.wflags & FW_WIRED, fs.entry);
749         }
750
751         if (didilock)
752                 vm_map_deinterlock(fs.map, &ilock);
753
754         /*
755          * If the page is not wired down, then put it where the pageout daemon
756          * can find it.
757          *
758          * NOTE: We cannot safely wire, unwire, or adjust queues for a
759          *       soft-busied page.
760          */
761         for (n = 0; n < mextcount; ++n) {
762                 if (fs.msoftonly) {
763                         KKASSERT(fs.mary[n]->busy_count & PBUSY_MASK);
764                         KKASSERT((fs.fault_flags & VM_FAULT_WIRE_MASK) == 0);
765                         vm_page_sbusy_drop(fs.mary[n]);
766                 } else {
767                         if (fs.fault_flags & VM_FAULT_WIRE_MASK) {
768                                 if (fs.wflags & FW_WIRED)
769                                         vm_page_wire(fs.mary[n]);
770                                 else
771                                         vm_page_unwire(fs.mary[n], 1);
772                         } else {
773                                 vm_page_activate(fs.mary[n]);
774                         }
775                         KKASSERT(fs.mary[n]->busy_count & PBUSY_LOCKED);
776                         vm_page_wakeup(fs.mary[n]);
777                 }
778         }
779
780         /*
781          * Burst in a few more pages if possible.  The fs.map should still
782          * be locked.  To avoid interlocking against a vnode->getblk
783          * operation we had to be sure to unbusy our primary vm_page above
784          * first.
785          *
786          * A normal burst can continue down backing store, only execute
787          * if we are holding an exclusive lock, otherwise the exclusive
788          * locks the burst code gets might cause excessive SMP collisions.
789          *
790          * A quick burst can be utilized when there is no backing object
791          * (i.e. a shared file mmap).
792          */
793         if ((fault_flags & VM_FAULT_BURST) &&
794             (fs.fault_flags & VM_FAULT_WIRE_MASK) == 0 &&
795             (fs.wflags & FW_WIRED) == 0) {
796                 if (fs.first_shared == 0 && fs.shared == 0) {
797                         vm_prefault(fs.map->pmap, vaddr,
798                                     fs.entry, fs.prot, fault_flags);
799                 } else {
800                         vm_prefault_quick(fs.map->pmap, vaddr,
801                                           fs.entry, fs.prot, fault_flags);
802                 }
803         }
804
805 done_success:
806         /*
807          * Unlock everything, and return
808          */
809         unlock_things(&fs);
810
811         mycpu->gd_cnt.v_vm_faults++;
812         if (td->td_lwp) {
813                 if (fs.hardfault) {
814                         ++td->td_lwp->lwp_ru.ru_majflt;
815                 } else {
816                         ++td->td_lwp->lwp_ru.ru_minflt;
817                 }
818         }
819
820         /*vm_object_deallocate(fs.first_ba->object);*/
821         /*fs.m = NULL; */
822
823         result = KERN_SUCCESS;
824 done:
825         if (fs.first_ba && fs.first_ba->object && fs.first_ba_held == 1) {
826                 vm_object_drop(fs.first_ba->object);
827                 fs.first_ba_held = 0;
828         }
829 done2:
830         if (lp)
831                 lp->lwp_flags &= ~LWP_PAGING;
832
833 #if !defined(NO_SWAPPING)
834         /*
835          * Check the process RSS limit and force deactivation and
836          * (asynchronous) paging if necessary.  This is a complex operation,
837          * only do it for direct user-mode faults, for now.
838          *
839          * To reduce overhead implement approximately a ~16MB hysteresis.
840          */
841         p = td->td_proc;
842         if ((fault_flags & VM_FAULT_USERMODE) && lp &&
843             p->p_limit && map->pmap && vm_pageout_memuse_mode >= 1 &&
844             map != &kernel_map) {
845                 vm_pindex_t limit;
846                 vm_pindex_t size;
847
848                 limit = OFF_TO_IDX(qmin(p->p_rlimit[RLIMIT_RSS].rlim_cur,
849                                         p->p_rlimit[RLIMIT_RSS].rlim_max));
850                 size = pmap_resident_tlnw_count(map->pmap);
851                 if (limit >= 0 && size > 4096 && size - 4096 >= limit) {
852                         vm_pageout_map_deactivate_pages(map, limit);
853                 }
854         }
855 #endif
856
857         if (result != KERN_SUCCESS && debug_fault < 0) {
858                 kprintf("VM_FAULT %d:%d (%s) result %d "
859                         "addr=%jx type=%02x flags=%02x "
860                         "fs.m=%p fs.prot=%02x fs.wflags=%02x fs.entry=%p\n",
861                         (curthread->td_proc ? curthread->td_proc->p_pid : -1),
862                         (curthread->td_lwp ? curthread->td_lwp->lwp_tid : -1),
863                         curthread->td_comm,
864                         result,
865                         (intmax_t)vaddr, fault_type, fault_flags,
866                         fs.mary[0], fs.prot, fs.wflags, fs.entry);
867                 while (debug_fault < 0 && (debug_fault & 1))
868                         tsleep(&debug_fault, 0, "DEBUG", hz);
869         }
870
871         return (result);
872 }
873
874 /*
875  * Attempt a lockless vm_fault() shortcut.  The stars have to align for this
876  * to work.  But if it does we can get our page only soft-busied and not
877  * have to touch the vm_object or vnode locks at all.
878  */
879 static
880 int
881 vm_fault_bypass(struct faultstate *fs, vm_pindex_t first_pindex,
882                vm_pindex_t first_count, int *mextcountp,
883                vm_prot_t fault_type)
884 {
885         vm_page_t m;
886         vm_object_t obj;        /* NOT LOCKED */
887         int n;
888         int nlim;
889
890         /*
891          * Don't waste time if the object is only being used by one vm_map.
892          */
893         obj = fs->first_ba->object;
894 #if 0
895         if (obj->flags & OBJ_ONEMAPPING)
896                 return KERN_FAILURE;
897 #endif
898
899         /*
900          * This will try to wire/unwire a page, which can't be done with
901          * a soft-busied page.
902          */
903         if (fs->fault_flags & VM_FAULT_WIRE_MASK)
904                 return KERN_FAILURE;
905
906         /*
907          * Ick, can't handle this
908          */
909         if (fs->entry->maptype == VM_MAPTYPE_VPAGETABLE) {
910 #ifdef VM_FAULT_QUICK_DEBUG
911                 ++vm_fault_bypass_failure_count1;
912 #endif
913                 return KERN_FAILURE;
914         }
915
916         /*
917          * Ok, try to get the vm_page quickly via the hash table.  The
918          * page will be soft-busied on success (NOT hard-busied).
919          */
920         m = vm_page_hash_get(obj, first_pindex);
921         if (m == NULL) {
922 #ifdef VM_FAULT_QUICK_DEBUG
923                 ++vm_fault_bypass_failure_count2;
924 #endif
925                 return KERN_FAILURE;
926         }
927         if ((obj->flags & OBJ_DEAD) ||
928             m->valid != VM_PAGE_BITS_ALL ||
929             m->queue - m->pc != PQ_ACTIVE ||
930             (m->flags & PG_SWAPPED)) {
931                 vm_page_sbusy_drop(m);
932 #ifdef VM_FAULT_QUICK_DEBUG
933                 ++vm_fault_bypass_failure_count3;
934 #endif
935                 return KERN_FAILURE;
936         }
937
938         /*
939          * The page is already fully valid, ACTIVE, and is not PG_SWAPPED.
940          *
941          * Don't map the page writable when emulating the dirty bit, a
942          * fault must be taken for proper emulation (vkernel).
943          */
944         if (curthread->td_lwp && curthread->td_lwp->lwp_vmspace &&
945             pmap_emulate_ad_bits(&curthread->td_lwp->lwp_vmspace->vm_pmap)) {
946                 if ((fault_type & VM_PROT_WRITE) == 0)
947                         fs->prot &= ~VM_PROT_WRITE;
948         }
949
950         /*
951          * If this is a write fault the object and the page must already
952          * be writable.  Since we don't hold an object lock and only a
953          * soft-busy on the page, we cannot manipulate the object or
954          * the page state (other than the page queue).
955          */
956         if (fs->prot & VM_PROT_WRITE) {
957                 if ((obj->flags & (OBJ_WRITEABLE | OBJ_MIGHTBEDIRTY)) !=
958                     (OBJ_WRITEABLE | OBJ_MIGHTBEDIRTY) ||
959                     m->dirty != VM_PAGE_BITS_ALL) {
960                         vm_page_sbusy_drop(m);
961 #ifdef VM_FAULT_QUICK_DEBUG
962                         ++vm_fault_bypass_failure_count4;
963 #endif
964                         return KERN_FAILURE;
965                 }
966                 vm_set_nosync(m, fs->entry);
967         }
968
969         /*
970          * Set page and potentially burst in more
971          *
972          * Even though we are only soft-busied we can still move pages
973          * around in the normal queue(s).  The soft-busy prevents the
974          * page from being removed from the object, etc (normal operation).
975          *
976          * However, in this fast path it is excessively important to avoid
977          * any hard locks, so we use a special passive version of activate.
978          */
979         fs->msoftonly = 1;
980         fs->mary[0] = m;
981         vm_page_soft_activate(m);
982
983         if (vm_fault_bypass_count > 1) {
984                 nlim = vm_fault_bypass_count;
985                 if (nlim > VM_FAULT_MAX_QUICK)          /* array limit(+1) */
986                         nlim = VM_FAULT_MAX_QUICK;
987                 if (nlim > first_count)                 /* user limit */
988                         nlim = first_count;
989
990                 for (n = 1; n < nlim; ++n) {
991                         m = vm_page_hash_get(obj, first_pindex + n);
992                         if (m == NULL)
993                                 break;
994                         if (m->valid != VM_PAGE_BITS_ALL ||
995                             m->queue - m->pc != PQ_ACTIVE ||
996                             (m->flags & PG_SWAPPED)) {
997                                 vm_page_sbusy_drop(m);
998                                 break;
999                         }
1000                         if (fs->prot & VM_PROT_WRITE) {
1001                                 if ((obj->flags & (OBJ_WRITEABLE |
1002                                                    OBJ_MIGHTBEDIRTY)) !=
1003                                     (OBJ_WRITEABLE | OBJ_MIGHTBEDIRTY) ||
1004                                     m->dirty != VM_PAGE_BITS_ALL) {
1005                                         vm_page_sbusy_drop(m);
1006                                         break;
1007                                 }
1008                         }
1009                         vm_page_soft_activate(m);
1010                         fs->mary[n] = m;
1011                 }
1012                 *mextcountp = n;
1013         }
1014
1015 #ifdef VM_FAULT_QUICK_DEBUG
1016         ++vm_fault_bypass_success_count;
1017 #endif
1018
1019         return KERN_SUCCESS;
1020 }
1021
1022 /*
1023  * Fault in the specified virtual address in the current process map, 
1024  * returning a held VM page or NULL.  See vm_fault_page() for more 
1025  * information.
1026  *
1027  * No requirements.
1028  */
1029 vm_page_t
1030 vm_fault_page_quick(vm_offset_t va, vm_prot_t fault_type,
1031                     int *errorp, int *busyp)
1032 {
1033         struct lwp *lp = curthread->td_lwp;
1034         vm_page_t m;
1035
1036         m = vm_fault_page(&lp->lwp_vmspace->vm_map, va, 
1037                           fault_type, VM_FAULT_NORMAL,
1038                           errorp, busyp);
1039         return(m);
1040 }
1041
1042 /*
1043  * Fault in the specified virtual address in the specified map, doing all
1044  * necessary manipulation of the object store and all necessary I/O.  Return
1045  * a held VM page or NULL, and set *errorp.  The related pmap is not
1046  * updated.
1047  *
1048  * If busyp is not NULL then *busyp will be set to TRUE if this routine
1049  * decides to return a busied page (aka VM_PROT_WRITE), or FALSE if it
1050  * does not (VM_PROT_WRITE not specified or busyp is NULL).  If busyp is
1051  * NULL the returned page is only held.
1052  *
1053  * If the caller has no intention of writing to the page's contents, busyp
1054  * can be passed as NULL along with VM_PROT_WRITE to force a COW operation
1055  * without busying the page.
1056  *
1057  * The returned page will also be marked PG_REFERENCED.
1058  *
1059  * If the page cannot be faulted writable and VM_PROT_WRITE was specified, an
1060  * error will be returned.
1061  *
1062  * No requirements.
1063  */
1064 vm_page_t
1065 vm_fault_page(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
1066               int fault_flags, int *errorp, int *busyp)
1067 {
1068         vm_pindex_t first_pindex;
1069         vm_pindex_t first_count;
1070         struct faultstate fs;
1071         int result;
1072         int retry;
1073         int growstack;
1074         int didcow;
1075         vm_prot_t orig_fault_type = fault_type;
1076
1077         retry = 0;
1078         didcow = 0;
1079         fs.hardfault = 0;
1080         fs.fault_flags = fault_flags;
1081         KKASSERT((fault_flags & VM_FAULT_WIRE_MASK) == 0);
1082
1083         /*
1084          * Dive the pmap (concurrency possible).  If we find the
1085          * appropriate page we can terminate early and quickly.
1086          *
1087          * This works great for normal programs but will always return
1088          * NULL for host lookups of vkernel maps in VMM mode.
1089          *
1090          * NOTE: pmap_fault_page_quick() might not busy the page.  If
1091          *       VM_PROT_WRITE is set in fault_type and pmap_fault_page_quick()
1092          *       returns non-NULL, it will safely dirty the returned vm_page_t
1093          *       for us.  We cannot safely dirty it here (it might not be
1094          *       busy).
1095          */
1096         fs.mary[0] = pmap_fault_page_quick(map->pmap, vaddr, fault_type, busyp);
1097         if (fs.mary[0]) {
1098                 *errorp = 0;
1099                 return(fs.mary[0]);
1100         }
1101
1102         /*
1103          * Otherwise take a concurrency hit and do a formal page
1104          * fault.
1105          */
1106         fs.vp = NULL;
1107         fs.shared = vm_shared_fault;
1108         fs.first_shared = vm_shared_fault;
1109         fs.msoftonly = 0;
1110         growstack = 1;
1111
1112         /*
1113          * VM_FAULT_UNSWAP - swap_pager_unswapped() needs an exclusive object
1114          * VM_FAULT_DIRTY  - may require swap_pager_unswapped() later, but
1115          *                   we can try shared first.
1116          */
1117         if (fault_flags & VM_FAULT_UNSWAP) {
1118                 fs.first_shared = 0;
1119         }
1120
1121 RetryFault:
1122         /*
1123          * Find the vm_map_entry representing the backing store and resolve
1124          * the top level object and page index.  This may have the side
1125          * effect of executing a copy-on-write on the map entry and/or
1126          * creating a shadow object, but will not COW any actual VM pages.
1127          *
1128          * On success fs.map is left read-locked and various other fields 
1129          * are initialized but not otherwise referenced or locked.
1130          *
1131          * NOTE!  vm_map_lookup will upgrade the fault_type to VM_FAULT_WRITE
1132          *        if the map entry is a virtual page table and also writable,
1133          *        so we can set the 'A'accessed bit in the virtual page table
1134          *        entry.
1135          */
1136         fs.map = map;
1137         fs.first_ba_held = 0;
1138         result = vm_map_lookup(&fs.map, vaddr, fault_type,
1139                                &fs.entry, &fs.first_ba,
1140                                &first_pindex, &first_count,
1141                                &fs.first_prot, &fs.wflags);
1142
1143         if (result != KERN_SUCCESS) {
1144                 if (result == KERN_FAILURE_NOFAULT) {
1145                         *errorp = KERN_FAILURE;
1146                         fs.mary[0] = NULL;
1147                         goto done;
1148                 }
1149                 if (result != KERN_PROTECTION_FAILURE ||
1150                     (fs.fault_flags & VM_FAULT_WIRE_MASK) != VM_FAULT_USER_WIRE)
1151                 {
1152                         if (result == KERN_INVALID_ADDRESS && growstack &&
1153                             map != &kernel_map && curproc != NULL) {
1154                                 result = vm_map_growstack(map, vaddr);
1155                                 if (result == KERN_SUCCESS) {
1156                                         growstack = 0;
1157                                         ++retry;
1158                                         goto RetryFault;
1159                                 }
1160                                 result = KERN_FAILURE;
1161                         }
1162                         fs.mary[0] = NULL;
1163                         *errorp = result;
1164                         goto done;
1165                 }
1166
1167                 /*
1168                  * If we are user-wiring a r/w segment, and it is COW, then
1169                  * we need to do the COW operation.  Note that we don't
1170                  * currently COW RO sections now, because it is NOT desirable
1171                  * to COW .text.  We simply keep .text from ever being COW'ed
1172                  * and take the heat that one cannot debug wired .text sections.
1173                  */
1174                 result = vm_map_lookup(&fs.map, vaddr,
1175                                        VM_PROT_READ|VM_PROT_WRITE|
1176                                         VM_PROT_OVERRIDE_WRITE,
1177                                        &fs.entry, &fs.first_ba,
1178                                        &first_pindex, &first_count,
1179                                        &fs.first_prot, &fs.wflags);
1180                 if (result != KERN_SUCCESS) {
1181                         /* could also be KERN_FAILURE_NOFAULT */
1182                         *errorp = KERN_FAILURE;
1183                         fs.mary[0] = NULL;
1184                         goto done;
1185                 }
1186
1187                 /*
1188                  * If we don't COW now, on a user wire, the user will never
1189                  * be able to write to the mapping.  If we don't make this
1190                  * restriction, the bookkeeping would be nearly impossible.
1191                  *
1192                  * XXX We have a shared lock, this will have a MP race but
1193                  * I don't see how it can hurt anything.
1194                  */
1195                 if ((fs.entry->protection & VM_PROT_WRITE) == 0) {
1196                         atomic_clear_char(&fs.entry->max_protection,
1197                                           VM_PROT_WRITE);
1198                 }
1199         }
1200
1201         /*
1202          * fs.map is read-locked
1203          *
1204          * Misc checks.  Save the map generation number to detect races.
1205          */
1206         fs.lookup_still_valid = 1;
1207         fs.first_m = NULL;
1208         fs.ba = fs.first_ba;
1209
1210         if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
1211                 panic("vm_fault: fault on nofault entry, addr: %lx",
1212                     (u_long)vaddr);
1213         }
1214
1215         /*
1216          * A user-kernel shared map has no VM object and bypasses
1217          * everything.  We execute the uksmap function with a temporary
1218          * fictitious vm_page.  The address is directly mapped with no
1219          * management.
1220          */
1221         if (fs.entry->maptype == VM_MAPTYPE_UKSMAP) {
1222                 struct vm_page fakem;
1223
1224                 bzero(&fakem, sizeof(fakem));
1225                 fakem.pindex = first_pindex;
1226                 fakem.flags = PG_FICTITIOUS | PG_UNQUEUED;
1227                 fakem.busy_count = PBUSY_LOCKED;
1228                 fakem.valid = VM_PAGE_BITS_ALL;
1229                 fakem.pat_mode = VM_MEMATTR_DEFAULT;
1230                 if (fs.entry->ba.uksmap(&fs.entry->ba, UKSMAPOP_FAULT,
1231                                         fs.entry->aux.dev, &fakem)) {
1232                         *errorp = KERN_FAILURE;
1233                         fs.mary[0] = NULL;
1234                         unlock_things(&fs);
1235                         goto done2;
1236                 }
1237                 fs.mary[0] = PHYS_TO_VM_PAGE(fakem.phys_addr);
1238                 vm_page_hold(fs.mary[0]);
1239                 if (busyp)
1240                         *busyp = 0;     /* don't need to busy R or W */
1241                 unlock_things(&fs);
1242                 *errorp = 0;
1243                 goto done;
1244         }
1245
1246
1247         /*
1248          * A system map entry may return a NULL object.  No object means
1249          * no pager means an unrecoverable kernel fault.
1250          */
1251         if (fs.first_ba == NULL) {
1252                 panic("vm_fault: unrecoverable fault at %p in entry %p",
1253                         (void *)vaddr, fs.entry);
1254         }
1255
1256         /*
1257          * Fail here if not a trivial anonymous page fault and TDF_NOFAULT
1258          * is set.
1259          *
1260          * Unfortunately a deadlock can occur if we are forced to page-in
1261          * from swap, but diving all the way into the vm_pager_get_page()
1262          * function to find out is too much.  Just check the object type.
1263          */
1264         if ((curthread->td_flags & TDF_NOFAULT) &&
1265             (retry ||
1266              fs.first_ba->object->type == OBJT_VNODE ||
1267              fs.first_ba->object->type == OBJT_SWAP ||
1268              fs.first_ba->backing_ba)) {
1269                 *errorp = KERN_FAILURE;
1270                 unlock_things(&fs);
1271                 fs.mary[0] = NULL;
1272                 goto done2;
1273         }
1274
1275         /*
1276          * If the entry is wired we cannot change the page protection.
1277          */
1278         if (fs.wflags & FW_WIRED)
1279                 fault_type = fs.first_prot;
1280
1281         /*
1282          * Make a reference to this object to prevent its disposal while we
1283          * are messing with it.  Once we have the reference, the map is free
1284          * to be diddled.  Since objects reference their shadows (and copies),
1285          * they will stay around as well.
1286          *
1287          * The reference should also prevent an unexpected collapse of the
1288          * parent that might move pages from the current object into the
1289          * parent unexpectedly, resulting in corruption.
1290          *
1291          * Bump the paging-in-progress count to prevent size changes (e.g.
1292          * truncation operations) during I/O.  This must be done after
1293          * obtaining the vnode lock in order to avoid possible deadlocks.
1294          */
1295         if (fs.first_ba->flags & VM_MAP_BACK_EXCL_HEUR)
1296                 fs.first_shared = 0;
1297
1298         if (fs.first_shared)
1299                 vm_object_hold_shared(fs.first_ba->object);
1300         else
1301                 vm_object_hold(fs.first_ba->object);
1302         fs.first_ba_held = 1;
1303         if (fs.vp == NULL)
1304                 fs.vp = vnode_pager_lock(fs.first_ba);  /* shared */
1305
1306         /*
1307          * The page we want is at (first_object, first_pindex), but if the
1308          * vm_map_entry is VM_MAPTYPE_VPAGETABLE we have to traverse the
1309          * page table to figure out the actual pindex.
1310          *
1311          * NOTE!  DEVELOPMENT IN PROGRESS, THIS IS AN INITIAL IMPLEMENTATION
1312          * ONLY
1313          */
1314         if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
1315                 result = vm_fault_vpagetable(&fs, &first_pindex,
1316                                              fs.entry->aux.master_pde,
1317                                              fault_type, 1);
1318                 first_count = 1;
1319                 if (result == KERN_TRY_AGAIN) {
1320                         ++retry;
1321                         goto RetryFault;
1322                 }
1323                 if (result != KERN_SUCCESS) {
1324                         *errorp = result;
1325                         fs.mary[0] = NULL;
1326                         goto done;
1327                 }
1328         }
1329
1330         /*
1331          * Now we have the actual (object, pindex), fault in the page.  If
1332          * vm_fault_object() fails it will unlock and deallocate the FS
1333          * data.   If it succeeds everything remains locked and fs->ba->object
1334          * will have an additinal PIP count if fs->ba != fs->first_ba.
1335          */
1336         fs.mary[0] = NULL;
1337         result = vm_fault_object(&fs, first_pindex, fault_type, 1);
1338
1339         if (result == KERN_TRY_AGAIN) {
1340                 KKASSERT(fs.first_ba_held == 0);
1341                 ++retry;
1342                 didcow |= fs.wflags & FW_DIDCOW;
1343                 goto RetryFault;
1344         }
1345         if (result != KERN_SUCCESS) {
1346                 *errorp = result;
1347                 fs.mary[0] = NULL;
1348                 goto done;
1349         }
1350
1351         if ((orig_fault_type & VM_PROT_WRITE) &&
1352             (fs.prot & VM_PROT_WRITE) == 0) {
1353                 *errorp = KERN_PROTECTION_FAILURE;
1354                 unlock_things(&fs);
1355                 fs.mary[0] = NULL;
1356                 goto done;
1357         }
1358
1359         /*
1360          * Generally speaking we don't want to update the pmap because
1361          * this routine can be called many times for situations that do
1362          * not require updating the pmap, not to mention the page might
1363          * already be in the pmap.
1364          *
1365          * However, if our vm_map_lookup() results in a COW, we need to
1366          * at least remove the pte from the pmap to guarantee proper
1367          * visibility of modifications made to the process.  For example,
1368          * modifications made by vkernel uiocopy/related routines and
1369          * modifications made by ptrace().
1370          */
1371         vm_page_flag_set(fs.mary[0], PG_REFERENCED);
1372 #if 0
1373         pmap_enter(fs.map->pmap, vaddr, fs.mary[0], fs.prot,
1374                    fs.wflags & FW_WIRED, NULL);
1375         mycpu->gd_cnt.v_vm_faults++;
1376         if (curthread->td_lwp)
1377                 ++curthread->td_lwp->lwp_ru.ru_minflt;
1378 #endif
1379         if ((fs.wflags | didcow) | FW_DIDCOW) {
1380                 pmap_remove(fs.map->pmap,
1381                             vaddr & ~PAGE_MASK,
1382                             (vaddr & ~PAGE_MASK) + PAGE_SIZE);
1383         }
1384
1385         /*
1386          * On success vm_fault_object() does not unlock or deallocate, and
1387          * fs.mary[0] will contain a busied page.  So we must unlock here
1388          * after having messed with the pmap.
1389          */
1390         unlock_things(&fs);
1391
1392         /*
1393          * Return a held page.  We are not doing any pmap manipulation so do
1394          * not set PG_MAPPED.  However, adjust the page flags according to
1395          * the fault type because the caller may not use a managed pmapping
1396          * (so we don't want to lose the fact that the page will be dirtied
1397          * if a write fault was specified).
1398          */
1399         if (fault_type & VM_PROT_WRITE)
1400                 vm_page_dirty(fs.mary[0]);
1401         vm_page_activate(fs.mary[0]);
1402
1403         if (curthread->td_lwp) {
1404                 if (fs.hardfault) {
1405                         curthread->td_lwp->lwp_ru.ru_majflt++;
1406                 } else {
1407                         curthread->td_lwp->lwp_ru.ru_minflt++;
1408                 }
1409         }
1410
1411         /*
1412          * Unlock everything, and return the held or busied page.
1413          */
1414         if (busyp) {
1415                 if (fault_type & VM_PROT_WRITE) {
1416                         vm_page_dirty(fs.mary[0]);
1417                         *busyp = 1;
1418                 } else {
1419                         *busyp = 0;
1420                         vm_page_hold(fs.mary[0]);
1421                         vm_page_wakeup(fs.mary[0]);
1422                 }
1423         } else {
1424                 vm_page_hold(fs.mary[0]);
1425                 vm_page_wakeup(fs.mary[0]);
1426         }
1427         /*vm_object_deallocate(fs.first_ba->object);*/
1428         *errorp = 0;
1429
1430 done:
1431         KKASSERT(fs.first_ba_held == 0);
1432 done2:
1433         return(fs.mary[0]);
1434 }
1435
1436 /*
1437  * Fault in the specified (object,offset), dirty the returned page as
1438  * needed.  If the requested fault_type cannot be done NULL and an
1439  * error is returned.
1440  *
1441  * A held (but not busied) page is returned.
1442  *
1443  * The passed in object must be held as specified by the shared
1444  * argument.
1445  */
1446 vm_page_t
1447 vm_fault_object_page(vm_object_t object, vm_ooffset_t offset,
1448                      vm_prot_t fault_type, int fault_flags,
1449                      int *sharedp, int *errorp)
1450 {
1451         int result;
1452         vm_pindex_t first_pindex;
1453         vm_pindex_t first_count;
1454         struct faultstate fs;
1455         struct vm_map_entry entry;
1456
1457         /*
1458          * Since we aren't actually faulting the page into a
1459          * pmap we can just fake the entry.ba.
1460          */
1461         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1462         bzero(&entry, sizeof(entry));
1463         entry.maptype = VM_MAPTYPE_NORMAL;
1464         entry.protection = entry.max_protection = fault_type;
1465         entry.ba.backing_ba = NULL;
1466         entry.ba.object = object;
1467         entry.ba.offset = 0;
1468
1469         fs.hardfault = 0;
1470         fs.fault_flags = fault_flags;
1471         fs.map = NULL;
1472         fs.shared = vm_shared_fault;
1473         fs.first_shared = *sharedp;
1474         fs.msoftonly = 0;
1475         fs.vp = NULL;
1476         fs.first_ba_held = -1;  /* object held across call, prevent drop */
1477         KKASSERT((fault_flags & VM_FAULT_WIRE_MASK) == 0);
1478
1479         /*
1480          * VM_FAULT_UNSWAP - swap_pager_unswapped() needs an exclusive object
1481          * VM_FAULT_DIRTY  - may require swap_pager_unswapped() later, but
1482          *                   we can try shared first.
1483          */
1484         if (fs.first_shared && (fault_flags & VM_FAULT_UNSWAP)) {
1485                 fs.first_shared = 0;
1486                 vm_object_upgrade(object);
1487         }
1488
1489         /*
1490          * Retry loop as needed (typically for shared->exclusive transitions)
1491          */
1492 RetryFault:
1493         *sharedp = fs.first_shared;
1494         first_pindex = OFF_TO_IDX(offset);
1495         first_count = 1;
1496         fs.first_ba = &entry.ba;
1497         fs.ba = fs.first_ba;
1498         fs.entry = &entry;
1499         fs.first_prot = fault_type;
1500         fs.wflags = 0;
1501
1502         /*
1503          * Make a reference to this object to prevent its disposal while we
1504          * are messing with it.  Once we have the reference, the map is free
1505          * to be diddled.  Since objects reference their shadows (and copies),
1506          * they will stay around as well.
1507          *
1508          * The reference should also prevent an unexpected collapse of the
1509          * parent that might move pages from the current object into the
1510          * parent unexpectedly, resulting in corruption.
1511          *
1512          * Bump the paging-in-progress count to prevent size changes (e.g.
1513          * truncation operations) during I/O.  This must be done after
1514          * obtaining the vnode lock in order to avoid possible deadlocks.
1515          */
1516         if (fs.vp == NULL)
1517                 fs.vp = vnode_pager_lock(fs.first_ba);
1518
1519         fs.lookup_still_valid = 1;
1520         fs.first_m = NULL;
1521
1522 #if 0
1523         /* XXX future - ability to operate on VM object using vpagetable */
1524         if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
1525                 result = vm_fault_vpagetable(&fs, &first_pindex,
1526                                              fs.entry->aux.master_pde,
1527                                              fault_type, 0);
1528                 if (result == KERN_TRY_AGAIN) {
1529                         if (fs.first_shared == 0 && *sharedp)
1530                                 vm_object_upgrade(object);
1531                         goto RetryFault;
1532                 }
1533                 if (result != KERN_SUCCESS) {
1534                         *errorp = result;
1535                         return (NULL);
1536                 }
1537         }
1538 #endif
1539
1540         /*
1541          * Now we have the actual (object, pindex), fault in the page.  If
1542          * vm_fault_object() fails it will unlock and deallocate the FS
1543          * data.   If it succeeds everything remains locked and fs->ba->object
1544          * will have an additinal PIP count if fs->ba != fs->first_ba.
1545          *
1546          * On KERN_TRY_AGAIN vm_fault_object() leaves fs.first_ba intact.
1547          * We may have to upgrade its lock to handle the requested fault.
1548          */
1549         result = vm_fault_object(&fs, first_pindex, fault_type, 0);
1550
1551         if (result == KERN_TRY_AGAIN) {
1552                 if (fs.first_shared == 0 && *sharedp)
1553                         vm_object_upgrade(object);
1554                 goto RetryFault;
1555         }
1556         if (result != KERN_SUCCESS) {
1557                 *errorp = result;
1558                 return(NULL);
1559         }
1560
1561         if ((fault_type & VM_PROT_WRITE) && (fs.prot & VM_PROT_WRITE) == 0) {
1562                 *errorp = KERN_PROTECTION_FAILURE;
1563                 unlock_things(&fs);
1564                 return(NULL);
1565         }
1566
1567         /*
1568          * On success vm_fault_object() does not unlock or deallocate, so we
1569          * do it here.  Note that the returned fs.m will be busied.
1570          */
1571         unlock_things(&fs);
1572
1573         /*
1574          * Return a held page.  We are not doing any pmap manipulation so do
1575          * not set PG_MAPPED.  However, adjust the page flags according to
1576          * the fault type because the caller may not use a managed pmapping
1577          * (so we don't want to lose the fact that the page will be dirtied
1578          * if a write fault was specified).
1579          */
1580         vm_page_hold(fs.mary[0]);
1581         vm_page_activate(fs.mary[0]);
1582         if ((fault_type & VM_PROT_WRITE) || (fault_flags & VM_FAULT_DIRTY))
1583                 vm_page_dirty(fs.mary[0]);
1584         if (fault_flags & VM_FAULT_UNSWAP)
1585                 swap_pager_unswapped(fs.mary[0]);
1586
1587         /*
1588          * Indicate that the page was accessed.
1589          */
1590         vm_page_flag_set(fs.mary[0], PG_REFERENCED);
1591
1592         if (curthread->td_lwp) {
1593                 if (fs.hardfault) {
1594                         curthread->td_lwp->lwp_ru.ru_majflt++;
1595                 } else {
1596                         curthread->td_lwp->lwp_ru.ru_minflt++;
1597                 }
1598         }
1599
1600         /*
1601          * Unlock everything, and return the held page.
1602          */
1603         vm_page_wakeup(fs.mary[0]);
1604         /*vm_object_deallocate(fs.first_ba->object);*/
1605
1606         *errorp = 0;
1607         return(fs.mary[0]);
1608 }
1609
1610 /*
1611  * Translate the virtual page number (first_pindex) that is relative
1612  * to the address space into a logical page number that is relative to the
1613  * backing object.  Use the virtual page table pointed to by (vpte).
1614  *
1615  * Possibly downgrade the protection based on the vpte bits.
1616  *
1617  * This implements an N-level page table.  Any level can terminate the
1618  * scan by setting VPTE_PS.   A linear mapping is accomplished by setting
1619  * VPTE_PS in the master page directory entry set via mcontrol(MADV_SETMAP).
1620  */
1621 static
1622 int
1623 vm_fault_vpagetable(struct faultstate *fs, vm_pindex_t *pindex,
1624                     vpte_t vpte, int fault_type, int allow_nofault)
1625 {
1626         struct lwbuf *lwb;
1627         struct lwbuf lwb_cache;
1628         int vshift = VPTE_FRAME_END - PAGE_SHIFT; /* index bits remaining */
1629         int result;
1630         vpte_t *ptep;
1631
1632         ASSERT_LWKT_TOKEN_HELD(vm_object_token(fs->first_ba->object));
1633         for (;;) {
1634                 /*
1635                  * We cannot proceed if the vpte is not valid, not readable
1636                  * for a read fault, not writable for a write fault, or
1637                  * not executable for an instruction execution fault.
1638                  */
1639                 if ((vpte & VPTE_V) == 0) {
1640                         unlock_things(fs);
1641                         return (KERN_FAILURE);
1642                 }
1643                 if ((fault_type & VM_PROT_WRITE) && (vpte & VPTE_RW) == 0) {
1644                         unlock_things(fs);
1645                         return (KERN_FAILURE);
1646                 }
1647                 if ((fault_type & VM_PROT_EXECUTE) && (vpte & VPTE_NX)) {
1648                         unlock_things(fs);
1649                         return (KERN_FAILURE);
1650                 }
1651                 if ((vpte & VPTE_PS) || vshift == 0)
1652                         break;
1653
1654                 /*
1655                  * Get the page table page.  Nominally we only read the page
1656                  * table, but since we are actively setting VPTE_M and VPTE_A,
1657                  * tell vm_fault_object() that we are writing it. 
1658                  *
1659                  * There is currently no real need to optimize this.
1660                  */
1661                 result = vm_fault_object(fs, (vpte & VPTE_FRAME) >> PAGE_SHIFT,
1662                                          VM_PROT_READ|VM_PROT_WRITE,
1663                                          allow_nofault);
1664                 if (result != KERN_SUCCESS)
1665                         return (result);
1666
1667                 /*
1668                  * Process the returned fs.mary[0] and look up the page table
1669                  * entry in the page table page.
1670                  */
1671                 vshift -= VPTE_PAGE_BITS;
1672                 lwb = lwbuf_alloc(fs->mary[0], &lwb_cache);
1673                 ptep = ((vpte_t *)lwbuf_kva(lwb) +
1674                         ((*pindex >> vshift) & VPTE_PAGE_MASK));
1675                 vm_page_activate(fs->mary[0]);
1676
1677                 /*
1678                  * Page table write-back - entire operation including
1679                  * validation of the pte must be atomic to avoid races
1680                  * against the vkernel changing the pte.
1681                  *
1682                  * If the vpte is valid for the* requested operation, do
1683                  * a write-back to the page table.
1684                  *
1685                  * XXX VPTE_M is not set properly for page directory pages.
1686                  * It doesn't get set in the page directory if the page table
1687                  * is modified during a read access.
1688                  */
1689                 for (;;) {
1690                         vpte_t nvpte;
1691
1692                         /*
1693                          * Reload for the cmpset, but make sure the pte is
1694                          * still valid.
1695                          */
1696                         vpte = *ptep;
1697                         cpu_ccfence();
1698                         nvpte = vpte;
1699
1700                         if ((vpte & VPTE_V) == 0)
1701                                 break;
1702
1703                         if ((fault_type & VM_PROT_WRITE) && (vpte & VPTE_RW))
1704                                 nvpte |= VPTE_M | VPTE_A;
1705                         if (fault_type & (VM_PROT_READ | VM_PROT_EXECUTE))
1706                                 nvpte |= VPTE_A;
1707                         if (vpte == nvpte)
1708                                 break;
1709                         if (atomic_cmpset_long(ptep, vpte, nvpte)) {
1710                                 vm_page_dirty(fs->mary[0]);
1711                                 break;
1712                         }
1713                 }
1714                 lwbuf_free(lwb);
1715                 vm_page_flag_set(fs->mary[0], PG_REFERENCED);
1716                 vm_page_wakeup(fs->mary[0]);
1717                 fs->mary[0] = NULL;
1718                 cleanup_fault(fs);
1719         }
1720
1721         /*
1722          * When the vkernel sets VPTE_RW it expects the real kernel to
1723          * reflect VPTE_M back when the page is modified via the mapping.
1724          * In order to accomplish this the real kernel must map the page
1725          * read-only for read faults and use write faults to reflect VPTE_M
1726          * back.
1727          *
1728          * Once VPTE_M has been set, the real kernel's pte allows writing.
1729          * If the vkernel clears VPTE_M the vkernel must be sure to
1730          * MADV_INVAL the real kernel's mappings to force the real kernel
1731          * to re-fault on the next write so oit can set VPTE_M again.
1732          */
1733         if ((fault_type & VM_PROT_WRITE) == 0 &&
1734             (vpte & (VPTE_RW | VPTE_M)) != (VPTE_RW | VPTE_M)) {
1735                 fs->first_prot &= ~VM_PROT_WRITE;
1736         }
1737
1738         /*
1739          * Disable EXECUTE perms if NX bit is set.
1740          */
1741         if (vpte & VPTE_NX)
1742                 fs->first_prot &= ~VM_PROT_EXECUTE;
1743
1744         /*
1745          * Combine remaining address bits with the vpte.
1746          */
1747         *pindex = ((vpte & VPTE_FRAME) >> PAGE_SHIFT) +
1748                   (*pindex & ((1L << vshift) - 1));
1749         return (KERN_SUCCESS);
1750 }
1751
1752
1753 /*
1754  * This is the core of the vm_fault code.
1755  *
1756  * Do all operations required to fault-in (fs.first_ba->object, pindex).
1757  * Run through the backing store as necessary and do required COW or virtual
1758  * copy operations.  The caller has already fully resolved the vm_map_entry
1759  * and, if appropriate, has created a copy-on-write layer.  All we need to
1760  * do is iterate the object chain.
1761  *
1762  * On failure (fs) is unlocked and deallocated and the caller may return or
1763  * retry depending on the failure code.  On success (fs) is NOT unlocked or
1764  * deallocated, fs.mary[0] will contained a resolved, busied page, and fs.ba's
1765  * object will have an additional PIP count if it is not equal to
1766  * fs.first_ba.
1767  *
1768  * If locks based on fs->first_shared or fs->shared are insufficient,
1769  * clear the appropriate field(s) and return RETRY.  COWs require that
1770  * first_shared be 0, while page allocations (or frees) require that
1771  * shared be 0.  Renames require that both be 0.
1772  *
1773  * NOTE! fs->[first_]shared might be set with VM_FAULT_DIRTY also set.
1774  *       we will have to retry with it exclusive if the vm_page is
1775  *       PG_SWAPPED.
1776  *
1777  * fs->first_ba->object must be held on call.
1778  */
1779 static
1780 int
1781 vm_fault_object(struct faultstate *fs, vm_pindex_t first_pindex,
1782                 vm_prot_t fault_type, int allow_nofault)
1783 {
1784         vm_map_backing_t next_ba;
1785         vm_pindex_t pindex;
1786         int error;
1787
1788         ASSERT_LWKT_TOKEN_HELD(vm_object_token(fs->first_ba->object));
1789         fs->prot = fs->first_prot;
1790         pindex = first_pindex;
1791         KKASSERT(fs->ba == fs->first_ba);
1792
1793         vm_object_pip_add(fs->first_ba->object, 1);
1794
1795         /* 
1796          * If a read fault occurs we try to upgrade the page protection
1797          * and make it also writable if possible.  There are three cases
1798          * where we cannot make the page mapping writable:
1799          *
1800          * (1) The mapping is read-only or the VM object is read-only,
1801          *     fs->prot above will simply not have VM_PROT_WRITE set.
1802          *
1803          * (2) If the mapping is a virtual page table fs->first_prot will
1804          *     have already been properly adjusted by vm_fault_vpagetable().
1805          *     to detect writes so we can set VPTE_M in the virtual page
1806          *     table.  Used by vkernels.
1807          *
1808          * (3) If the VM page is read-only or copy-on-write, upgrading would
1809          *     just result in an unnecessary COW fault.
1810          *
1811          * (4) If the pmap specifically requests A/M bit emulation, downgrade
1812          *     here.
1813          */
1814 #if 0
1815         /* see vpagetable code */
1816         if (fs->entry->maptype == VM_MAPTYPE_VPAGETABLE) {
1817                 if ((fault_type & VM_PROT_WRITE) == 0)
1818                         fs->prot &= ~VM_PROT_WRITE;
1819         }
1820 #endif
1821
1822         if (curthread->td_lwp && curthread->td_lwp->lwp_vmspace &&
1823             pmap_emulate_ad_bits(&curthread->td_lwp->lwp_vmspace->vm_pmap)) {
1824                 if ((fault_type & VM_PROT_WRITE) == 0)
1825                         fs->prot &= ~VM_PROT_WRITE;
1826         }
1827
1828         /* vm_object_hold(fs->ba->object); implied b/c ba == first_ba */
1829
1830         for (;;) {
1831                 /*
1832                  * If the object is dead, we stop here
1833                  */
1834                 if (fs->ba->object->flags & OBJ_DEAD) {
1835                         vm_object_pip_wakeup(fs->first_ba->object);
1836                         unlock_things(fs);
1837                         return (KERN_PROTECTION_FAILURE);
1838                 }
1839
1840                 /*
1841                  * See if the page is resident.  Wait/Retry if the page is
1842                  * busy (lots of stuff may have changed so we can't continue
1843                  * in that case).
1844                  *
1845                  * We can theoretically allow the soft-busy case on a read
1846                  * fault if the page is marked valid, but since such
1847                  * pages are typically already pmap'd, putting that
1848                  * special case in might be more effort then it is
1849                  * worth.  We cannot under any circumstances mess
1850                  * around with a vm_page_t->busy page except, perhaps,
1851                  * to pmap it.
1852                  */
1853                 fs->mary[0] = vm_page_lookup_busy_try(fs->ba->object, pindex,
1854                                                       TRUE, &error);
1855                 if (error) {
1856                         vm_object_pip_wakeup(fs->first_ba->object);
1857                         unlock_things(fs);
1858                         vm_page_sleep_busy(fs->mary[0], TRUE, "vmpfw");
1859                         mycpu->gd_cnt.v_intrans++;
1860                         fs->mary[0] = NULL;
1861                         return (KERN_TRY_AGAIN);
1862                 }
1863                 if (fs->mary[0]) {
1864                         /*
1865                          * The page is busied for us.
1866                          *
1867                          * If reactivating a page from PQ_CACHE we may have
1868                          * to rate-limit.
1869                          */
1870                         int queue = fs->mary[0]->queue;
1871                         vm_page_unqueue_nowakeup(fs->mary[0]);
1872
1873                         if ((queue - fs->mary[0]->pc) == PQ_CACHE &&
1874                             vm_page_count_severe()) {
1875                                 vm_page_activate(fs->mary[0]);
1876                                 vm_page_wakeup(fs->mary[0]);
1877                                 fs->mary[0] = NULL;
1878                                 vm_object_pip_wakeup(fs->first_ba->object);
1879                                 unlock_things(fs);
1880                                 if (allow_nofault == 0 ||
1881                                     (curthread->td_flags & TDF_NOFAULT) == 0) {
1882                                         thread_t td;
1883
1884                                         vm_wait_pfault();
1885                                         td = curthread;
1886                                         if (td->td_proc && (td->td_proc->p_flags & P_LOWMEMKILL))
1887                                                 return (KERN_PROTECTION_FAILURE);
1888                                 }
1889                                 return (KERN_TRY_AGAIN);
1890                         }
1891
1892                         /*
1893                          * If it still isn't completely valid (readable),
1894                          * or if a read-ahead-mark is set on the VM page,
1895                          * jump to readrest, else we found the page and
1896                          * can return.
1897                          *
1898                          * We can release the spl once we have marked the
1899                          * page busy.
1900                          */
1901                         if (fs->mary[0]->object != &kernel_object) {
1902                                 if ((fs->mary[0]->valid & VM_PAGE_BITS_ALL) !=
1903                                     VM_PAGE_BITS_ALL) {
1904                                         goto readrest;
1905                                 }
1906                                 if (fs->mary[0]->flags & PG_RAM) {
1907                                         if (debug_cluster)
1908                                                 kprintf("R");
1909                                         vm_page_flag_clear(fs->mary[0], PG_RAM);
1910                                         goto readrest;
1911                                 }
1912                         }
1913                         atomic_clear_int(&fs->first_ba->flags,
1914                                          VM_MAP_BACK_EXCL_HEUR);
1915                         break; /* break to PAGE HAS BEEN FOUND */
1916                 }
1917
1918                 /*
1919                  * Page is not resident, If this is the search termination
1920                  * or the pager might contain the page, allocate a new page.
1921                  */
1922                 if (TRYPAGER(fs) || fs->ba == fs->first_ba) {
1923                         /*
1924                          * If this is a SWAP object we can use the shared
1925                          * lock to check existence of a swap block.  If
1926                          * there isn't one we can skip to the next object.
1927                          *
1928                          * However, if this is the first object we allocate
1929                          * a page now just in case we need to copy to it
1930                          * later.
1931                          */
1932                         if (fs->ba != fs->first_ba &&
1933                             fs->ba->object->type == OBJT_SWAP) {
1934                                 if (swap_pager_haspage_locked(fs->ba->object,
1935                                                               pindex) == 0) {
1936                                         goto next;
1937                                 }
1938                         }
1939
1940                         /*
1941                          * Allocating, must be exclusive.
1942                          */
1943                         atomic_set_int(&fs->first_ba->flags,
1944                                        VM_MAP_BACK_EXCL_HEUR);
1945                         if (fs->ba == fs->first_ba && fs->first_shared) {
1946                                 fs->first_shared = 0;
1947                                 vm_object_pip_wakeup(fs->first_ba->object);
1948                                 unlock_things(fs);
1949                                 return (KERN_TRY_AGAIN);
1950                         }
1951                         if (fs->ba != fs->first_ba && fs->shared) {
1952                                 fs->first_shared = 0;
1953                                 fs->shared = 0;
1954                                 vm_object_pip_wakeup(fs->first_ba->object);
1955                                 unlock_things(fs);
1956                                 return (KERN_TRY_AGAIN);
1957                         }
1958
1959                         /*
1960                          * If the page is beyond the object size we fail
1961                          */
1962                         if (pindex >= fs->ba->object->size) {
1963                                 vm_object_pip_wakeup(fs->first_ba->object);
1964                                 unlock_things(fs);
1965                                 return (KERN_PROTECTION_FAILURE);
1966                         }
1967
1968                         /*
1969                          * Allocate a new page for this object/offset pair.
1970                          *
1971                          * It is possible for the allocation to race, so
1972                          * handle the case.
1973                          */
1974                         fs->mary[0] = NULL;
1975                         if (!vm_page_count_severe()) {
1976                                 fs->mary[0] = vm_page_alloc(fs->ba->object,
1977                                     pindex,
1978                                     ((fs->vp || fs->ba->backing_ba) ?
1979                                         VM_ALLOC_NULL_OK | VM_ALLOC_NORMAL :
1980                                         VM_ALLOC_NULL_OK | VM_ALLOC_NORMAL |
1981                                         VM_ALLOC_USE_GD | VM_ALLOC_ZERO));
1982                         }
1983                         if (fs->mary[0] == NULL) {
1984                                 vm_object_pip_wakeup(fs->first_ba->object);
1985                                 unlock_things(fs);
1986                                 if (allow_nofault == 0 ||
1987                                     (curthread->td_flags & TDF_NOFAULT) == 0) {
1988                                         thread_t td;
1989
1990                                         vm_wait_pfault();
1991                                         td = curthread;
1992                                         if (td->td_proc && (td->td_proc->p_flags & P_LOWMEMKILL))
1993                                                 return (KERN_PROTECTION_FAILURE);
1994                                 }
1995                                 return (KERN_TRY_AGAIN);
1996                         }
1997
1998                         /*
1999                          * Fall through to readrest.  We have a new page which
2000                          * will have to be paged (since m->valid will be 0).
2001                          */
2002                 }
2003
2004 readrest:
2005                 /*
2006                  * We have found an invalid or partially valid page, a
2007                  * page with a read-ahead mark which might be partially or
2008                  * fully valid (and maybe dirty too), or we have allocated
2009                  * a new page.
2010                  *
2011                  * Attempt to fault-in the page if there is a chance that the
2012                  * pager has it, and potentially fault in additional pages
2013                  * at the same time.
2014                  *
2015                  * If TRYPAGER is true then fs.mary[0] will be non-NULL and
2016                  * busied for us.
2017                  */
2018                 if (TRYPAGER(fs)) {
2019                         u_char behavior = vm_map_entry_behavior(fs->entry);
2020                         vm_object_t object;
2021                         vm_page_t first_m;
2022                         int seqaccess;
2023                         int rv;
2024
2025                         if (behavior == MAP_ENTRY_BEHAV_RANDOM)
2026                                 seqaccess = 0;
2027                         else
2028                                 seqaccess = -1;
2029
2030                         /*
2031                          * Doing I/O may synchronously insert additional
2032                          * pages so we can't be shared at this point either.
2033                          *
2034                          * NOTE: We can't free fs->mary[0] here in the
2035                          *       allocated case (fs->ba != fs->first_ba) as
2036                          *       this would require an exclusively locked
2037                          *       VM object.
2038                          */
2039                         if (fs->ba == fs->first_ba && fs->first_shared) {
2040                                 vm_page_deactivate(fs->mary[0]);
2041                                 vm_page_wakeup(fs->mary[0]);
2042                                 fs->mary[0]= NULL;
2043                                 fs->first_shared = 0;
2044                                 vm_object_pip_wakeup(fs->first_ba->object);
2045                                 unlock_things(fs);
2046                                 return (KERN_TRY_AGAIN);
2047                         }
2048                         if (fs->ba != fs->first_ba && fs->shared) {
2049                                 vm_page_deactivate(fs->mary[0]);
2050                                 vm_page_wakeup(fs->mary[0]);
2051                                 fs->mary[0] = NULL;
2052                                 fs->first_shared = 0;
2053                                 fs->shared = 0;
2054                                 vm_object_pip_wakeup(fs->first_ba->object);
2055                                 unlock_things(fs);
2056                                 return (KERN_TRY_AGAIN);
2057                         }
2058
2059                         object = fs->ba->object;
2060                         first_m = NULL;
2061
2062                         /* object is held, no more access to entry or ba's */
2063
2064                         /*
2065                          * Acquire the page data.  We still hold object
2066                          * and the page has been BUSY's.
2067                          *
2068                          * We own the page, but we must re-issue the lookup
2069                          * because the pager may have replaced it (for example,
2070                          * in order to enter a fictitious page into the
2071                          * object).  In this situation the pager will have
2072                          * cleaned up the old page and left the new one
2073                          * busy for us.
2074                          *
2075                          * If we got here through a PG_RAM read-ahead
2076                          * mark the page may be partially dirty and thus
2077                          * not freeable.  Don't bother checking to see
2078                          * if the pager has the page because we can't free
2079                          * it anyway.  We have to depend on the get_page
2080                          * operation filling in any gaps whether there is
2081                          * backing store or not.
2082                          *
2083                          * We must dispose of the page (fs->mary[0]) and also
2084                          * possibly first_m (the fronting layer).  If
2085                          * this is a write fault leave the page intact
2086                          * because we will probably have to copy fs->mary[0]
2087                          * to fs->first_m on the retry.  If this is a
2088                          * read fault we probably won't need the page.
2089                          */
2090                         rv = vm_pager_get_page(object, &fs->mary[0], seqaccess);
2091
2092                         if (rv == VM_PAGER_OK) {
2093                                 ++fs->hardfault;
2094                                 fs->mary[0] = vm_page_lookup(object, pindex);
2095                                 if (fs->mary[0]) {
2096                                         vm_page_activate(fs->mary[0]);
2097                                         vm_page_wakeup(fs->mary[0]);
2098                                         fs->mary[0] = NULL;
2099                                 }
2100
2101                                 if (fs->mary[0]) {
2102                                         /* have page */
2103                                         break;
2104                                 }
2105                                 vm_object_pip_wakeup(fs->first_ba->object);
2106                                 unlock_things(fs);
2107                                 return (KERN_TRY_AGAIN);
2108                         }
2109
2110                         /*
2111                          * If the pager doesn't have the page, continue on
2112                          * to the next object.  Retain the vm_page if this
2113                          * is the first object, we may need to copy into
2114                          * it later.
2115                          */
2116                         if (rv == VM_PAGER_FAIL) {
2117                                 if (fs->ba != fs->first_ba) {
2118                                         vm_page_free(fs->mary[0]);
2119                                         fs->mary[0] = NULL;
2120                                 }
2121                                 goto next;
2122                         }
2123
2124                         /*
2125                          * Remove the bogus page (which does not exist at this
2126                          * object/offset).
2127                          *
2128                          * Also wake up any other process that may want to bring
2129                          * in this page.
2130                          *
2131                          * If this is the top-level object, we must leave the
2132                          * busy page to prevent another process from rushing
2133                          * past us, and inserting the page in that object at
2134                          * the same time that we are.
2135                          */
2136                         if (rv == VM_PAGER_ERROR) {
2137                                 if (curproc) {
2138                                         kprintf("vm_fault: pager read error, "
2139                                                 "pid %d (%s)\n",
2140                                                 curproc->p_pid,
2141                                                 curproc->p_comm);
2142                                 } else {
2143                                         kprintf("vm_fault: pager read error, "
2144                                                 "thread %p (%s)\n",
2145                                                 curthread,
2146                                                 curthread->td_comm);
2147                                 }
2148                         }
2149
2150                         /*
2151                          * I/O error or data outside pager's range.
2152                          */
2153                         if (fs->mary[0]) {
2154                                 vnode_pager_freepage(fs->mary[0]);
2155                                 fs->mary[0] = NULL;
2156                         }
2157                         if (first_m) {
2158                                 vm_page_free(first_m);
2159                                 first_m = NULL;         /* safety */
2160                         }
2161                         vm_object_pip_wakeup(object);
2162                         unlock_things(fs);
2163
2164                         switch(rv) {
2165                         case VM_PAGER_ERROR:
2166                                 return (KERN_FAILURE);
2167                         case VM_PAGER_BAD:
2168                                 return (KERN_PROTECTION_FAILURE);
2169                         default:
2170                                 return (KERN_PROTECTION_FAILURE);
2171                         }
2172
2173 #if 0
2174                         /*
2175                          * Data outside the range of the pager or an I/O error
2176                          *
2177                          * The page may have been wired during the pagein,
2178                          * e.g. by the buffer cache, and cannot simply be
2179                          * freed.  Call vnode_pager_freepage() to deal with it.
2180                          *
2181                          * The object is not held shared so we can safely
2182                          * free the page.
2183                          */
2184                         if (fs->ba != fs->first_ba) {
2185
2186                                 /*
2187                                  * XXX - we cannot just fall out at this
2188                                  * point, m has been freed and is invalid!
2189                                  */
2190                         }
2191
2192                         /*
2193                          * XXX - the check for kernel_map is a kludge to work
2194                          * around having the machine panic on a kernel space
2195                          * fault w/ I/O error.
2196                          */
2197                         if (((fs->map != &kernel_map) &&
2198                             (rv == VM_PAGER_ERROR)) || (rv == VM_PAGER_BAD)) {
2199                                 if (fs->m) {
2200                                         /* from just above */
2201                                         KKASSERT(fs->first_shared == 0);
2202                                         vnode_pager_freepage(fs->m);
2203                                         fs->m = NULL;
2204                                 }
2205                                 /* NOT REACHED */
2206                         }
2207 #endif
2208                 }
2209
2210 next:
2211                 /*
2212                  * We get here if the object has a default pager (or unwiring) 
2213                  * or the pager doesn't have the page.
2214                  *
2215                  * fs->first_m will be used for the COW unless we find a
2216                  * deeper page to be mapped read-only, in which case the
2217                  * unlock*(fs) will free first_m.
2218                  */
2219                 if (fs->ba == fs->first_ba)
2220                         fs->first_m = fs->mary[0];
2221
2222                 /*
2223                  * Move on to the next object.  The chain lock should prevent
2224                  * the backing_object from getting ripped out from under us.
2225                  *
2226                  * The object lock for the next object is governed by
2227                  * fs->shared.
2228                  */
2229                 next_ba = fs->ba->backing_ba;
2230                 if (next_ba == NULL) {
2231                         /*
2232                          * If there's no object left, fill the page in the top
2233                          * object with zeros.
2234                          */
2235                         if (fs->ba != fs->first_ba) {
2236                                 vm_object_pip_wakeup(fs->ba->object);
2237                                 vm_object_drop(fs->ba->object);
2238                                 fs->ba = fs->first_ba;
2239                                 pindex = first_pindex;
2240                                 fs->mary[0] = fs->first_m;
2241                         }
2242                         fs->first_m = NULL;
2243
2244                         /*
2245                          * Zero the page and mark it valid.
2246                          */
2247                         vm_page_zero_fill(fs->mary[0]);
2248                         mycpu->gd_cnt.v_zfod++;
2249                         fs->mary[0]->valid = VM_PAGE_BITS_ALL;
2250                         break;  /* break to PAGE HAS BEEN FOUND */
2251                 }
2252
2253                 if (fs->shared)
2254                         vm_object_hold_shared(next_ba->object);
2255                 else
2256                         vm_object_hold(next_ba->object);
2257                 KKASSERT(next_ba == fs->ba->backing_ba);
2258                 pindex -= OFF_TO_IDX(fs->ba->offset);
2259                 pindex += OFF_TO_IDX(next_ba->offset);
2260
2261                 if (fs->ba != fs->first_ba) {
2262                         vm_object_pip_wakeup(fs->ba->object);
2263                         vm_object_lock_swap();  /* flip ba/next_ba */
2264                         vm_object_drop(fs->ba->object);
2265                 }
2266                 fs->ba = next_ba;
2267                 vm_object_pip_add(next_ba->object, 1);
2268         }
2269
2270         /*
2271          * PAGE HAS BEEN FOUND. [Loop invariant still holds -- the object lock
2272          * is held.]
2273          *
2274          * object still held.
2275          * vm_map may not be locked (determined by fs->lookup_still_valid)
2276          *
2277          * local shared variable may be different from fs->shared.
2278          *
2279          * If the page is being written, but isn't already owned by the
2280          * top-level object, we have to copy it into a new page owned by the
2281          * top-level object.
2282          */
2283         KASSERT((fs->mary[0]->busy_count & PBUSY_LOCKED) != 0,
2284                 ("vm_fault: not busy after main loop"));
2285
2286         if (fs->ba != fs->first_ba) {
2287                 /*
2288                  * We only really need to copy if we want to write it.
2289                  */
2290                 if (fault_type & VM_PROT_WRITE) {
2291 #if 0
2292                         /* CODE REFACTOR IN PROGRESS, REMOVE OPTIMIZATION */
2293                         /*
2294                          * This allows pages to be virtually copied from a 
2295                          * backing_object into the first_object, where the 
2296                          * backing object has no other refs to it, and cannot
2297                          * gain any more refs.  Instead of a bcopy, we just 
2298                          * move the page from the backing object to the 
2299                          * first object.  Note that we must mark the page 
2300                          * dirty in the first object so that it will go out 
2301                          * to swap when needed.
2302                          */
2303                         if (virtual_copy_ok(fs)) {
2304                                 /*
2305                                  * (first_m) and (m) are both busied.  We have
2306                                  * move (m) into (first_m)'s object/pindex
2307                                  * in an atomic fashion, then free (first_m).
2308                                  *
2309                                  * first_object is held so second remove
2310                                  * followed by the rename should wind
2311                                  * up being atomic.  vm_page_free() might
2312                                  * block so we don't do it until after the
2313                                  * rename.
2314                                  */
2315                                 vm_page_protect(fs->first_m, VM_PROT_NONE);
2316                                 vm_page_remove(fs->first_m);
2317                                 vm_page_rename(fs->mary[0],
2318                                                fs->first_ba->object,
2319                                                first_pindex);
2320                                 vm_page_free(fs->first_m);
2321                                 fs->first_m = fs->mary[0];
2322                                 fs->mary[0] = NULL;
2323                                 mycpu->gd_cnt.v_cow_optim++;
2324                         } else
2325 #endif
2326                         {
2327                                 /*
2328                                  * Oh, well, lets copy it.
2329                                  *
2330                                  * We used to unmap the original page here
2331                                  * because vm_fault_page() didn't and this
2332                                  * would cause havoc for the umtx*() code
2333                                  * and the procfs code.
2334                                  *
2335                                  * This is no longer necessary.  The
2336                                  * vm_fault_page() routine will now unmap the
2337                                  * page after a COW, and the umtx code will
2338                                  * recover on its own.
2339                                  */
2340                                 /*
2341                                  * NOTE: Since fs->mary[0] is a backing page,
2342                                  *       it is read-only, so there isn't any
2343                                  *       copy race vs writers.
2344                                  */
2345                                 KKASSERT(fs->first_shared == 0);
2346                                 vm_page_copy(fs->mary[0], fs->first_m);
2347                                 /* pmap_remove_specific(
2348                                     &curthread->td_lwp->lwp_vmspace->vm_pmap,
2349                                     fs->mary[0]); */
2350                         }
2351
2352                         /*
2353                          * We no longer need the old page or object.
2354                          */
2355                         if (fs->mary[0])
2356                                 release_page(fs);
2357
2358                         /*
2359                          * fs->ba != fs->first_ba due to above conditional
2360                          */
2361                         vm_object_pip_wakeup(fs->ba->object);
2362                         vm_object_drop(fs->ba->object);
2363                         fs->ba = fs->first_ba;
2364
2365                         /*
2366                          * Only use the new page below...
2367                          */
2368                         mycpu->gd_cnt.v_cow_faults++;
2369                         fs->mary[0] = fs->first_m;
2370                         pindex = first_pindex;
2371                 } else {
2372                         /*
2373                          * If it wasn't a write fault avoid having to copy
2374                          * the page by mapping it read-only from backing
2375                          * store.  The process is not allowed to modify
2376                          * backing pages.
2377                          */
2378                         fs->prot &= ~VM_PROT_WRITE;
2379                 }
2380         }
2381
2382         /*
2383          * Relock the map if necessary, then check the generation count.
2384          * relock_map() will update fs->timestamp to account for the
2385          * relocking if necessary.
2386          *
2387          * If the count has changed after relocking then all sorts of
2388          * crap may have happened and we have to retry.
2389          *
2390          * NOTE: The relock_map() can fail due to a deadlock against
2391          *       the vm_page we are holding BUSY.
2392          */
2393         KKASSERT(fs->lookup_still_valid != 0);
2394 #if 0
2395         if (fs->lookup_still_valid == 0 && fs->map) {
2396                 if (relock_map(fs) ||
2397                     fs->map->timestamp != fs->map_generation) {
2398                         release_page(fs);
2399                         vm_object_pip_wakeup(fs->first_ba->object);
2400                         unlock_things(fs);
2401                         return (KERN_TRY_AGAIN);
2402                 }
2403         }
2404 #endif
2405
2406         /*
2407          * If the fault is a write, we know that this page is being
2408          * written NOW so dirty it explicitly to save on pmap_is_modified()
2409          * calls later.
2410          *
2411          * If this is a NOSYNC mmap we do not want to set PG_NOSYNC
2412          * if the page is already dirty to prevent data written with
2413          * the expectation of being synced from not being synced.
2414          * Likewise if this entry does not request NOSYNC then make
2415          * sure the page isn't marked NOSYNC.  Applications sharing
2416          * data should use the same flags to avoid ping ponging.
2417          *
2418          * Also tell the backing pager, if any, that it should remove
2419          * any swap backing since the page is now dirty.
2420          */
2421         vm_page_activate(fs->mary[0]);
2422         if (fs->prot & VM_PROT_WRITE) {
2423                 vm_object_set_writeable_dirty(fs->mary[0]->object);
2424                 vm_set_nosync(fs->mary[0], fs->entry);
2425                 if (fs->fault_flags & VM_FAULT_DIRTY) {
2426                         vm_page_dirty(fs->mary[0]);
2427                         if (fs->mary[0]->flags & PG_SWAPPED) {
2428                                 /*
2429                                  * If the page is swapped out we have to call
2430                                  * swap_pager_unswapped() which requires an
2431                                  * exclusive object lock.  If we are shared,
2432                                  * we must clear the shared flag and retry.
2433                                  */
2434                                 if ((fs->ba == fs->first_ba &&
2435                                      fs->first_shared) ||
2436                                     (fs->ba != fs->first_ba && fs->shared)) {
2437                                         vm_page_wakeup(fs->mary[0]);
2438                                         fs->mary[0] = NULL;
2439                                         if (fs->ba == fs->first_ba)
2440                                                 fs->first_shared = 0;
2441                                         else
2442                                                 fs->shared = 0;
2443                                         vm_object_pip_wakeup(
2444                                                         fs->first_ba->object);
2445                                         unlock_things(fs);
2446                                         return (KERN_TRY_AGAIN);
2447                                 }
2448                                 swap_pager_unswapped(fs->mary[0]);
2449                         }
2450                 }
2451         }
2452
2453         /*
2454          * We found our page at backing layer ba.  Leave the layer state
2455          * intact.
2456          */
2457
2458         vm_object_pip_wakeup(fs->first_ba->object);
2459 #if 0
2460         if (fs->ba != fs->first_ba)
2461                 vm_object_drop(fs->ba->object);
2462 #endif
2463
2464         /*
2465          * Page had better still be busy.  We are still locked up and 
2466          * fs->ba->object will have another PIP reference for the case
2467          * where fs->ba != fs->first_ba.
2468          */
2469         KASSERT(fs->mary[0]->busy_count & PBUSY_LOCKED,
2470                 ("vm_fault: page %p not busy!", fs->mary[0]));
2471
2472         /*
2473          * Sanity check: page must be completely valid or it is not fit to
2474          * map into user space.  vm_pager_get_pages() ensures this.
2475          */
2476         if (fs->mary[0]->valid != VM_PAGE_BITS_ALL) {
2477                 vm_page_zero_invalid(fs->mary[0], TRUE);
2478                 kprintf("Warning: page %p partially invalid on fault\n",
2479                         fs->mary[0]);
2480         }
2481
2482         return (KERN_SUCCESS);
2483 }
2484
2485 /*
2486  * Wire down a range of virtual addresses in a map.  The entry in question
2487  * should be marked in-transition and the map must be locked.  We must
2488  * release the map temporarily while faulting-in the page to avoid a
2489  * deadlock.  Note that the entry may be clipped while we are blocked but
2490  * will never be freed.
2491  *
2492  * map must be locked on entry.
2493  */
2494 int
2495 vm_fault_wire(vm_map_t map, vm_map_entry_t entry,
2496               boolean_t user_wire, int kmflags)
2497 {
2498         boolean_t fictitious;
2499         vm_offset_t start;
2500         vm_offset_t end;
2501         vm_offset_t va;
2502         pmap_t pmap;
2503         int rv;
2504         int wire_prot;
2505         int fault_flags;
2506         vm_page_t m;
2507
2508         if (user_wire) {
2509                 wire_prot = VM_PROT_READ;
2510                 fault_flags = VM_FAULT_USER_WIRE;
2511         } else {
2512                 wire_prot = VM_PROT_READ | VM_PROT_WRITE;
2513                 fault_flags = VM_FAULT_CHANGE_WIRING;
2514         }
2515         if (kmflags & KM_NOTLBSYNC)
2516                 wire_prot |= VM_PROT_NOSYNC;
2517
2518         pmap = vm_map_pmap(map);
2519         start = entry->ba.start;
2520         end = entry->ba.end;
2521
2522         switch(entry->maptype) {
2523         case VM_MAPTYPE_NORMAL:
2524         case VM_MAPTYPE_VPAGETABLE:
2525                 fictitious = entry->ba.object &&
2526                             ((entry->ba.object->type == OBJT_DEVICE) ||
2527                              (entry->ba.object->type == OBJT_MGTDEVICE));
2528                 break;
2529         case VM_MAPTYPE_UKSMAP:
2530                 fictitious = TRUE;
2531                 break;
2532         default:
2533                 fictitious = FALSE;
2534                 break;
2535         }
2536
2537         if (entry->eflags & MAP_ENTRY_KSTACK)
2538                 start += PAGE_SIZE;
2539         map->timestamp++;
2540         vm_map_unlock(map);
2541
2542         /*
2543          * We simulate a fault to get the page and enter it in the physical
2544          * map.
2545          */
2546         for (va = start; va < end; va += PAGE_SIZE) {
2547                 rv = vm_fault(map, va, wire_prot, fault_flags);
2548                 if (rv) {
2549                         while (va > start) {
2550                                 va -= PAGE_SIZE;
2551                                 m = pmap_unwire(pmap, va);
2552                                 if (m && !fictitious) {
2553                                         vm_page_busy_wait(m, FALSE, "vmwrpg");
2554                                         vm_page_unwire(m, 1);
2555                                         vm_page_wakeup(m);
2556                                 }
2557                         }
2558                         goto done;
2559                 }
2560         }
2561         rv = KERN_SUCCESS;
2562 done:
2563         vm_map_lock(map);
2564
2565         return (rv);
2566 }
2567
2568 /*
2569  * Unwire a range of virtual addresses in a map.  The map should be
2570  * locked.
2571  */
2572 void
2573 vm_fault_unwire(vm_map_t map, vm_map_entry_t entry)
2574 {
2575         boolean_t fictitious;
2576         vm_offset_t start;
2577         vm_offset_t end;
2578         vm_offset_t va;
2579         pmap_t pmap;
2580         vm_page_t m;
2581
2582         pmap = vm_map_pmap(map);
2583         start = entry->ba.start;
2584         end = entry->ba.end;
2585         fictitious = entry->ba.object &&
2586                         ((entry->ba.object->type == OBJT_DEVICE) ||
2587                          (entry->ba.object->type == OBJT_MGTDEVICE));
2588         if (entry->eflags & MAP_ENTRY_KSTACK)
2589                 start += PAGE_SIZE;
2590
2591         /*
2592          * Since the pages are wired down, we must be able to get their
2593          * mappings from the physical map system.
2594          */
2595         for (va = start; va < end; va += PAGE_SIZE) {
2596                 m = pmap_unwire(pmap, va);
2597                 if (m && !fictitious) {
2598                         vm_page_busy_wait(m, FALSE, "vmwrpg");
2599                         vm_page_unwire(m, 1);
2600                         vm_page_wakeup(m);
2601                 }
2602         }
2603 }
2604
2605 /*
2606  * Simulate write faults to bring all data into the head object, return
2607  * KERN_SUCCESS on success (which should be always unless the system runs
2608  * out of memory).
2609  *
2610  * The caller will handle destroying the backing_ba's.
2611  */
2612 int
2613 vm_fault_collapse(vm_map_t map, vm_map_entry_t entry)
2614 {
2615         struct faultstate fs;
2616         vm_ooffset_t scan;
2617         vm_pindex_t pindex;
2618         vm_object_t object;
2619         int rv;
2620         int all_shadowed;
2621
2622         bzero(&fs, sizeof(fs));
2623         object = entry->ba.object;
2624
2625         fs.first_prot = entry->max_protection | /* optional VM_PROT_EXECUTE */
2626                         VM_PROT_READ | VM_PROT_WRITE | VM_PROT_OVERRIDE_WRITE;
2627         fs.fault_flags = VM_FAULT_NORMAL;
2628         fs.map = map;
2629         fs.entry = entry;
2630         fs.lookup_still_valid = -1;     /* leave map atomically locked */
2631         fs.first_ba = &entry->ba;
2632         fs.first_ba_held = -1;          /* leave object held */
2633
2634         /* fs.hardfault */
2635
2636         vm_object_hold(object);
2637         rv = KERN_SUCCESS;
2638
2639         scan = entry->ba.start;
2640         all_shadowed = 1;
2641
2642         while (scan < entry->ba.end) {
2643                 pindex = OFF_TO_IDX(entry->ba.offset + (scan - entry->ba.start));
2644
2645                 if (vm_page_lookup(object, pindex)) {
2646                         scan += PAGE_SIZE;
2647                         continue;
2648                 }
2649
2650                 all_shadowed = 0;
2651                 fs.ba = fs.first_ba;
2652                 fs.prot = fs.first_prot;
2653
2654                 rv = vm_fault_object(&fs, pindex, fs.first_prot, 1);
2655                 if (rv == KERN_TRY_AGAIN)
2656                         continue;
2657                 if (rv != KERN_SUCCESS)
2658                         break;
2659                 vm_page_flag_set(fs.mary[0], PG_REFERENCED);
2660                 vm_page_activate(fs.mary[0]);
2661                 vm_page_wakeup(fs.mary[0]);
2662                 scan += PAGE_SIZE;
2663         }
2664         KKASSERT(entry->ba.object == object);
2665         vm_object_drop(object);
2666
2667         /*
2668          * If the fronting object did not have every page we have to clear
2669          * the pmap range due to the pages being changed so we can fault-in
2670          * the proper pages.
2671          */
2672         if (all_shadowed == 0)
2673                 pmap_remove(map->pmap, entry->ba.start, entry->ba.end);
2674
2675         return rv;
2676 }
2677
2678 /*
2679  * Copy all of the pages from one map entry to another.  If the source
2680  * is wired down we just use vm_page_lookup().  If not we use
2681  * vm_fault_object().
2682  *
2683  * The source and destination maps must be locked for write.
2684  * The source and destination maps token must be held
2685  *
2686  * No other requirements.
2687  *
2688  * XXX do segment optimization
2689  */
2690 void
2691 vm_fault_copy_entry(vm_map_t dst_map, vm_map_t src_map,
2692                     vm_map_entry_t dst_entry, vm_map_entry_t src_entry)
2693 {
2694         vm_object_t dst_object;
2695         vm_object_t src_object;
2696         vm_ooffset_t dst_offset;
2697         vm_ooffset_t src_offset;
2698         vm_prot_t prot;
2699         vm_offset_t vaddr;
2700         vm_page_t dst_m;
2701         vm_page_t src_m;
2702
2703         src_object = src_entry->ba.object;
2704         src_offset = src_entry->ba.offset;
2705
2706         /*
2707          * Create the top-level object for the destination entry. (Doesn't
2708          * actually shadow anything - we copy the pages directly.)
2709          */
2710         vm_map_entry_allocate_object(dst_entry);
2711         dst_object = dst_entry->ba.object;
2712
2713         prot = dst_entry->max_protection;
2714
2715         /*
2716          * Loop through all of the pages in the entry's range, copying each
2717          * one from the source object (it should be there) to the destination
2718          * object.
2719          */
2720         vm_object_hold(src_object);
2721         vm_object_hold(dst_object);
2722
2723         for (vaddr = dst_entry->ba.start, dst_offset = 0;
2724              vaddr < dst_entry->ba.end;
2725              vaddr += PAGE_SIZE, dst_offset += PAGE_SIZE) {
2726
2727                 /*
2728                  * Allocate a page in the destination object
2729                  */
2730                 do {
2731                         dst_m = vm_page_alloc(dst_object,
2732                                               OFF_TO_IDX(dst_offset),
2733                                               VM_ALLOC_NORMAL);
2734                         if (dst_m == NULL) {
2735                                 vm_wait(0);
2736                         }
2737                 } while (dst_m == NULL);
2738
2739                 /*
2740                  * Find the page in the source object, and copy it in.
2741                  * (Because the source is wired down, the page will be in
2742                  * memory.)
2743                  */
2744                 src_m = vm_page_lookup(src_object,
2745                                        OFF_TO_IDX(dst_offset + src_offset));
2746                 if (src_m == NULL)
2747                         panic("vm_fault_copy_wired: page missing");
2748
2749                 vm_page_copy(src_m, dst_m);
2750
2751                 /*
2752                  * Enter it in the pmap...
2753                  */
2754                 pmap_enter(dst_map->pmap, vaddr, dst_m, prot, FALSE, dst_entry);
2755
2756                 /*
2757                  * Mark it no longer busy, and put it on the active list.
2758                  */
2759                 vm_page_activate(dst_m);
2760                 vm_page_wakeup(dst_m);
2761         }
2762         vm_object_drop(dst_object);
2763         vm_object_drop(src_object);
2764 }
2765
2766 #if 0
2767
2768 /*
2769  * This routine checks around the requested page for other pages that
2770  * might be able to be faulted in.  This routine brackets the viable
2771  * pages for the pages to be paged in.
2772  *
2773  * Inputs:
2774  *      m, rbehind, rahead
2775  *
2776  * Outputs:
2777  *  marray (array of vm_page_t), reqpage (index of requested page)
2778  *
2779  * Return value:
2780  *  number of pages in marray
2781  */
2782 static int
2783 vm_fault_additional_pages(vm_page_t m, int rbehind, int rahead,
2784                           vm_page_t *marray, int *reqpage)
2785 {
2786         int i,j;
2787         vm_object_t object;
2788         vm_pindex_t pindex, startpindex, endpindex, tpindex;
2789         vm_page_t rtm;
2790         int cbehind, cahead;
2791
2792         object = m->object;
2793         pindex = m->pindex;
2794
2795         /*
2796          * we don't fault-ahead for device pager
2797          */
2798         if ((object->type == OBJT_DEVICE) ||
2799             (object->type == OBJT_MGTDEVICE)) {
2800                 *reqpage = 0;
2801                 marray[0] = m;
2802                 return 1;
2803         }
2804
2805         /*
2806          * if the requested page is not available, then give up now
2807          */
2808         if (!vm_pager_has_page(object, pindex, &cbehind, &cahead)) {
2809                 *reqpage = 0;   /* not used by caller, fix compiler warn */
2810                 return 0;
2811         }
2812
2813         if ((cbehind == 0) && (cahead == 0)) {
2814                 *reqpage = 0;
2815                 marray[0] = m;
2816                 return 1;
2817         }
2818
2819         if (rahead > cahead) {
2820                 rahead = cahead;
2821         }
2822
2823         if (rbehind > cbehind) {
2824                 rbehind = cbehind;
2825         }
2826
2827         /*
2828          * Do not do any readahead if we have insufficient free memory.
2829          *
2830          * XXX code was broken disabled before and has instability
2831          * with this conditonal fixed, so shortcut for now.
2832          */
2833         if (burst_fault == 0 || vm_page_count_severe()) {
2834                 marray[0] = m;
2835                 *reqpage = 0;
2836                 return 1;
2837         }
2838
2839         /*
2840          * scan backward for the read behind pages -- in memory 
2841          *
2842          * Assume that if the page is not found an interrupt will not
2843          * create it.  Theoretically interrupts can only remove (busy)
2844          * pages, not create new associations.
2845          */
2846         if (pindex > 0) {
2847                 if (rbehind > pindex) {
2848                         rbehind = pindex;
2849                         startpindex = 0;
2850                 } else {
2851                         startpindex = pindex - rbehind;
2852                 }
2853
2854                 vm_object_hold(object);
2855                 for (tpindex = pindex; tpindex > startpindex; --tpindex) {
2856                         if (vm_page_lookup(object, tpindex - 1))
2857                                 break;
2858                 }
2859
2860                 i = 0;
2861                 while (tpindex < pindex) {
2862                         rtm = vm_page_alloc(object, tpindex, VM_ALLOC_SYSTEM |
2863                                                              VM_ALLOC_NULL_OK);
2864                         if (rtm == NULL) {
2865                                 for (j = 0; j < i; j++) {
2866                                         vm_page_free(marray[j]);
2867                                 }
2868                                 vm_object_drop(object);
2869                                 marray[0] = m;
2870                                 *reqpage = 0;
2871                                 return 1;
2872                         }
2873                         marray[i] = rtm;
2874                         ++i;
2875                         ++tpindex;
2876                 }
2877                 vm_object_drop(object);
2878         } else {
2879                 i = 0;
2880         }
2881
2882         /*
2883          * Assign requested page
2884          */
2885         marray[i] = m;
2886         *reqpage = i;
2887         ++i;
2888
2889         /*
2890          * Scan forwards for read-ahead pages
2891          */
2892         tpindex = pindex + 1;
2893         endpindex = tpindex + rahead;
2894         if (endpindex > object->size)
2895                 endpindex = object->size;
2896
2897         vm_object_hold(object);
2898         while (tpindex < endpindex) {
2899                 if (vm_page_lookup(object, tpindex))
2900                         break;
2901                 rtm = vm_page_alloc(object, tpindex, VM_ALLOC_SYSTEM |
2902                                                      VM_ALLOC_NULL_OK);
2903                 if (rtm == NULL)
2904                         break;
2905                 marray[i] = rtm;
2906                 ++i;
2907                 ++tpindex;
2908         }
2909         vm_object_drop(object);
2910
2911         return (i);
2912 }
2913
2914 #endif
2915
2916 /*
2917  * vm_prefault() provides a quick way of clustering pagefaults into a
2918  * processes address space.  It is a "cousin" of pmap_object_init_pt,
2919  * except it runs at page fault time instead of mmap time.
2920  *
2921  * vm.fast_fault        Enables pre-faulting zero-fill pages
2922  *
2923  * vm.prefault_pages    Number of pages (1/2 negative, 1/2 positive) to
2924  *                      prefault.  Scan stops in either direction when
2925  *                      a page is found to already exist.
2926  *
2927  * This code used to be per-platform pmap_prefault().  It is now
2928  * machine-independent and enhanced to also pre-fault zero-fill pages
2929  * (see vm.fast_fault) as well as make them writable, which greatly
2930  * reduces the number of page faults programs incur.
2931  *
2932  * Application performance when pre-faulting zero-fill pages is heavily
2933  * dependent on the application.  Very tiny applications like /bin/echo
2934  * lose a little performance while applications of any appreciable size
2935  * gain performance.  Prefaulting multiple pages also reduces SMP
2936  * congestion and can improve SMP performance significantly.
2937  *
2938  * NOTE!  prot may allow writing but this only applies to the top level
2939  *        object.  If we wind up mapping a page extracted from a backing
2940  *        object we have to make sure it is read-only.
2941  *
2942  * NOTE!  The caller has already handled any COW operations on the
2943  *        vm_map_entry via the normal fault code.  Do NOT call this
2944  *        shortcut unless the normal fault code has run on this entry.
2945  *
2946  * The related map must be locked.
2947  * No other requirements.
2948  */
2949 __read_mostly static int vm_prefault_pages = 8;
2950 SYSCTL_INT(_vm, OID_AUTO, prefault_pages, CTLFLAG_RW, &vm_prefault_pages, 0,
2951            "Maximum number of pages to pre-fault");
2952 __read_mostly static int vm_fast_fault = 1;
2953 SYSCTL_INT(_vm, OID_AUTO, fast_fault, CTLFLAG_RW, &vm_fast_fault, 0,
2954            "Burst fault zero-fill regions");
2955
2956 /*
2957  * Set PG_NOSYNC if the map entry indicates so, but only if the page
2958  * is not already dirty by other means.  This will prevent passive
2959  * filesystem syncing as well as 'sync' from writing out the page.
2960  */
2961 static void
2962 vm_set_nosync(vm_page_t m, vm_map_entry_t entry)
2963 {
2964         if (entry->eflags & MAP_ENTRY_NOSYNC) {
2965                 if (m->dirty == 0)
2966                         vm_page_flag_set(m, PG_NOSYNC);
2967         } else {
2968                 vm_page_flag_clear(m, PG_NOSYNC);
2969         }
2970 }
2971
2972 static void
2973 vm_prefault(pmap_t pmap, vm_offset_t addra, vm_map_entry_t entry, int prot,
2974             int fault_flags)
2975 {
2976         vm_map_backing_t ba;    /* first ba */
2977         struct lwp *lp;
2978         vm_page_t m;
2979         vm_offset_t addr;
2980         vm_pindex_t index;
2981         vm_pindex_t pindex;
2982         vm_object_t object;
2983         int pprot;
2984         int i;
2985         int noneg;
2986         int nopos;
2987         int maxpages;
2988
2989         /*
2990          * Get stable max count value, disabled if set to 0
2991          */
2992         maxpages = vm_prefault_pages;
2993         cpu_ccfence();
2994         if (maxpages <= 0)
2995                 return;
2996
2997         /*
2998          * We do not currently prefault mappings that use virtual page
2999          * tables.  We do not prefault foreign pmaps.
3000          */
3001         if (entry->maptype != VM_MAPTYPE_NORMAL)
3002                 return;
3003         lp = curthread->td_lwp;
3004         if (lp == NULL || (pmap != vmspace_pmap(lp->lwp_vmspace)))
3005                 return;
3006
3007         /*
3008          * Limit pre-fault count to 1024 pages.
3009          */
3010         if (maxpages > 1024)
3011                 maxpages = 1024;
3012
3013         ba = &entry->ba;
3014         object = entry->ba.object;
3015         KKASSERT(object != NULL);
3016
3017         /*
3018          * NOTE: VM_FAULT_DIRTY allowed later so must hold object exclusively
3019          *       now (or do something more complex XXX).
3020          */
3021         vm_object_hold(object);
3022
3023         noneg = 0;
3024         nopos = 0;
3025         for (i = 0; i < maxpages; ++i) {
3026                 vm_object_t lobject;
3027                 vm_object_t nobject;
3028                 vm_map_backing_t last_ba;       /* last ba */
3029                 vm_map_backing_t next_ba;       /* last ba */
3030                 int allocated = 0;
3031                 int error;
3032
3033                 /*
3034                  * This can eat a lot of time on a heavily contended
3035                  * machine so yield on the tick if needed.
3036                  */
3037                 if ((i & 7) == 7)
3038                         lwkt_yield();
3039
3040                 /*
3041                  * Calculate the page to pre-fault, stopping the scan in
3042                  * each direction separately if the limit is reached.
3043                  */
3044                 if (i & 1) {
3045                         if (noneg)
3046                                 continue;
3047                         addr = addra - ((i + 1) >> 1) * PAGE_SIZE;
3048                 } else {
3049                         if (nopos)
3050                                 continue;
3051                         addr = addra + ((i + 2) >> 1) * PAGE_SIZE;
3052                 }
3053                 if (addr < entry->ba.start) {
3054                         noneg = 1;
3055                         if (noneg && nopos)
3056                                 break;
3057                         continue;
3058                 }
3059                 if (addr >= entry->ba.end) {
3060                         nopos = 1;
3061                         if (noneg && nopos)
3062                                 break;
3063                         continue;
3064                 }
3065
3066                 /*
3067                  * Skip pages already mapped, and stop scanning in that
3068                  * direction.  When the scan terminates in both directions
3069                  * we are done.
3070                  */
3071                 if (pmap_prefault_ok(pmap, addr) == 0) {
3072                         if (i & 1)
3073                                 noneg = 1;
3074                         else
3075                                 nopos = 1;
3076                         if (noneg && nopos)
3077                                 break;
3078                         continue;
3079                 }
3080
3081                 /*
3082                  * Follow the backing layers to obtain the page to be mapped
3083                  * into the pmap.
3084                  *
3085                  * If we reach the terminal object without finding a page
3086                  * and we determine it would be advantageous, then allocate
3087                  * a zero-fill page for the base object.  The base object
3088                  * is guaranteed to be OBJT_DEFAULT for this case.
3089                  *
3090                  * In order to not have to check the pager via *haspage*()
3091                  * we stop if any non-default object is encountered.  e.g.
3092                  * a vnode or swap object would stop the loop.
3093                  */
3094                 index = ((addr - entry->ba.start) + entry->ba.offset) >>
3095                         PAGE_SHIFT;
3096                 last_ba = ba;
3097                 lobject = object;
3098                 pindex = index;
3099                 pprot = prot;
3100
3101                 /*vm_object_hold(lobject); implied */
3102
3103                 while ((m = vm_page_lookup_busy_try(lobject, pindex,
3104                                                     TRUE, &error)) == NULL) {
3105                         if (lobject->type != OBJT_DEFAULT)
3106                                 break;
3107                         if ((next_ba = last_ba->backing_ba) == NULL) {
3108                                 if (vm_fast_fault == 0)
3109                                         break;
3110                                 if ((prot & VM_PROT_WRITE) == 0 ||
3111                                     vm_page_count_min(0)) {
3112                                         break;
3113                                 }
3114
3115                                 /*
3116                                  * NOTE: Allocated from base object
3117                                  */
3118                                 m = vm_page_alloc(object, index,
3119                                                   VM_ALLOC_NORMAL |
3120                                                   VM_ALLOC_ZERO |
3121                                                   VM_ALLOC_USE_GD |
3122                                                   VM_ALLOC_NULL_OK);
3123                                 if (m == NULL)
3124                                         break;
3125                                 allocated = 1;
3126                                 pprot = prot;
3127                                 /* lobject = object .. not needed */
3128                                 break;
3129                         }
3130                         if (next_ba->offset & PAGE_MASK)
3131                                 break;
3132                         nobject = next_ba->object;
3133                         vm_object_hold(nobject);
3134                         pindex -= last_ba->offset >> PAGE_SHIFT;
3135                         pindex += next_ba->offset >> PAGE_SHIFT;
3136                         if (last_ba != ba) {
3137                                 vm_object_lock_swap();
3138                                 vm_object_drop(lobject);
3139                         }
3140                         lobject = nobject;
3141                         last_ba = next_ba;
3142                         pprot &= ~VM_PROT_WRITE;
3143                 }
3144
3145                 /*
3146                  * NOTE: A non-NULL (m) will be associated with lobject if
3147                  *       it was found there, otherwise it is probably a
3148                  *       zero-fill page associated with the base object.
3149                  *
3150                  * Give-up if no page is available.
3151                  */
3152                 if (m == NULL) {
3153                         if (last_ba != ba)
3154                                 vm_object_drop(lobject);
3155                         break;
3156                 }
3157
3158                 /*
3159                  * The object must be marked dirty if we are mapping a
3160                  * writable page.  m->object is either lobject or object,
3161                  * both of which are still held.  Do this before we
3162                  * potentially drop the object.
3163                  */
3164                 if (pprot & VM_PROT_WRITE)
3165                         vm_object_set_writeable_dirty(m->object);
3166
3167                 /*
3168                  * Do not conditionalize on PG_RAM.  If pages are present in
3169                  * the VM system we assume optimal caching.  If caching is
3170                  * not optimal the I/O gravy train will be restarted when we
3171                  * hit an unavailable page.  We do not want to try to restart
3172                  * the gravy train now because we really don't know how much
3173                  * of the object has been cached.  The cost for restarting
3174                  * the gravy train should be low (since accesses will likely
3175                  * be I/O bound anyway).
3176                  */
3177                 if (last_ba != ba)
3178                         vm_object_drop(lobject);
3179
3180                 /*
3181                  * Enter the page into the pmap if appropriate.  If we had
3182                  * allocated the page we have to place it on a queue.  If not
3183                  * we just have to make sure it isn't on the cache queue
3184                  * (pages on the cache queue are not allowed to be mapped).
3185                  */
3186                 if (allocated) {
3187                         /*
3188                          * Page must be zerod.
3189                          */
3190                         vm_page_zero_fill(m);
3191                         mycpu->gd_cnt.v_zfod++;
3192                         m->valid = VM_PAGE_BITS_ALL;
3193
3194                         /*
3195                          * Handle dirty page case
3196                          */
3197                         if (pprot & VM_PROT_WRITE)
3198                                 vm_set_nosync(m, entry);
3199                         pmap_enter(pmap, addr, m, pprot, 0, entry);
3200 #if 0
3201                         /* REMOVE ME, a burst counts as one fault */
3202                         mycpu->gd_cnt.v_vm_faults++;
3203                         if (curthread->td_lwp)
3204                                 ++curthread->td_lwp->lwp_ru.ru_minflt;
3205 #endif
3206                         vm_page_deactivate(m);
3207                         if (pprot & VM_PROT_WRITE) {
3208                                 /*vm_object_set_writeable_dirty(m->object);*/
3209                                 vm_set_nosync(m, entry);
3210                                 if (fault_flags & VM_FAULT_DIRTY) {
3211                                         vm_page_dirty(m);
3212                                         /*XXX*/
3213                                         swap_pager_unswapped(m);
3214                                 }
3215                         }
3216                         vm_page_wakeup(m);
3217                 } else if (error) {
3218                         /* couldn't busy page, no wakeup */
3219                 } else if (
3220                     ((m->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
3221                     (m->flags & PG_FICTITIOUS) == 0) {
3222                         /*
3223                          * A fully valid page not undergoing soft I/O can
3224                          * be immediately entered into the pmap.
3225                          */
3226                         if ((m->queue - m->pc) == PQ_CACHE)
3227                                 vm_page_deactivate(m);
3228                         if (pprot & VM_PROT_WRITE) {
3229                                 /*vm_object_set_writeable_dirty(m->object);*/
3230                                 vm_set_nosync(m, entry);
3231                                 if (fault_flags & VM_FAULT_DIRTY) {
3232                                         vm_page_dirty(m);
3233                                         /*XXX*/
3234                                         swap_pager_unswapped(m);
3235                                 }
3236                         }
3237                         if (pprot & VM_PROT_WRITE)
3238                                 vm_set_nosync(m, entry);
3239                         pmap_enter(pmap, addr, m, pprot, 0, entry);
3240 #if 0
3241                         /* REMOVE ME, a burst counts as one fault */
3242                         mycpu->gd_cnt.v_vm_faults++;
3243                         if (curthread->td_lwp)
3244                                 ++curthread->td_lwp->lwp_ru.ru_minflt;
3245 #endif
3246                         vm_page_wakeup(m);
3247                 } else {
3248                         vm_page_wakeup(m);
3249                 }
3250         }
3251         vm_object_drop(object);
3252 }
3253
3254 /*
3255  * Object can be held shared
3256  */
3257 static void
3258 vm_prefault_quick(pmap_t pmap, vm_offset_t addra,
3259                   vm_map_entry_t entry, int prot, int fault_flags)
3260 {
3261         struct lwp *lp;
3262         vm_page_t m;
3263         vm_offset_t addr;
3264         vm_pindex_t pindex;
3265         vm_object_t object;
3266         int i;
3267         int noneg;
3268         int nopos;
3269         int maxpages;
3270
3271         /*
3272          * Get stable max count value, disabled if set to 0
3273          */
3274         maxpages = vm_prefault_pages;
3275         cpu_ccfence();
3276         if (maxpages <= 0)
3277                 return;
3278
3279         /*
3280          * We do not currently prefault mappings that use virtual page
3281          * tables.  We do not prefault foreign pmaps.
3282          */
3283         if (entry->maptype != VM_MAPTYPE_NORMAL)
3284                 return;
3285         lp = curthread->td_lwp;
3286         if (lp == NULL || (pmap != vmspace_pmap(lp->lwp_vmspace)))
3287                 return;
3288         object = entry->ba.object;
3289         if (entry->ba.backing_ba != NULL)
3290                 return;
3291         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
3292
3293         /*
3294          * Limit pre-fault count to 1024 pages.
3295          */
3296         if (maxpages > 1024)
3297                 maxpages = 1024;
3298
3299         noneg = 0;
3300         nopos = 0;
3301         for (i = 0; i < maxpages; ++i) {
3302                 int error;
3303
3304                 /*
3305                  * Calculate the page to pre-fault, stopping the scan in
3306                  * each direction separately if the limit is reached.
3307                  */
3308                 if (i & 1) {
3309                         if (noneg)
3310                                 continue;
3311                         addr = addra - ((i + 1) >> 1) * PAGE_SIZE;
3312                 } else {
3313                         if (nopos)
3314                                 continue;
3315                         addr = addra + ((i + 2) >> 1) * PAGE_SIZE;
3316                 }
3317                 if (addr < entry->ba.start) {
3318                         noneg = 1;
3319                         if (noneg && nopos)
3320                                 break;
3321                         continue;
3322                 }
3323                 if (addr >= entry->ba.end) {
3324                         nopos = 1;
3325                         if (noneg && nopos)
3326                                 break;
3327                         continue;
3328                 }
3329
3330                 /*
3331                  * Follow the VM object chain to obtain the page to be mapped
3332                  * into the pmap.  This version of the prefault code only
3333                  * works with terminal objects.
3334                  *
3335                  * The page must already exist.  If we encounter a problem
3336                  * we stop here.
3337                  *
3338                  * WARNING!  We cannot call swap_pager_unswapped() or insert
3339                  *           a new vm_page with a shared token.
3340                  */
3341                 pindex = ((addr - entry->ba.start) + entry->ba.offset) >>
3342                          PAGE_SHIFT;
3343
3344                 /*
3345                  * Skip pages already mapped, and stop scanning in that
3346                  * direction.  When the scan terminates in both directions
3347                  * we are done.
3348                  */
3349                 if (pmap_prefault_ok(pmap, addr) == 0) {
3350                         if (i & 1)
3351                                 noneg = 1;
3352                         else
3353                                 nopos = 1;
3354                         if (noneg && nopos)
3355                                 break;
3356                         continue;
3357                 }
3358
3359                 /*
3360                  * Shortcut the read-only mapping case using the far more
3361                  * efficient vm_page_lookup_sbusy_try() function.  This
3362                  * allows us to acquire the page soft-busied only which
3363                  * is especially nice for concurrent execs of the same
3364                  * program.
3365                  *
3366                  * The lookup function also validates page suitability
3367                  * (all valid bits set, and not fictitious).
3368                  *
3369                  * If the page is in PQ_CACHE we have to fall-through
3370                  * and hard-busy it so we can move it out of PQ_CACHE.
3371                  */
3372                 if ((prot & VM_PROT_WRITE) == 0) {
3373                         m = vm_page_lookup_sbusy_try(object, pindex,
3374                                                      0, PAGE_SIZE);
3375                         if (m == NULL)
3376                                 break;
3377                         if ((m->queue - m->pc) != PQ_CACHE) {
3378                                 pmap_enter(pmap, addr, m, prot, 0, entry);
3379 #if 0
3380                         /* REMOVE ME, a burst counts as one fault */
3381                                 mycpu->gd_cnt.v_vm_faults++;
3382                                 if (curthread->td_lwp)
3383                                         ++curthread->td_lwp->lwp_ru.ru_minflt;
3384 #endif
3385                                 vm_page_sbusy_drop(m);
3386                                 continue;
3387                         }
3388                         vm_page_sbusy_drop(m);
3389                 }
3390
3391                 /*
3392                  * Fallback to normal vm_page lookup code.  This code
3393                  * hard-busies the page.  Not only that, but the page
3394                  * can remain in that state for a significant period
3395                  * time due to pmap_enter()'s overhead.
3396                  */
3397                 m = vm_page_lookup_busy_try(object, pindex, TRUE, &error);
3398                 if (m == NULL || error)
3399                         break;
3400
3401                 /*
3402                  * Stop if the page cannot be trivially entered into the
3403                  * pmap.
3404                  */
3405                 if (((m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) ||
3406                     (m->flags & PG_FICTITIOUS) ||
3407                     ((m->flags & PG_SWAPPED) &&
3408                      (prot & VM_PROT_WRITE) &&
3409                      (fault_flags & VM_FAULT_DIRTY))) {
3410                         vm_page_wakeup(m);
3411                         break;
3412                 }
3413
3414                 /*
3415                  * Enter the page into the pmap.  The object might be held
3416                  * shared so we can't do any (serious) modifying operation
3417                  * on it.
3418                  */
3419                 if ((m->queue - m->pc) == PQ_CACHE)
3420                         vm_page_deactivate(m);
3421                 if (prot & VM_PROT_WRITE) {
3422                         vm_object_set_writeable_dirty(m->object);
3423                         vm_set_nosync(m, entry);
3424                         if (fault_flags & VM_FAULT_DIRTY) {
3425                                 vm_page_dirty(m);
3426                                 /* can't happeen due to conditional above */
3427                                 /* swap_pager_unswapped(m); */
3428                         }
3429                 }
3430                 pmap_enter(pmap, addr, m, prot, 0, entry);
3431 #if 0
3432                 /* REMOVE ME, a burst counts as one fault */
3433                 mycpu->gd_cnt.v_vm_faults++;
3434                 if (curthread->td_lwp)
3435                         ++curthread->td_lwp->lwp_ru.ru_minflt;
3436 #endif
3437                 vm_page_wakeup(m);
3438         }
3439 }