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