kernel - VM rework part 4 - Implement vm_fault_collapse()
[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->start &&
520                     vaddr < fs.entry->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         vm_page_activate(m);
957         fs->m = m;
958         fs->msoftonly = 1;
959 #ifdef VM_FAULT_QUICK_DEBUG
960         ++vm_fault_quick_success_count;
961 #endif
962
963         return KERN_SUCCESS;
964 }
965
966 /*
967  * Fault in the specified virtual address in the current process map, 
968  * returning a held VM page or NULL.  See vm_fault_page() for more 
969  * information.
970  *
971  * No requirements.
972  */
973 vm_page_t
974 vm_fault_page_quick(vm_offset_t va, vm_prot_t fault_type,
975                     int *errorp, int *busyp)
976 {
977         struct lwp *lp = curthread->td_lwp;
978         vm_page_t m;
979
980         m = vm_fault_page(&lp->lwp_vmspace->vm_map, va, 
981                           fault_type, VM_FAULT_NORMAL,
982                           errorp, busyp);
983         return(m);
984 }
985
986 /*
987  * Fault in the specified virtual address in the specified map, doing all
988  * necessary manipulation of the object store and all necessary I/O.  Return
989  * a held VM page or NULL, and set *errorp.  The related pmap is not
990  * updated.
991  *
992  * If busyp is not NULL then *busyp will be set to TRUE if this routine
993  * decides to return a busied page (aka VM_PROT_WRITE), or FALSE if it
994  * does not (VM_PROT_WRITE not specified or busyp is NULL).  If busyp is
995  * NULL the returned page is only held.
996  *
997  * If the caller has no intention of writing to the page's contents, busyp
998  * can be passed as NULL along with VM_PROT_WRITE to force a COW operation
999  * without busying the page.
1000  *
1001  * The returned page will also be marked PG_REFERENCED.
1002  *
1003  * If the page cannot be faulted writable and VM_PROT_WRITE was specified, an
1004  * error will be returned.
1005  *
1006  * No requirements.
1007  */
1008 vm_page_t
1009 vm_fault_page(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
1010               int fault_flags, int *errorp, int *busyp)
1011 {
1012         vm_pindex_t first_pindex;
1013         struct faultstate fs;
1014         int result;
1015         int retry;
1016         int growstack;
1017         int didcow;
1018         vm_prot_t orig_fault_type = fault_type;
1019
1020         retry = 0;
1021         didcow = 0;
1022         fs.hardfault = 0;
1023         fs.fault_flags = fault_flags;
1024         KKASSERT((fault_flags & VM_FAULT_WIRE_MASK) == 0);
1025
1026         /*
1027          * Dive the pmap (concurrency possible).  If we find the
1028          * appropriate page we can terminate early and quickly.
1029          *
1030          * This works great for normal programs but will always return
1031          * NULL for host lookups of vkernel maps in VMM mode.
1032          *
1033          * NOTE: pmap_fault_page_quick() might not busy the page.  If
1034          *       VM_PROT_WRITE is set in fault_type and pmap_fault_page_quick()
1035          *       returns non-NULL, it will safely dirty the returned vm_page_t
1036          *       for us.  We cannot safely dirty it here (it might not be
1037          *       busy).
1038          */
1039         fs.m = pmap_fault_page_quick(map->pmap, vaddr, fault_type, busyp);
1040         if (fs.m) {
1041                 *errorp = 0;
1042                 return(fs.m);
1043         }
1044
1045         /*
1046          * Otherwise take a concurrency hit and do a formal page
1047          * fault.
1048          */
1049         fs.vp = NULL;
1050         fs.shared = vm_shared_fault;
1051         fs.first_shared = vm_shared_fault;
1052         fs.msoftonly = 0;
1053         growstack = 1;
1054
1055         /*
1056          * VM_FAULT_UNSWAP - swap_pager_unswapped() needs an exclusive object
1057          * VM_FAULT_DIRTY  - may require swap_pager_unswapped() later, but
1058          *                   we can try shared first.
1059          */
1060         if (fault_flags & VM_FAULT_UNSWAP) {
1061                 fs.first_shared = 0;
1062         }
1063
1064 RetryFault:
1065         /*
1066          * Find the vm_map_entry representing the backing store and resolve
1067          * the top level object and page index.  This may have the side
1068          * effect of executing a copy-on-write on the map entry and/or
1069          * creating a shadow object, but will not COW any actual VM pages.
1070          *
1071          * On success fs.map is left read-locked and various other fields 
1072          * are initialized but not otherwise referenced or locked.
1073          *
1074          * NOTE!  vm_map_lookup will upgrade the fault_type to VM_FAULT_WRITE
1075          *        if the map entry is a virtual page table and also writable,
1076          *        so we can set the 'A'accessed bit in the virtual page table
1077          *        entry.
1078          */
1079         fs.map = map;
1080         fs.first_ba_held = 0;
1081         result = vm_map_lookup(&fs.map, vaddr, fault_type,
1082                                &fs.entry, &fs.first_ba,
1083                                &first_pindex, &fs.first_prot, &fs.wflags);
1084
1085         if (result != KERN_SUCCESS) {
1086                 if (result == KERN_FAILURE_NOFAULT) {
1087                         *errorp = KERN_FAILURE;
1088                         fs.m = NULL;
1089                         goto done;
1090                 }
1091                 if (result != KERN_PROTECTION_FAILURE ||
1092                     (fs.fault_flags & VM_FAULT_WIRE_MASK) != VM_FAULT_USER_WIRE)
1093                 {
1094                         if (result == KERN_INVALID_ADDRESS && growstack &&
1095                             map != &kernel_map && curproc != NULL) {
1096                                 result = vm_map_growstack(map, vaddr);
1097                                 if (result == KERN_SUCCESS) {
1098                                         growstack = 0;
1099                                         ++retry;
1100                                         goto RetryFault;
1101                                 }
1102                                 result = KERN_FAILURE;
1103                         }
1104                         fs.m = NULL;
1105                         *errorp = result;
1106                         goto done;
1107                 }
1108
1109                 /*
1110                  * If we are user-wiring a r/w segment, and it is COW, then
1111                  * we need to do the COW operation.  Note that we don't
1112                  * currently COW RO sections now, because it is NOT desirable
1113                  * to COW .text.  We simply keep .text from ever being COW'ed
1114                  * and take the heat that one cannot debug wired .text sections.
1115                  */
1116                 result = vm_map_lookup(&fs.map, vaddr,
1117                                        VM_PROT_READ|VM_PROT_WRITE|
1118                                         VM_PROT_OVERRIDE_WRITE,
1119                                        &fs.entry, &fs.first_ba,
1120                                        &first_pindex, &fs.first_prot,
1121                                        &fs.wflags);
1122                 if (result != KERN_SUCCESS) {
1123                         /* could also be KERN_FAILURE_NOFAULT */
1124                         *errorp = KERN_FAILURE;
1125                         fs.m = NULL;
1126                         goto done;
1127                 }
1128
1129                 /*
1130                  * If we don't COW now, on a user wire, the user will never
1131                  * be able to write to the mapping.  If we don't make this
1132                  * restriction, the bookkeeping would be nearly impossible.
1133                  *
1134                  * XXX We have a shared lock, this will have a MP race but
1135                  * I don't see how it can hurt anything.
1136                  */
1137                 if ((fs.entry->protection & VM_PROT_WRITE) == 0) {
1138                         atomic_clear_char(&fs.entry->max_protection,
1139                                           VM_PROT_WRITE);
1140                 }
1141         }
1142
1143         /*
1144          * fs.map is read-locked
1145          *
1146          * Misc checks.  Save the map generation number to detect races.
1147          */
1148         fs.lookup_still_valid = 1;
1149         fs.first_m = NULL;
1150         fs.ba = fs.first_ba;
1151
1152         if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
1153                 panic("vm_fault: fault on nofault entry, addr: %lx",
1154                     (u_long)vaddr);
1155         }
1156
1157         /*
1158          * A user-kernel shared map has no VM object and bypasses
1159          * everything.  We execute the uksmap function with a temporary
1160          * fictitious vm_page.  The address is directly mapped with no
1161          * management.
1162          */
1163         if (fs.entry->maptype == VM_MAPTYPE_UKSMAP) {
1164                 struct vm_page fakem;
1165
1166                 bzero(&fakem, sizeof(fakem));
1167                 fakem.pindex = first_pindex;
1168                 fakem.flags = PG_FICTITIOUS | PG_UNMANAGED;
1169                 fakem.busy_count = PBUSY_LOCKED;
1170                 fakem.valid = VM_PAGE_BITS_ALL;
1171                 fakem.pat_mode = VM_MEMATTR_DEFAULT;
1172                 if (fs.entry->ba.uksmap(fs.entry->aux.dev, &fakem)) {
1173                         *errorp = KERN_FAILURE;
1174                         fs.m = NULL;
1175                         unlock_things(&fs);
1176                         goto done2;
1177                 }
1178                 fs.m = PHYS_TO_VM_PAGE(fakem.phys_addr);
1179                 vm_page_hold(fs.m);
1180                 if (busyp)
1181                         *busyp = 0;     /* don't need to busy R or W */
1182                 unlock_things(&fs);
1183                 *errorp = 0;
1184                 goto done;
1185         }
1186
1187
1188         /*
1189          * A system map entry may return a NULL object.  No object means
1190          * no pager means an unrecoverable kernel fault.
1191          */
1192         if (fs.first_ba == NULL) {
1193                 panic("vm_fault: unrecoverable fault at %p in entry %p",
1194                         (void *)vaddr, fs.entry);
1195         }
1196
1197         /*
1198          * Fail here if not a trivial anonymous page fault and TDF_NOFAULT
1199          * is set.
1200          *
1201          * Unfortunately a deadlock can occur if we are forced to page-in
1202          * from swap, but diving all the way into the vm_pager_get_page()
1203          * function to find out is too much.  Just check the object type.
1204          */
1205         if ((curthread->td_flags & TDF_NOFAULT) &&
1206             (retry ||
1207              fs.first_ba->object->type == OBJT_VNODE ||
1208              fs.first_ba->object->type == OBJT_SWAP ||
1209              fs.first_ba->backing_ba)) {
1210                 *errorp = KERN_FAILURE;
1211                 unlock_things(&fs);
1212                 fs.m = NULL;
1213                 goto done2;
1214         }
1215
1216         /*
1217          * If the entry is wired we cannot change the page protection.
1218          */
1219         if (fs.wflags & FW_WIRED)
1220                 fault_type = fs.first_prot;
1221
1222         /*
1223          * Make a reference to this object to prevent its disposal while we
1224          * are messing with it.  Once we have the reference, the map is free
1225          * to be diddled.  Since objects reference their shadows (and copies),
1226          * they will stay around as well.
1227          *
1228          * The reference should also prevent an unexpected collapse of the
1229          * parent that might move pages from the current object into the
1230          * parent unexpectedly, resulting in corruption.
1231          *
1232          * Bump the paging-in-progress count to prevent size changes (e.g.
1233          * truncation operations) during I/O.  This must be done after
1234          * obtaining the vnode lock in order to avoid possible deadlocks.
1235          */
1236         if (fs.first_ba->flags & VM_MAP_BACK_EXCL_HEUR)
1237                 fs.first_shared = 0;
1238
1239         if (fs.first_shared)
1240                 vm_object_hold_shared(fs.first_ba->object);
1241         else
1242                 vm_object_hold(fs.first_ba->object);
1243         fs.first_ba_held = 1;
1244         if (fs.vp == NULL)
1245                 fs.vp = vnode_pager_lock(fs.first_ba);  /* shared */
1246
1247         /*
1248          * The page we want is at (first_object, first_pindex), but if the
1249          * vm_map_entry is VM_MAPTYPE_VPAGETABLE we have to traverse the
1250          * page table to figure out the actual pindex.
1251          *
1252          * NOTE!  DEVELOPMENT IN PROGRESS, THIS IS AN INITIAL IMPLEMENTATION
1253          * ONLY
1254          */
1255         if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
1256                 result = vm_fault_vpagetable(&fs, &first_pindex,
1257                                              fs.entry->aux.master_pde,
1258                                              fault_type, 1);
1259                 if (result == KERN_TRY_AGAIN) {
1260                         ++retry;
1261                         goto RetryFault;
1262                 }
1263                 if (result != KERN_SUCCESS) {
1264                         *errorp = result;
1265                         fs.m = NULL;
1266                         goto done;
1267                 }
1268         }
1269
1270         /*
1271          * Now we have the actual (object, pindex), fault in the page.  If
1272          * vm_fault_object() fails it will unlock and deallocate the FS
1273          * data.   If it succeeds everything remains locked and fs->ba->object
1274          * will have an additinal PIP count if fs->ba != fs->first_ba.
1275          */
1276         fs.m = NULL;
1277         result = vm_fault_object(&fs, first_pindex, fault_type, 1);
1278
1279         if (result == KERN_TRY_AGAIN) {
1280                 KKASSERT(fs.first_ba_held == 0);
1281                 ++retry;
1282                 didcow |= fs.wflags & FW_DIDCOW;
1283                 goto RetryFault;
1284         }
1285         if (result != KERN_SUCCESS) {
1286                 *errorp = result;
1287                 fs.m = NULL;
1288                 goto done;
1289         }
1290
1291         if ((orig_fault_type & VM_PROT_WRITE) &&
1292             (fs.prot & VM_PROT_WRITE) == 0) {
1293                 *errorp = KERN_PROTECTION_FAILURE;
1294                 unlock_things(&fs);
1295                 fs.m = NULL;
1296                 goto done;
1297         }
1298
1299         /*
1300          * Generally speaking we don't want to update the pmap because
1301          * this routine can be called many times for situations that do
1302          * not require updating the pmap, not to mention the page might
1303          * already be in the pmap.
1304          *
1305          * However, if our vm_map_lookup() results in a COW, we need to
1306          * at least remove the pte from the pmap to guarantee proper
1307          * visibility of modifications made to the process.  For example,
1308          * modifications made by vkernel uiocopy/related routines and
1309          * modifications made by ptrace().
1310          */
1311         vm_page_flag_set(fs.m, PG_REFERENCED);
1312 #if 0
1313         pmap_enter(fs.map->pmap, vaddr, fs.m, fs.prot,
1314                    fs.wflags & FW_WIRED, NULL);
1315         mycpu->gd_cnt.v_vm_faults++;
1316         if (curthread->td_lwp)
1317                 ++curthread->td_lwp->lwp_ru.ru_minflt;
1318 #endif
1319         if ((fs.wflags | didcow) | FW_DIDCOW) {
1320                 pmap_remove(fs.map->pmap,
1321                             vaddr & ~PAGE_MASK,
1322                             (vaddr & ~PAGE_MASK) + PAGE_SIZE);
1323         }
1324
1325         /*
1326          * On success vm_fault_object() does not unlock or deallocate, and fs.m
1327          * will contain a busied page.  So we must unlock here after having
1328          * messed with the pmap.
1329          */
1330         unlock_things(&fs);
1331
1332         /*
1333          * Return a held page.  We are not doing any pmap manipulation so do
1334          * not set PG_MAPPED.  However, adjust the page flags according to
1335          * the fault type because the caller may not use a managed pmapping
1336          * (so we don't want to lose the fact that the page will be dirtied
1337          * if a write fault was specified).
1338          */
1339         if (fault_type & VM_PROT_WRITE)
1340                 vm_page_dirty(fs.m);
1341         vm_page_activate(fs.m);
1342
1343         if (curthread->td_lwp) {
1344                 if (fs.hardfault) {
1345                         curthread->td_lwp->lwp_ru.ru_majflt++;
1346                 } else {
1347                         curthread->td_lwp->lwp_ru.ru_minflt++;
1348                 }
1349         }
1350
1351         /*
1352          * Unlock everything, and return the held or busied page.
1353          */
1354         if (busyp) {
1355                 if (fault_type & VM_PROT_WRITE) {
1356                         vm_page_dirty(fs.m);
1357                         *busyp = 1;
1358                 } else {
1359                         *busyp = 0;
1360                         vm_page_hold(fs.m);
1361                         vm_page_wakeup(fs.m);
1362                 }
1363         } else {
1364                 vm_page_hold(fs.m);
1365                 vm_page_wakeup(fs.m);
1366         }
1367         /*vm_object_deallocate(fs.first_ba->object);*/
1368         *errorp = 0;
1369
1370 done:
1371         KKASSERT(fs.first_ba_held == 0);
1372 done2:
1373         return(fs.m);
1374 }
1375
1376 /*
1377  * Fault in the specified (object,offset), dirty the returned page as
1378  * needed.  If the requested fault_type cannot be done NULL and an
1379  * error is returned.
1380  *
1381  * A held (but not busied) page is returned.
1382  *
1383  * The passed in object must be held as specified by the shared
1384  * argument.
1385  */
1386 vm_page_t
1387 vm_fault_object_page(vm_object_t object, vm_ooffset_t offset,
1388                      vm_prot_t fault_type, int fault_flags,
1389                      int *sharedp, int *errorp)
1390 {
1391         int result;
1392         vm_pindex_t first_pindex;
1393         struct faultstate fs;
1394         struct vm_map_entry entry;
1395
1396         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1397         bzero(&entry, sizeof(entry));
1398         entry.maptype = VM_MAPTYPE_NORMAL;
1399         entry.protection = entry.max_protection = fault_type;
1400         entry.ba.backing_ba = NULL;
1401         entry.ba.object = object;
1402         entry.ba.offset = 0;
1403
1404         fs.hardfault = 0;
1405         fs.fault_flags = fault_flags;
1406         fs.map = NULL;
1407         fs.shared = vm_shared_fault;
1408         fs.first_shared = *sharedp;
1409         fs.msoftonly = 0;
1410         fs.vp = NULL;
1411         fs.first_ba_held = -1;  /* object held across call, prevent drop */
1412         KKASSERT((fault_flags & VM_FAULT_WIRE_MASK) == 0);
1413
1414         /*
1415          * VM_FAULT_UNSWAP - swap_pager_unswapped() needs an exclusive object
1416          * VM_FAULT_DIRTY  - may require swap_pager_unswapped() later, but
1417          *                   we can try shared first.
1418          */
1419         if (fs.first_shared && (fault_flags & VM_FAULT_UNSWAP)) {
1420                 fs.first_shared = 0;
1421                 vm_object_upgrade(object);
1422         }
1423
1424         /*
1425          * Retry loop as needed (typically for shared->exclusive transitions)
1426          */
1427 RetryFault:
1428         *sharedp = fs.first_shared;
1429         first_pindex = OFF_TO_IDX(offset);
1430         fs.first_ba = &entry.ba;
1431         fs.ba = fs.first_ba;
1432         fs.entry = &entry;
1433         fs.first_prot = fault_type;
1434         fs.wflags = 0;
1435
1436         /*
1437          * Make a reference to this object to prevent its disposal while we
1438          * are messing with it.  Once we have the reference, the map is free
1439          * to be diddled.  Since objects reference their shadows (and copies),
1440          * they will stay around as well.
1441          *
1442          * The reference should also prevent an unexpected collapse of the
1443          * parent that might move pages from the current object into the
1444          * parent unexpectedly, resulting in corruption.
1445          *
1446          * Bump the paging-in-progress count to prevent size changes (e.g.
1447          * truncation operations) during I/O.  This must be done after
1448          * obtaining the vnode lock in order to avoid possible deadlocks.
1449          */
1450         if (fs.vp == NULL)
1451                 fs.vp = vnode_pager_lock(fs.first_ba);
1452
1453         fs.lookup_still_valid = 1;
1454         fs.first_m = NULL;
1455
1456 #if 0
1457         /* XXX future - ability to operate on VM object using vpagetable */
1458         if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
1459                 result = vm_fault_vpagetable(&fs, &first_pindex,
1460                                              fs.entry->aux.master_pde,
1461                                              fault_type, 0);
1462                 if (result == KERN_TRY_AGAIN) {
1463                         if (fs.first_shared == 0 && *sharedp)
1464                                 vm_object_upgrade(object);
1465                         goto RetryFault;
1466                 }
1467                 if (result != KERN_SUCCESS) {
1468                         *errorp = result;
1469                         return (NULL);
1470                 }
1471         }
1472 #endif
1473
1474         /*
1475          * Now we have the actual (object, pindex), fault in the page.  If
1476          * vm_fault_object() fails it will unlock and deallocate the FS
1477          * data.   If it succeeds everything remains locked and fs->ba->object
1478          * will have an additinal PIP count if fs->ba != fs->first_ba.
1479          *
1480          * On KERN_TRY_AGAIN vm_fault_object() leaves fs.first_ba intact.
1481          * We may have to upgrade its lock to handle the requested fault.
1482          */
1483         result = vm_fault_object(&fs, first_pindex, fault_type, 0);
1484
1485         if (result == KERN_TRY_AGAIN) {
1486                 if (fs.first_shared == 0 && *sharedp)
1487                         vm_object_upgrade(object);
1488                 goto RetryFault;
1489         }
1490         if (result != KERN_SUCCESS) {
1491                 *errorp = result;
1492                 return(NULL);
1493         }
1494
1495         if ((fault_type & VM_PROT_WRITE) && (fs.prot & VM_PROT_WRITE) == 0) {
1496                 *errorp = KERN_PROTECTION_FAILURE;
1497                 unlock_things(&fs);
1498                 return(NULL);
1499         }
1500
1501         /*
1502          * On success vm_fault_object() does not unlock or deallocate, so we
1503          * do it here.  Note that the returned fs.m will be busied.
1504          */
1505         unlock_things(&fs);
1506
1507         /*
1508          * Return a held page.  We are not doing any pmap manipulation so do
1509          * not set PG_MAPPED.  However, adjust the page flags according to
1510          * the fault type because the caller may not use a managed pmapping
1511          * (so we don't want to lose the fact that the page will be dirtied
1512          * if a write fault was specified).
1513          */
1514         vm_page_hold(fs.m);
1515         vm_page_activate(fs.m);
1516         if ((fault_type & VM_PROT_WRITE) || (fault_flags & VM_FAULT_DIRTY))
1517                 vm_page_dirty(fs.m);
1518         if (fault_flags & VM_FAULT_UNSWAP)
1519                 swap_pager_unswapped(fs.m);
1520
1521         /*
1522          * Indicate that the page was accessed.
1523          */
1524         vm_page_flag_set(fs.m, PG_REFERENCED);
1525
1526         if (curthread->td_lwp) {
1527                 if (fs.hardfault) {
1528                         curthread->td_lwp->lwp_ru.ru_majflt++;
1529                 } else {
1530                         curthread->td_lwp->lwp_ru.ru_minflt++;
1531                 }
1532         }
1533
1534         /*
1535          * Unlock everything, and return the held page.
1536          */
1537         vm_page_wakeup(fs.m);
1538         /*vm_object_deallocate(fs.first_ba->object);*/
1539
1540         *errorp = 0;
1541         return(fs.m);
1542 }
1543
1544 /*
1545  * Translate the virtual page number (first_pindex) that is relative
1546  * to the address space into a logical page number that is relative to the
1547  * backing object.  Use the virtual page table pointed to by (vpte).
1548  *
1549  * Possibly downgrade the protection based on the vpte bits.
1550  *
1551  * This implements an N-level page table.  Any level can terminate the
1552  * scan by setting VPTE_PS.   A linear mapping is accomplished by setting
1553  * VPTE_PS in the master page directory entry set via mcontrol(MADV_SETMAP).
1554  */
1555 static
1556 int
1557 vm_fault_vpagetable(struct faultstate *fs, vm_pindex_t *pindex,
1558                     vpte_t vpte, int fault_type, int allow_nofault)
1559 {
1560         struct lwbuf *lwb;
1561         struct lwbuf lwb_cache;
1562         int vshift = VPTE_FRAME_END - PAGE_SHIFT; /* index bits remaining */
1563         int result;
1564         vpte_t *ptep;
1565
1566         ASSERT_LWKT_TOKEN_HELD(vm_object_token(fs->first_ba->object));
1567         for (;;) {
1568                 /*
1569                  * We cannot proceed if the vpte is not valid, not readable
1570                  * for a read fault, not writable for a write fault, or
1571                  * not executable for an instruction execution fault.
1572                  */
1573                 if ((vpte & VPTE_V) == 0) {
1574                         unlock_things(fs);
1575                         return (KERN_FAILURE);
1576                 }
1577                 if ((fault_type & VM_PROT_WRITE) && (vpte & VPTE_RW) == 0) {
1578                         unlock_things(fs);
1579                         return (KERN_FAILURE);
1580                 }
1581                 if ((fault_type & VM_PROT_EXECUTE) && (vpte & VPTE_NX)) {
1582                         unlock_things(fs);
1583                         return (KERN_FAILURE);
1584                 }
1585                 if ((vpte & VPTE_PS) || vshift == 0)
1586                         break;
1587
1588                 /*
1589                  * Get the page table page.  Nominally we only read the page
1590                  * table, but since we are actively setting VPTE_M and VPTE_A,
1591                  * tell vm_fault_object() that we are writing it. 
1592                  *
1593                  * There is currently no real need to optimize this.
1594                  */
1595                 result = vm_fault_object(fs, (vpte & VPTE_FRAME) >> PAGE_SHIFT,
1596                                          VM_PROT_READ|VM_PROT_WRITE,
1597                                          allow_nofault);
1598                 if (result != KERN_SUCCESS)
1599                         return (result);
1600
1601                 /*
1602                  * Process the returned fs.m and look up the page table
1603                  * entry in the page table page.
1604                  */
1605                 vshift -= VPTE_PAGE_BITS;
1606                 lwb = lwbuf_alloc(fs->m, &lwb_cache);
1607                 ptep = ((vpte_t *)lwbuf_kva(lwb) +
1608                         ((*pindex >> vshift) & VPTE_PAGE_MASK));
1609                 vm_page_activate(fs->m);
1610
1611                 /*
1612                  * Page table write-back - entire operation including
1613                  * validation of the pte must be atomic to avoid races
1614                  * against the vkernel changing the pte.
1615                  *
1616                  * If the vpte is valid for the* requested operation, do
1617                  * a write-back to the page table.
1618                  *
1619                  * XXX VPTE_M is not set properly for page directory pages.
1620                  * It doesn't get set in the page directory if the page table
1621                  * is modified during a read access.
1622                  */
1623                 for (;;) {
1624                         vpte_t nvpte;
1625
1626                         /*
1627                          * Reload for the cmpset, but make sure the pte is
1628                          * still valid.
1629                          */
1630                         vpte = *ptep;
1631                         cpu_ccfence();
1632                         nvpte = vpte;
1633
1634                         if ((vpte & VPTE_V) == 0)
1635                                 break;
1636
1637                         if ((fault_type & VM_PROT_WRITE) && (vpte & VPTE_RW))
1638                                 nvpte |= VPTE_M | VPTE_A;
1639                         if (fault_type & (VM_PROT_READ | VM_PROT_EXECUTE))
1640                                 nvpte |= VPTE_A;
1641                         if (vpte == nvpte)
1642                                 break;
1643                         if (atomic_cmpset_long(ptep, vpte, nvpte)) {
1644                                 vm_page_dirty(fs->m);
1645                                 break;
1646                         }
1647                 }
1648                 lwbuf_free(lwb);
1649                 vm_page_flag_set(fs->m, PG_REFERENCED);
1650                 vm_page_wakeup(fs->m);
1651                 fs->m = NULL;
1652                 cleanup_fault(fs);
1653         }
1654
1655         /*
1656          * When the vkernel sets VPTE_RW it expects the real kernel to
1657          * reflect VPTE_M back when the page is modified via the mapping.
1658          * In order to accomplish this the real kernel must map the page
1659          * read-only for read faults and use write faults to reflect VPTE_M
1660          * back.
1661          *
1662          * Once VPTE_M has been set, the real kernel's pte allows writing.
1663          * If the vkernel clears VPTE_M the vkernel must be sure to
1664          * MADV_INVAL the real kernel's mappings to force the real kernel
1665          * to re-fault on the next write so oit can set VPTE_M again.
1666          */
1667         if ((fault_type & VM_PROT_WRITE) == 0 &&
1668             (vpte & (VPTE_RW | VPTE_M)) != (VPTE_RW | VPTE_M)) {
1669                 fs->first_prot &= ~VM_PROT_WRITE;
1670         }
1671
1672         /*
1673          * Disable EXECUTE perms if NX bit is set.
1674          */
1675         if (vpte & VPTE_NX)
1676                 fs->first_prot &= ~VM_PROT_EXECUTE;
1677
1678         /*
1679          * Combine remaining address bits with the vpte.
1680          */
1681         *pindex = ((vpte & VPTE_FRAME) >> PAGE_SHIFT) +
1682                   (*pindex & ((1L << vshift) - 1));
1683         return (KERN_SUCCESS);
1684 }
1685
1686
1687 /*
1688  * This is the core of the vm_fault code.
1689  *
1690  * Do all operations required to fault-in (fs.first_ba->object, pindex).
1691  * Run through the backing store as necessary and do required COW or virtual
1692  * copy operations.  The caller has already fully resolved the vm_map_entry
1693  * and, if appropriate, has created a copy-on-write layer.  All we need to
1694  * do is iterate the object chain.
1695  *
1696  * On failure (fs) is unlocked and deallocated and the caller may return or
1697  * retry depending on the failure code.  On success (fs) is NOT unlocked or
1698  * deallocated, fs.m will contained a resolved, busied page, and fs.ba's
1699  * object will have an additional PIP count if it is not equal to
1700  * fs.first_ba.
1701  *
1702  * If locks based on fs->first_shared or fs->shared are insufficient,
1703  * clear the appropriate field(s) and return RETRY.  COWs require that
1704  * first_shared be 0, while page allocations (or frees) require that
1705  * shared be 0.  Renames require that both be 0.
1706  *
1707  * NOTE! fs->[first_]shared might be set with VM_FAULT_DIRTY also set.
1708  *       we will have to retry with it exclusive if the vm_page is
1709  *       PG_SWAPPED.
1710  *
1711  * fs->first_ba->object must be held on call.
1712  */
1713 static
1714 int
1715 vm_fault_object(struct faultstate *fs, vm_pindex_t first_pindex,
1716                 vm_prot_t fault_type, int allow_nofault)
1717 {
1718         vm_map_backing_t next_ba;
1719         vm_pindex_t pindex;
1720         int error;
1721
1722         ASSERT_LWKT_TOKEN_HELD(vm_object_token(fs->first_ba->object));
1723         fs->prot = fs->first_prot;
1724         pindex = first_pindex;
1725         KKASSERT(fs->ba == fs->first_ba);
1726
1727         vm_object_pip_add(fs->first_ba->object, 1);
1728
1729         /* 
1730          * If a read fault occurs we try to upgrade the page protection
1731          * and make it also writable if possible.  There are three cases
1732          * where we cannot make the page mapping writable:
1733          *
1734          * (1) The mapping is read-only or the VM object is read-only,
1735          *     fs->prot above will simply not have VM_PROT_WRITE set.
1736          *
1737          * (2) If the mapping is a virtual page table fs->first_prot will
1738          *     have already been properly adjusted by vm_fault_vpagetable().
1739          *     to detect writes so we can set VPTE_M in the virtual page
1740          *     table.  Used by vkernels.
1741          *
1742          * (3) If the VM page is read-only or copy-on-write, upgrading would
1743          *     just result in an unnecessary COW fault.
1744          *
1745          * (4) If the pmap specifically requests A/M bit emulation, downgrade
1746          *     here.
1747          */
1748 #if 0
1749         /* see vpagetable code */
1750         if (fs->entry->maptype == VM_MAPTYPE_VPAGETABLE) {
1751                 if ((fault_type & VM_PROT_WRITE) == 0)
1752                         fs->prot &= ~VM_PROT_WRITE;
1753         }
1754 #endif
1755
1756         if (curthread->td_lwp && curthread->td_lwp->lwp_vmspace &&
1757             pmap_emulate_ad_bits(&curthread->td_lwp->lwp_vmspace->vm_pmap)) {
1758                 if ((fault_type & VM_PROT_WRITE) == 0)
1759                         fs->prot &= ~VM_PROT_WRITE;
1760         }
1761
1762         /* vm_object_hold(fs->ba->object); implied b/c ba == first_ba */
1763
1764         for (;;) {
1765                 /*
1766                  * If the object is dead, we stop here
1767                  */
1768                 if (fs->ba->object->flags & OBJ_DEAD) {
1769                         vm_object_pip_wakeup(fs->first_ba->object);
1770                         unlock_things(fs);
1771                         return (KERN_PROTECTION_FAILURE);
1772                 }
1773
1774                 /*
1775                  * See if the page is resident.  Wait/Retry if the page is
1776                  * busy (lots of stuff may have changed so we can't continue
1777                  * in that case).
1778                  *
1779                  * We can theoretically allow the soft-busy case on a read
1780                  * fault if the page is marked valid, but since such
1781                  * pages are typically already pmap'd, putting that
1782                  * special case in might be more effort then it is
1783                  * worth.  We cannot under any circumstances mess
1784                  * around with a vm_page_t->busy page except, perhaps,
1785                  * to pmap it.
1786                  */
1787                 fs->m = vm_page_lookup_busy_try(fs->ba->object, pindex,
1788                                                 TRUE, &error);
1789                 if (error) {
1790                         vm_object_pip_wakeup(fs->first_ba->object);
1791                         unlock_things(fs);
1792                         vm_page_sleep_busy(fs->m, TRUE, "vmpfw");
1793                         mycpu->gd_cnt.v_intrans++;
1794                         fs->m = NULL;
1795                         return (KERN_TRY_AGAIN);
1796                 }
1797                 if (fs->m) {
1798                         /*
1799                          * The page is busied for us.
1800                          *
1801                          * If reactivating a page from PQ_CACHE we may have
1802                          * to rate-limit.
1803                          */
1804                         int queue = fs->m->queue;
1805                         vm_page_unqueue_nowakeup(fs->m);
1806
1807                         if ((queue - fs->m->pc) == PQ_CACHE && 
1808                             vm_page_count_severe()) {
1809                                 vm_page_activate(fs->m);
1810                                 vm_page_wakeup(fs->m);
1811                                 fs->m = NULL;
1812                                 vm_object_pip_wakeup(fs->first_ba->object);
1813                                 unlock_things(fs);
1814                                 if (allow_nofault == 0 ||
1815                                     (curthread->td_flags & TDF_NOFAULT) == 0) {
1816                                         thread_t td;
1817
1818                                         vm_wait_pfault();
1819                                         td = curthread;
1820                                         if (td->td_proc && (td->td_proc->p_flags & P_LOWMEMKILL))
1821                                                 return (KERN_PROTECTION_FAILURE);
1822                                 }
1823                                 return (KERN_TRY_AGAIN);
1824                         }
1825
1826                         /*
1827                          * If it still isn't completely valid (readable),
1828                          * or if a read-ahead-mark is set on the VM page,
1829                          * jump to readrest, else we found the page and
1830                          * can return.
1831                          *
1832                          * We can release the spl once we have marked the
1833                          * page busy.
1834                          */
1835                         if (fs->m->object != &kernel_object) {
1836                                 if ((fs->m->valid & VM_PAGE_BITS_ALL) !=
1837                                     VM_PAGE_BITS_ALL) {
1838                                         goto readrest;
1839                                 }
1840                                 if (fs->m->flags & PG_RAM) {
1841                                         if (debug_cluster)
1842                                                 kprintf("R");
1843                                         vm_page_flag_clear(fs->m, PG_RAM);
1844                                         goto readrest;
1845                                 }
1846                         }
1847                         fs->first_ba->flags &= ~VM_MAP_BACK_EXCL_HEUR;
1848                         break; /* break to PAGE HAS BEEN FOUND */
1849                 }
1850
1851                 /*
1852                  * Page is not resident, If this is the search termination
1853                  * or the pager might contain the page, allocate a new page.
1854                  */
1855                 if (TRYPAGER(fs) || fs->ba == fs->first_ba) {
1856                         /*
1857                          * If this is a SWAP object we can use the shared
1858                          * lock to check existence of a swap block.  If
1859                          * there isn't one we can skip to the next object.
1860                          *
1861                          * However, if this is the first object we allocate
1862                          * a page now just in case we need to copy to it
1863                          * later.
1864                          */
1865                         if (fs->ba != fs->first_ba &&
1866                             fs->ba->object->type == OBJT_SWAP) {
1867                                 if (swap_pager_haspage_locked(fs->ba->object,
1868                                                               pindex) == 0) {
1869                                         goto next;
1870                                 }
1871                         }
1872
1873                         /*
1874                          * Allocating, must be exclusive.
1875                          */
1876                         fs->first_ba->flags |= VM_MAP_BACK_EXCL_HEUR;
1877                         if (fs->ba == fs->first_ba && fs->first_shared) {
1878                                 fs->first_shared = 0;
1879                                 vm_object_pip_wakeup(fs->first_ba->object);
1880                                 unlock_things(fs);
1881                                 return (KERN_TRY_AGAIN);
1882                         }
1883                         if (fs->ba != fs->first_ba && fs->shared) {
1884                                 fs->first_shared = 0;
1885                                 fs->shared = 0;
1886                                 vm_object_pip_wakeup(fs->first_ba->object);
1887                                 unlock_things(fs);
1888                                 return (KERN_TRY_AGAIN);
1889                         }
1890
1891                         /*
1892                          * If the page is beyond the object size we fail
1893                          */
1894                         if (pindex >= fs->ba->object->size) {
1895                                 vm_object_pip_wakeup(fs->first_ba->object);
1896                                 unlock_things(fs);
1897                                 return (KERN_PROTECTION_FAILURE);
1898                         }
1899
1900                         /*
1901                          * Allocate a new page for this object/offset pair.
1902                          *
1903                          * It is possible for the allocation to race, so
1904                          * handle the case.
1905                          */
1906                         fs->m = NULL;
1907                         if (!vm_page_count_severe()) {
1908                                 fs->m = vm_page_alloc(fs->ba->object, pindex,
1909                                     ((fs->vp || fs->ba->backing_ba) ?
1910                                         VM_ALLOC_NULL_OK | VM_ALLOC_NORMAL :
1911                                         VM_ALLOC_NULL_OK | VM_ALLOC_NORMAL |
1912                                         VM_ALLOC_USE_GD | VM_ALLOC_ZERO));
1913                         }
1914                         if (fs->m == NULL) {
1915                                 vm_object_pip_wakeup(fs->first_ba->object);
1916                                 unlock_things(fs);
1917                                 if (allow_nofault == 0 ||
1918                                     (curthread->td_flags & TDF_NOFAULT) == 0) {
1919                                         thread_t td;
1920
1921                                         vm_wait_pfault();
1922                                         td = curthread;
1923                                         if (td->td_proc && (td->td_proc->p_flags & P_LOWMEMKILL))
1924                                                 return (KERN_PROTECTION_FAILURE);
1925                                 }
1926                                 return (KERN_TRY_AGAIN);
1927                         }
1928
1929                         /*
1930                          * Fall through to readrest.  We have a new page which
1931                          * will have to be paged (since m->valid will be 0).
1932                          */
1933                 }
1934
1935 readrest:
1936                 /*
1937                  * We have found an invalid or partially valid page, a
1938                  * page with a read-ahead mark which might be partially or
1939                  * fully valid (and maybe dirty too), or we have allocated
1940                  * a new page.
1941                  *
1942                  * Attempt to fault-in the page if there is a chance that the
1943                  * pager has it, and potentially fault in additional pages
1944                  * at the same time.
1945                  *
1946                  * If TRYPAGER is true then fs.m will be non-NULL and busied
1947                  * for us.
1948                  */
1949                 if (TRYPAGER(fs)) {
1950                         u_char behavior = vm_map_entry_behavior(fs->entry);
1951                         vm_object_t object;
1952                         vm_page_t first_m;
1953                         int seqaccess;
1954                         int rv;
1955
1956                         if (behavior == MAP_ENTRY_BEHAV_RANDOM)
1957                                 seqaccess = 0;
1958                         else
1959                                 seqaccess = -1;
1960
1961                         /*
1962                          * Doing I/O may synchronously insert additional
1963                          * pages so we can't be shared at this point either.
1964                          *
1965                          * NOTE: We can't free fs->m here in the allocated
1966                          *       case (fs->ba != fs->first_ba) as this
1967                          *       would require an exclusively locked
1968                          *       VM object.
1969                          */
1970                         if (fs->ba == fs->first_ba && fs->first_shared) {
1971                                 vm_page_deactivate(fs->m);
1972                                 vm_page_wakeup(fs->m);
1973                                 fs->m = NULL;
1974                                 fs->first_shared = 0;
1975                                 vm_object_pip_wakeup(fs->first_ba->object);
1976                                 unlock_things(fs);
1977                                 return (KERN_TRY_AGAIN);
1978                         }
1979                         if (fs->ba != fs->first_ba && fs->shared) {
1980                                 vm_page_deactivate(fs->m);
1981                                 vm_page_wakeup(fs->m);
1982                                 fs->m = NULL;
1983                                 fs->first_shared = 0;
1984                                 fs->shared = 0;
1985                                 vm_object_pip_wakeup(fs->first_ba->object);
1986                                 unlock_things(fs);
1987                                 return (KERN_TRY_AGAIN);
1988                         }
1989
1990                         object = fs->ba->object;
1991                         first_m = NULL;
1992
1993                         /* object is held, no more access to entry or ba's */
1994
1995                         /*
1996                          * Acquire the page data.  We still hold object
1997                          * and the page has been BUSY's.
1998                          *
1999                          * We own the page, but we must re-issue the lookup
2000                          * because the pager may have replaced it (for example,
2001                          * in order to enter a fictitious page into the
2002                          * object).  In this situation the pager will have
2003                          * cleaned up the old page and left the new one
2004                          * busy for us.
2005                          *
2006                          * If we got here through a PG_RAM read-ahead
2007                          * mark the page may be partially dirty and thus
2008                          * not freeable.  Don't bother checking to see
2009                          * if the pager has the page because we can't free
2010                          * it anyway.  We have to depend on the get_page
2011                          * operation filling in any gaps whether there is
2012                          * backing store or not.
2013                          *
2014                          * We must dispose of the page (fs->m) and also
2015                          * possibly first_m (the fronting layer).  If
2016                          * this is a write fault leave the page intact
2017                          * because we will probably have to copy fs->m
2018                          * to fs->first_m on the retry.  If this is a
2019                          * read fault we probably won't need the page.
2020                          */
2021                         rv = vm_pager_get_page(object, &fs->m, seqaccess);
2022
2023                         if (rv == VM_PAGER_OK) {
2024                                 ++fs->hardfault;
2025                                 fs->m = vm_page_lookup(object, pindex);
2026                                 if (fs->m) {
2027                                         vm_page_activate(fs->m);
2028                                         vm_page_wakeup(fs->m);
2029                                         fs->m = NULL;
2030                                 }
2031
2032                                 if (fs->m) {
2033                                         /* have page */
2034                                         break;
2035                                 }
2036                                 vm_object_pip_wakeup(fs->first_ba->object);
2037                                 unlock_things(fs);
2038                                 return (KERN_TRY_AGAIN);
2039                         }
2040
2041                         /*
2042                          * If the pager doesn't have the page, continue on
2043                          * to the next object.  Retain the vm_page if this
2044                          * is the first object, we may need to copy into
2045                          * it later.
2046                          */
2047                         if (rv == VM_PAGER_FAIL) {
2048                                 if (fs->ba != fs->first_ba) {
2049                                         vm_page_free(fs->m);
2050                                         fs->m = NULL;
2051                                 }
2052                                 goto next;
2053                         }
2054
2055                         /*
2056                          * Remove the bogus page (which does not exist at this
2057                          * object/offset).
2058                          *
2059                          * Also wake up any other process that may want to bring
2060                          * in this page.
2061                          *
2062                          * If this is the top-level object, we must leave the
2063                          * busy page to prevent another process from rushing
2064                          * past us, and inserting the page in that object at
2065                          * the same time that we are.
2066                          */
2067                         if (rv == VM_PAGER_ERROR) {
2068                                 if (curproc) {
2069                                         kprintf("vm_fault: pager read error, "
2070                                                 "pid %d (%s)\n",
2071                                                 curproc->p_pid,
2072                                                 curproc->p_comm);
2073                                 } else {
2074                                         kprintf("vm_fault: pager read error, "
2075                                                 "thread %p (%s)\n",
2076                                                 curthread,
2077                                                 curthread->td_comm);
2078                                 }
2079                         }
2080
2081                         /*
2082                          * I/O error or data outside pager's range.
2083                          */
2084                         if (fs->m) {
2085                                 vnode_pager_freepage(fs->m);
2086                                 fs->m = NULL;
2087                         }
2088                         if (first_m) {
2089                                 vm_page_free(first_m);
2090                                 first_m = NULL;         /* safety */
2091                         }
2092                         vm_object_pip_wakeup(object);
2093                         unlock_things(fs);
2094
2095                         switch(rv) {
2096                         case VM_PAGER_ERROR:
2097                                 return (KERN_FAILURE);
2098                         case VM_PAGER_BAD:
2099                                 return (KERN_PROTECTION_FAILURE);
2100                         default:
2101                                 return (KERN_PROTECTION_FAILURE);
2102                         }
2103
2104 #if 0
2105                         /*
2106                          * Data outside the range of the pager or an I/O error
2107                          *
2108                          * The page may have been wired during the pagein,
2109                          * e.g. by the buffer cache, and cannot simply be
2110                          * freed.  Call vnode_pager_freepage() to deal with it.
2111                          *
2112                          * The object is not held shared so we can safely
2113                          * free the page.
2114                          */
2115                         if (fs->ba != fs->first_ba) {
2116
2117                                 /*
2118                                  * XXX - we cannot just fall out at this
2119                                  * point, m has been freed and is invalid!
2120                                  */
2121                         }
2122
2123                         /*
2124                          * XXX - the check for kernel_map is a kludge to work
2125                          * around having the machine panic on a kernel space
2126                          * fault w/ I/O error.
2127                          */
2128                         if (((fs->map != &kernel_map) &&
2129                             (rv == VM_PAGER_ERROR)) || (rv == VM_PAGER_BAD)) {
2130                                 if (fs->m) {
2131                                         /* from just above */
2132                                         KKASSERT(fs->first_shared == 0);
2133                                         vnode_pager_freepage(fs->m);
2134                                         fs->m = NULL;
2135                                 }
2136                                 /* NOT REACHED */
2137                         }
2138 #endif
2139                 }
2140
2141 next:
2142                 /*
2143                  * We get here if the object has a default pager (or unwiring) 
2144                  * or the pager doesn't have the page.
2145                  *
2146                  * fs->first_m will be used for the COW unless we find a
2147                  * deeper page to be mapped read-only, in which case the
2148                  * unlock*(fs) will free first_m.
2149                  */
2150                 if (fs->ba == fs->first_ba)
2151                         fs->first_m = fs->m;
2152
2153                 /*
2154                  * Move on to the next object.  The chain lock should prevent
2155                  * the backing_object from getting ripped out from under us.
2156                  *
2157                  * The object lock for the next object is governed by
2158                  * fs->shared.
2159                  */
2160                 if ((next_ba = fs->ba->backing_ba) != NULL) {
2161                         if (fs->shared)
2162                                 vm_object_hold_shared(next_ba->object);
2163                         else
2164                                 vm_object_hold(next_ba->object);
2165                         KKASSERT(next_ba == fs->ba->backing_ba);
2166                         pindex += OFF_TO_IDX(next_ba->offset);
2167                 }
2168
2169                 if (next_ba == NULL) {
2170                         /*
2171                          * If there's no object left, fill the page in the top
2172                          * object with zeros.
2173                          */
2174                         if (fs->ba != fs->first_ba) {
2175                                 vm_object_pip_wakeup(fs->ba->object);
2176                                 vm_object_drop(fs->ba->object);
2177                                 fs->ba = fs->first_ba;
2178                                 pindex = first_pindex;
2179                                 fs->m = fs->first_m;
2180                         }
2181                         fs->first_m = NULL;
2182
2183                         /*
2184                          * Zero the page and mark it valid.
2185                          */
2186                         vm_page_zero_fill(fs->m);
2187                         mycpu->gd_cnt.v_zfod++;
2188                         fs->m->valid = VM_PAGE_BITS_ALL;
2189                         break;  /* break to PAGE HAS BEEN FOUND */
2190                 }
2191                 if (fs->ba != fs->first_ba) {
2192                         vm_object_pip_wakeup(fs->ba->object);
2193                         vm_object_lock_swap();  /* flip ba/next_ba */
2194                         vm_object_drop(fs->ba->object);
2195                 }
2196                 fs->ba = next_ba;
2197                 vm_object_pip_add(next_ba->object, 1);
2198         }
2199
2200         /*
2201          * PAGE HAS BEEN FOUND. [Loop invariant still holds -- the object lock
2202          * is held.]
2203          *
2204          * object still held.
2205          * vm_map may not be locked (determined by fs->lookup_still_valid)
2206          *
2207          * local shared variable may be different from fs->shared.
2208          *
2209          * If the page is being written, but isn't already owned by the
2210          * top-level object, we have to copy it into a new page owned by the
2211          * top-level object.
2212          */
2213         KASSERT((fs->m->busy_count & PBUSY_LOCKED) != 0,
2214                 ("vm_fault: not busy after main loop"));
2215
2216         if (fs->ba != fs->first_ba) {
2217                 /*
2218                  * We only really need to copy if we want to write it.
2219                  */
2220                 if (fault_type & VM_PROT_WRITE) {
2221 #if 0
2222                         /* CODE REFACTOR IN PROGRESS, REMOVE OPTIMIZATION */
2223                         /*
2224                          * This allows pages to be virtually copied from a 
2225                          * backing_object into the first_object, where the 
2226                          * backing object has no other refs to it, and cannot
2227                          * gain any more refs.  Instead of a bcopy, we just 
2228                          * move the page from the backing object to the 
2229                          * first object.  Note that we must mark the page 
2230                          * dirty in the first object so that it will go out 
2231                          * to swap when needed.
2232                          */
2233                         if (virtual_copy_ok(fs)) {
2234                                 /*
2235                                  * (first_m) and (m) are both busied.  We have
2236                                  * move (m) into (first_m)'s object/pindex
2237                                  * in an atomic fashion, then free (first_m).
2238                                  *
2239                                  * first_object is held so second remove
2240                                  * followed by the rename should wind
2241                                  * up being atomic.  vm_page_free() might
2242                                  * block so we don't do it until after the
2243                                  * rename.
2244                                  */
2245                                 vm_page_protect(fs->first_m, VM_PROT_NONE);
2246                                 vm_page_remove(fs->first_m);
2247                                 vm_page_rename(fs->m,
2248                                                fs->first_ba->object,
2249                                                first_pindex);
2250                                 vm_page_free(fs->first_m);
2251                                 fs->first_m = fs->m;
2252                                 fs->m = NULL;
2253                                 mycpu->gd_cnt.v_cow_optim++;
2254                         } else
2255 #endif
2256                         {
2257                                 /*
2258                                  * Oh, well, lets copy it.
2259                                  *
2260                                  * Why are we unmapping the original page
2261                                  * here?  Well, in short, not all accessors
2262                                  * of user memory go through the pmap.  The
2263                                  * procfs code doesn't have access user memory
2264                                  * via a local pmap, so vm_fault_page*()
2265                                  * can't call pmap_enter().  And the umtx*()
2266                                  * code may modify the COW'd page via a DMAP
2267                                  * or kernel mapping and not via the pmap,
2268                                  * leaving the original page still mapped
2269                                  * read-only into the pmap.
2270                                  *
2271                                  * So we have to remove the page from at
2272                                  * least the current pmap if it is in it.
2273                                  *
2274                                  * We used to just remove it from all pmaps
2275                                  * but that creates inefficiencies on SMP,
2276                                  * particularly for COW program & library
2277                                  * mappings that are concurrently exec'd.
2278                                  * Only remove the page from the current
2279                                  * pmap.
2280                                  */
2281                                 KKASSERT(fs->first_shared == 0);
2282                                 vm_page_copy(fs->m, fs->first_m);
2283                                 /*vm_page_protect(fs->m, VM_PROT_NONE);*/
2284                                 pmap_remove_specific(
2285                                     &curthread->td_lwp->lwp_vmspace->vm_pmap,
2286                                     fs->m);
2287                         }
2288
2289                         /*
2290                          * We no longer need the old page or object.
2291                          */
2292                         if (fs->m)
2293                                 release_page(fs);
2294
2295                         /*
2296                          * fs->ba != fs->first_ba due to above conditional
2297                          */
2298                         vm_object_pip_wakeup(fs->ba->object);
2299                         vm_object_drop(fs->ba->object);
2300                         fs->ba = fs->first_ba;
2301
2302                         /*
2303                          * Only use the new page below...
2304                          */
2305                         mycpu->gd_cnt.v_cow_faults++;
2306                         fs->m = fs->first_m;
2307                         pindex = first_pindex;
2308                 } else {
2309                         /*
2310                          * If it wasn't a write fault avoid having to copy
2311                          * the page by mapping it read-only from backing
2312                          * store.  The process is not allowed to modify
2313                          * backing pages.
2314                          */
2315                         fs->prot &= ~VM_PROT_WRITE;
2316                 }
2317         }
2318
2319         /*
2320          * Relock the map if necessary, then check the generation count.
2321          * relock_map() will update fs->timestamp to account for the
2322          * relocking if necessary.
2323          *
2324          * If the count has changed after relocking then all sorts of
2325          * crap may have happened and we have to retry.
2326          *
2327          * NOTE: The relock_map() can fail due to a deadlock against
2328          *       the vm_page we are holding BUSY.
2329          */
2330         KKASSERT(fs->lookup_still_valid != 0);
2331 #if 0
2332         if (fs->lookup_still_valid == 0 && fs->map) {
2333                 if (relock_map(fs) ||
2334                     fs->map->timestamp != fs->map_generation) {
2335                         release_page(fs);
2336                         vm_object_pip_wakeup(fs->first_ba->object);
2337                         unlock_things(fs);
2338                         return (KERN_TRY_AGAIN);
2339                 }
2340         }
2341 #endif
2342
2343         /*
2344          * If the fault is a write, we know that this page is being
2345          * written NOW so dirty it explicitly to save on pmap_is_modified()
2346          * calls later.
2347          *
2348          * If this is a NOSYNC mmap we do not want to set PG_NOSYNC
2349          * if the page is already dirty to prevent data written with
2350          * the expectation of being synced from not being synced.
2351          * Likewise if this entry does not request NOSYNC then make
2352          * sure the page isn't marked NOSYNC.  Applications sharing
2353          * data should use the same flags to avoid ping ponging.
2354          *
2355          * Also tell the backing pager, if any, that it should remove
2356          * any swap backing since the page is now dirty.
2357          */
2358         vm_page_activate(fs->m);
2359         if (fs->prot & VM_PROT_WRITE) {
2360                 vm_object_set_writeable_dirty(fs->m->object);
2361                 vm_set_nosync(fs->m, fs->entry);
2362                 if (fs->fault_flags & VM_FAULT_DIRTY) {
2363                         vm_page_dirty(fs->m);
2364                         if (fs->m->flags & PG_SWAPPED) {
2365                                 /*
2366                                  * If the page is swapped out we have to call
2367                                  * swap_pager_unswapped() which requires an
2368                                  * exclusive object lock.  If we are shared,
2369                                  * we must clear the shared flag and retry.
2370                                  */
2371                                 if ((fs->ba == fs->first_ba &&
2372                                      fs->first_shared) ||
2373                                     (fs->ba != fs->first_ba && fs->shared)) {
2374                                         vm_page_wakeup(fs->m);
2375                                         fs->m = NULL;
2376                                         if (fs->ba == fs->first_ba)
2377                                                 fs->first_shared = 0;
2378                                         else
2379                                                 fs->shared = 0;
2380                                         vm_object_pip_wakeup(
2381                                                         fs->first_ba->object);
2382                                         unlock_things(fs);
2383                                         return (KERN_TRY_AGAIN);
2384                                 }
2385                                 swap_pager_unswapped(fs->m);
2386                         }
2387                 }
2388         }
2389
2390         /*
2391          * We found our page at backing layer ba.  Leave the layer state
2392          * intact.
2393          */
2394
2395         vm_object_pip_wakeup(fs->first_ba->object);
2396 #if 0
2397         if (fs->ba != fs->first_ba)
2398                 vm_object_drop(fs->ba->object);
2399 #endif
2400
2401         /*
2402          * Page had better still be busy.  We are still locked up and 
2403          * fs->ba->object will have another PIP reference for the case
2404          * where fs->ba != fs->first_ba.
2405          */
2406         KASSERT(fs->m->busy_count & PBUSY_LOCKED,
2407                 ("vm_fault: page %p not busy!", fs->m));
2408
2409         /*
2410          * Sanity check: page must be completely valid or it is not fit to
2411          * map into user space.  vm_pager_get_pages() ensures this.
2412          */
2413         if (fs->m->valid != VM_PAGE_BITS_ALL) {
2414                 vm_page_zero_invalid(fs->m, TRUE);
2415                 kprintf("Warning: page %p partially invalid on fault\n", fs->m);
2416         }
2417
2418         return (KERN_SUCCESS);
2419 }
2420
2421 /*
2422  * Wire down a range of virtual addresses in a map.  The entry in question
2423  * should be marked in-transition and the map must be locked.  We must
2424  * release the map temporarily while faulting-in the page to avoid a
2425  * deadlock.  Note that the entry may be clipped while we are blocked but
2426  * will never be freed.
2427  *
2428  * map must be locked on entry.
2429  */
2430 int
2431 vm_fault_wire(vm_map_t map, vm_map_entry_t entry,
2432               boolean_t user_wire, int kmflags)
2433 {
2434         boolean_t fictitious;
2435         vm_offset_t start;
2436         vm_offset_t end;
2437         vm_offset_t va;
2438         pmap_t pmap;
2439         int rv;
2440         int wire_prot;
2441         int fault_flags;
2442         vm_page_t m;
2443
2444         if (user_wire) {
2445                 wire_prot = VM_PROT_READ;
2446                 fault_flags = VM_FAULT_USER_WIRE;
2447         } else {
2448                 wire_prot = VM_PROT_READ | VM_PROT_WRITE;
2449                 fault_flags = VM_FAULT_CHANGE_WIRING;
2450         }
2451         if (kmflags & KM_NOTLBSYNC)
2452                 wire_prot |= VM_PROT_NOSYNC;
2453
2454         pmap = vm_map_pmap(map);
2455         start = entry->start;
2456         end = entry->end;
2457
2458         switch(entry->maptype) {
2459         case VM_MAPTYPE_NORMAL:
2460         case VM_MAPTYPE_VPAGETABLE:
2461                 fictitious = entry->ba.object &&
2462                             ((entry->ba.object->type == OBJT_DEVICE) ||
2463                              (entry->ba.object->type == OBJT_MGTDEVICE));
2464                 break;
2465         case VM_MAPTYPE_UKSMAP:
2466                 fictitious = TRUE;
2467                 break;
2468         default:
2469                 fictitious = FALSE;
2470                 break;
2471         }
2472
2473         if (entry->eflags & MAP_ENTRY_KSTACK)
2474                 start += PAGE_SIZE;
2475         map->timestamp++;
2476         vm_map_unlock(map);
2477
2478         /*
2479          * We simulate a fault to get the page and enter it in the physical
2480          * map.
2481          */
2482         for (va = start; va < end; va += PAGE_SIZE) {
2483                 rv = vm_fault(map, va, wire_prot, fault_flags);
2484                 if (rv) {
2485                         while (va > start) {
2486                                 va -= PAGE_SIZE;
2487                                 m = pmap_unwire(pmap, va);
2488                                 if (m && !fictitious) {
2489                                         vm_page_busy_wait(m, FALSE, "vmwrpg");
2490                                         vm_page_unwire(m, 1);
2491                                         vm_page_wakeup(m);
2492                                 }
2493                         }
2494                         goto done;
2495                 }
2496         }
2497         rv = KERN_SUCCESS;
2498 done:
2499         vm_map_lock(map);
2500
2501         return (rv);
2502 }
2503
2504 /*
2505  * Unwire a range of virtual addresses in a map.  The map should be
2506  * locked.
2507  */
2508 void
2509 vm_fault_unwire(vm_map_t map, vm_map_entry_t entry)
2510 {
2511         boolean_t fictitious;
2512         vm_offset_t start;
2513         vm_offset_t end;
2514         vm_offset_t va;
2515         pmap_t pmap;
2516         vm_page_t m;
2517
2518         pmap = vm_map_pmap(map);
2519         start = entry->start;
2520         end = entry->end;
2521         fictitious = entry->ba.object &&
2522                         ((entry->ba.object->type == OBJT_DEVICE) ||
2523                          (entry->ba.object->type == OBJT_MGTDEVICE));
2524         if (entry->eflags & MAP_ENTRY_KSTACK)
2525                 start += PAGE_SIZE;
2526
2527         /*
2528          * Since the pages are wired down, we must be able to get their
2529          * mappings from the physical map system.
2530          */
2531         for (va = start; va < end; va += PAGE_SIZE) {
2532                 m = pmap_unwire(pmap, va);
2533                 if (m && !fictitious) {
2534                         vm_page_busy_wait(m, FALSE, "vmwrpg");
2535                         vm_page_unwire(m, 1);
2536                         vm_page_wakeup(m);
2537                 }
2538         }
2539 }
2540
2541 /*
2542  * Simulate write faults to bring all data into the head object, return
2543  * KERN_SUCCESS on success (which should be always unless the system runs
2544  * out of memory).
2545  *
2546  * The caller will handle destroying the backing_ba's.
2547  */
2548 int
2549 vm_fault_collapse(vm_map_t map, vm_map_entry_t entry)
2550 {
2551         struct faultstate fs;
2552         vm_ooffset_t scan;
2553         vm_pindex_t pindex;
2554         vm_object_t object;
2555         int rv;
2556         int all_shadowed;
2557
2558         bzero(&fs, sizeof(fs));
2559         object = entry->ba.object;
2560
2561         fs.first_prot = entry->max_protection | /* optional VM_PROT_EXECUTE */
2562                         VM_PROT_READ | VM_PROT_WRITE | VM_PROT_OVERRIDE_WRITE;
2563         fs.fault_flags = VM_FAULT_NORMAL;
2564         fs.map = map;
2565         fs.entry = entry;
2566         fs.lookup_still_valid = -1;     /* leave map atomically locked */
2567         fs.first_ba = &entry->ba;
2568         fs.first_ba_held = -1;          /* leave object held */
2569
2570         /* fs.hardfault */
2571
2572         vm_object_hold(object);
2573         rv = KERN_SUCCESS;
2574
2575         scan = entry->start;
2576         all_shadowed = 1;
2577
2578         while (scan < entry->end) {
2579                 pindex = OFF_TO_IDX(entry->ba.offset + (scan - entry->start));
2580
2581                 if (vm_page_lookup(object, pindex)) {
2582                         scan += PAGE_SIZE;
2583                         continue;
2584                 }
2585
2586                 all_shadowed = 0;
2587                 fs.ba = fs.first_ba;
2588                 fs.prot = fs.first_prot;
2589
2590                 rv = vm_fault_object(&fs, pindex, fs.first_prot, 1);
2591                 if (rv == KERN_TRY_AGAIN)
2592                         continue;
2593                 if (rv != KERN_SUCCESS)
2594                         break;
2595                 vm_page_flag_set(fs.m, PG_REFERENCED);
2596                 vm_page_activate(fs.m);
2597                 vm_page_wakeup(fs.m);
2598                 scan += PAGE_SIZE;
2599         }
2600         KKASSERT(entry->ba.object == object);
2601         vm_object_drop(object);
2602
2603         /*
2604          * If the fronting object did not have every page we have to clear
2605          * the pmap range due to the pages being changed so we can fault-in
2606          * the proper pages.
2607          */
2608         if (all_shadowed == 0)
2609                 pmap_remove(map->pmap, entry->start, entry->end);
2610
2611         return rv;
2612 }
2613
2614 /*
2615  * Copy all of the pages from one map entry to another.  If the source
2616  * is wired down we just use vm_page_lookup().  If not we use
2617  * vm_fault_object().
2618  *
2619  * The source and destination maps must be locked for write.
2620  * The source and destination maps token must be held
2621  *
2622  * No other requirements.
2623  *
2624  * XXX do segment optimization
2625  */
2626 void
2627 vm_fault_copy_entry(vm_map_t dst_map, vm_map_t src_map,
2628                     vm_map_entry_t dst_entry, vm_map_entry_t src_entry)
2629 {
2630         vm_object_t dst_object;
2631         vm_object_t src_object;
2632         vm_ooffset_t dst_offset;
2633         vm_ooffset_t src_offset;
2634         vm_prot_t prot;
2635         vm_offset_t vaddr;
2636         vm_page_t dst_m;
2637         vm_page_t src_m;
2638
2639         src_object = src_entry->ba.object;
2640         src_offset = src_entry->ba.offset;
2641
2642         /*
2643          * Create the top-level object for the destination entry. (Doesn't
2644          * actually shadow anything - we copy the pages directly.)
2645          */
2646         vm_map_entry_allocate_object(dst_entry);
2647         dst_object = dst_entry->ba.object;
2648
2649         prot = dst_entry->max_protection;
2650
2651         /*
2652          * Loop through all of the pages in the entry's range, copying each
2653          * one from the source object (it should be there) to the destination
2654          * object.
2655          */
2656         vm_object_hold(src_object);
2657         vm_object_hold(dst_object);
2658
2659         for (vaddr = dst_entry->start, dst_offset = 0;
2660              vaddr < dst_entry->end;
2661              vaddr += PAGE_SIZE, dst_offset += PAGE_SIZE) {
2662
2663                 /*
2664                  * Allocate a page in the destination object
2665                  */
2666                 do {
2667                         dst_m = vm_page_alloc(dst_object,
2668                                               OFF_TO_IDX(dst_offset),
2669                                               VM_ALLOC_NORMAL);
2670                         if (dst_m == NULL) {
2671                                 vm_wait(0);
2672                         }
2673                 } while (dst_m == NULL);
2674
2675                 /*
2676                  * Find the page in the source object, and copy it in.
2677                  * (Because the source is wired down, the page will be in
2678                  * memory.)
2679                  */
2680                 src_m = vm_page_lookup(src_object,
2681                                        OFF_TO_IDX(dst_offset + src_offset));
2682                 if (src_m == NULL)
2683                         panic("vm_fault_copy_wired: page missing");
2684
2685                 vm_page_copy(src_m, dst_m);
2686
2687                 /*
2688                  * Enter it in the pmap...
2689                  */
2690                 pmap_enter(dst_map->pmap, vaddr, dst_m, prot, FALSE, dst_entry);
2691
2692                 /*
2693                  * Mark it no longer busy, and put it on the active list.
2694                  */
2695                 vm_page_activate(dst_m);
2696                 vm_page_wakeup(dst_m);
2697         }
2698         vm_object_drop(dst_object);
2699         vm_object_drop(src_object);
2700 }
2701
2702 #if 0
2703
2704 /*
2705  * This routine checks around the requested page for other pages that
2706  * might be able to be faulted in.  This routine brackets the viable
2707  * pages for the pages to be paged in.
2708  *
2709  * Inputs:
2710  *      m, rbehind, rahead
2711  *
2712  * Outputs:
2713  *  marray (array of vm_page_t), reqpage (index of requested page)
2714  *
2715  * Return value:
2716  *  number of pages in marray
2717  */
2718 static int
2719 vm_fault_additional_pages(vm_page_t m, int rbehind, int rahead,
2720                           vm_page_t *marray, int *reqpage)
2721 {
2722         int i,j;
2723         vm_object_t object;
2724         vm_pindex_t pindex, startpindex, endpindex, tpindex;
2725         vm_page_t rtm;
2726         int cbehind, cahead;
2727
2728         object = m->object;
2729         pindex = m->pindex;
2730
2731         /*
2732          * we don't fault-ahead for device pager
2733          */
2734         if ((object->type == OBJT_DEVICE) ||
2735             (object->type == OBJT_MGTDEVICE)) {
2736                 *reqpage = 0;
2737                 marray[0] = m;
2738                 return 1;
2739         }
2740
2741         /*
2742          * if the requested page is not available, then give up now
2743          */
2744         if (!vm_pager_has_page(object, pindex, &cbehind, &cahead)) {
2745                 *reqpage = 0;   /* not used by caller, fix compiler warn */
2746                 return 0;
2747         }
2748
2749         if ((cbehind == 0) && (cahead == 0)) {
2750                 *reqpage = 0;
2751                 marray[0] = m;
2752                 return 1;
2753         }
2754
2755         if (rahead > cahead) {
2756                 rahead = cahead;
2757         }
2758
2759         if (rbehind > cbehind) {
2760                 rbehind = cbehind;
2761         }
2762
2763         /*
2764          * Do not do any readahead if we have insufficient free memory.
2765          *
2766          * XXX code was broken disabled before and has instability
2767          * with this conditonal fixed, so shortcut for now.
2768          */
2769         if (burst_fault == 0 || vm_page_count_severe()) {
2770                 marray[0] = m;
2771                 *reqpage = 0;
2772                 return 1;
2773         }
2774
2775         /*
2776          * scan backward for the read behind pages -- in memory 
2777          *
2778          * Assume that if the page is not found an interrupt will not
2779          * create it.  Theoretically interrupts can only remove (busy)
2780          * pages, not create new associations.
2781          */
2782         if (pindex > 0) {
2783                 if (rbehind > pindex) {
2784                         rbehind = pindex;
2785                         startpindex = 0;
2786                 } else {
2787                         startpindex = pindex - rbehind;
2788                 }
2789
2790                 vm_object_hold(object);
2791                 for (tpindex = pindex; tpindex > startpindex; --tpindex) {
2792                         if (vm_page_lookup(object, tpindex - 1))
2793                                 break;
2794                 }
2795
2796                 i = 0;
2797                 while (tpindex < pindex) {
2798                         rtm = vm_page_alloc(object, tpindex, VM_ALLOC_SYSTEM |
2799                                                              VM_ALLOC_NULL_OK);
2800                         if (rtm == NULL) {
2801                                 for (j = 0; j < i; j++) {
2802                                         vm_page_free(marray[j]);
2803                                 }
2804                                 vm_object_drop(object);
2805                                 marray[0] = m;
2806                                 *reqpage = 0;
2807                                 return 1;
2808                         }
2809                         marray[i] = rtm;
2810                         ++i;
2811                         ++tpindex;
2812                 }
2813                 vm_object_drop(object);
2814         } else {
2815                 i = 0;
2816         }
2817
2818         /*
2819          * Assign requested page
2820          */
2821         marray[i] = m;
2822         *reqpage = i;
2823         ++i;
2824
2825         /*
2826          * Scan forwards for read-ahead pages
2827          */
2828         tpindex = pindex + 1;
2829         endpindex = tpindex + rahead;
2830         if (endpindex > object->size)
2831                 endpindex = object->size;
2832
2833         vm_object_hold(object);
2834         while (tpindex < endpindex) {
2835                 if (vm_page_lookup(object, tpindex))
2836                         break;
2837                 rtm = vm_page_alloc(object, tpindex, VM_ALLOC_SYSTEM |
2838                                                      VM_ALLOC_NULL_OK);
2839                 if (rtm == NULL)
2840                         break;
2841                 marray[i] = rtm;
2842                 ++i;
2843                 ++tpindex;
2844         }
2845         vm_object_drop(object);
2846
2847         return (i);
2848 }
2849
2850 #endif
2851
2852 /*
2853  * vm_prefault() provides a quick way of clustering pagefaults into a
2854  * processes address space.  It is a "cousin" of pmap_object_init_pt,
2855  * except it runs at page fault time instead of mmap time.
2856  *
2857  * vm.fast_fault        Enables pre-faulting zero-fill pages
2858  *
2859  * vm.prefault_pages    Number of pages (1/2 negative, 1/2 positive) to
2860  *                      prefault.  Scan stops in either direction when
2861  *                      a page is found to already exist.
2862  *
2863  * This code used to be per-platform pmap_prefault().  It is now
2864  * machine-independent and enhanced to also pre-fault zero-fill pages
2865  * (see vm.fast_fault) as well as make them writable, which greatly
2866  * reduces the number of page faults programs incur.
2867  *
2868  * Application performance when pre-faulting zero-fill pages is heavily
2869  * dependent on the application.  Very tiny applications like /bin/echo
2870  * lose a little performance while applications of any appreciable size
2871  * gain performance.  Prefaulting multiple pages also reduces SMP
2872  * congestion and can improve SMP performance significantly.
2873  *
2874  * NOTE!  prot may allow writing but this only applies to the top level
2875  *        object.  If we wind up mapping a page extracted from a backing
2876  *        object we have to make sure it is read-only.
2877  *
2878  * NOTE!  The caller has already handled any COW operations on the
2879  *        vm_map_entry via the normal fault code.  Do NOT call this
2880  *        shortcut unless the normal fault code has run on this entry.
2881  *
2882  * The related map must be locked.
2883  * No other requirements.
2884  */
2885 __read_mostly static int vm_prefault_pages = 8;
2886 SYSCTL_INT(_vm, OID_AUTO, prefault_pages, CTLFLAG_RW, &vm_prefault_pages, 0,
2887            "Maximum number of pages to pre-fault");
2888 __read_mostly static int vm_fast_fault = 1;
2889 SYSCTL_INT(_vm, OID_AUTO, fast_fault, CTLFLAG_RW, &vm_fast_fault, 0,
2890            "Burst fault zero-fill regions");
2891
2892 /*
2893  * Set PG_NOSYNC if the map entry indicates so, but only if the page
2894  * is not already dirty by other means.  This will prevent passive
2895  * filesystem syncing as well as 'sync' from writing out the page.
2896  */
2897 static void
2898 vm_set_nosync(vm_page_t m, vm_map_entry_t entry)
2899 {
2900         if (entry->eflags & MAP_ENTRY_NOSYNC) {
2901                 if (m->dirty == 0)
2902                         vm_page_flag_set(m, PG_NOSYNC);
2903         } else {
2904                 vm_page_flag_clear(m, PG_NOSYNC);
2905         }
2906 }
2907
2908 static void
2909 vm_prefault(pmap_t pmap, vm_offset_t addra, vm_map_entry_t entry, int prot,
2910             int fault_flags)
2911 {
2912         vm_map_backing_t ba;    /* first ba */
2913         struct lwp *lp;
2914         vm_page_t m;
2915         vm_offset_t addr;
2916         vm_pindex_t index;
2917         vm_pindex_t pindex;
2918         vm_object_t object;
2919         int pprot;
2920         int i;
2921         int noneg;
2922         int nopos;
2923         int maxpages;
2924
2925         /*
2926          * Get stable max count value, disabled if set to 0
2927          */
2928         maxpages = vm_prefault_pages;
2929         cpu_ccfence();
2930         if (maxpages <= 0)
2931                 return;
2932
2933         /*
2934          * We do not currently prefault mappings that use virtual page
2935          * tables.  We do not prefault foreign pmaps.
2936          */
2937         if (entry->maptype != VM_MAPTYPE_NORMAL)
2938                 return;
2939         lp = curthread->td_lwp;
2940         if (lp == NULL || (pmap != vmspace_pmap(lp->lwp_vmspace)))
2941                 return;
2942
2943         /*
2944          * Limit pre-fault count to 1024 pages.
2945          */
2946         if (maxpages > 1024)
2947                 maxpages = 1024;
2948
2949         ba = &entry->ba;
2950         object = entry->ba.object;
2951         KKASSERT(object != NULL);
2952
2953         /*
2954          * NOTE: VM_FAULT_DIRTY allowed later so must hold object exclusively
2955          *       now (or do something more complex XXX).
2956          */
2957         vm_object_hold(object);
2958
2959         noneg = 0;
2960         nopos = 0;
2961         for (i = 0; i < maxpages; ++i) {
2962                 vm_object_t lobject;
2963                 vm_object_t nobject;
2964                 vm_map_backing_t last_ba;       /* last ba */
2965                 vm_map_backing_t next_ba;       /* last ba */
2966                 int allocated = 0;
2967                 int error;
2968
2969                 /*
2970                  * This can eat a lot of time on a heavily contended
2971                  * machine so yield on the tick if needed.
2972                  */
2973                 if ((i & 7) == 7)
2974                         lwkt_yield();
2975
2976                 /*
2977                  * Calculate the page to pre-fault, stopping the scan in
2978                  * each direction separately if the limit is reached.
2979                  */
2980                 if (i & 1) {
2981                         if (noneg)
2982                                 continue;
2983                         addr = addra - ((i + 1) >> 1) * PAGE_SIZE;
2984                 } else {
2985                         if (nopos)
2986                                 continue;
2987                         addr = addra + ((i + 2) >> 1) * PAGE_SIZE;
2988                 }
2989                 if (addr < entry->start) {
2990                         noneg = 1;
2991                         if (noneg && nopos)
2992                                 break;
2993                         continue;
2994                 }
2995                 if (addr >= entry->end) {
2996                         nopos = 1;
2997                         if (noneg && nopos)
2998                                 break;
2999                         continue;
3000                 }
3001
3002                 /*
3003                  * Skip pages already mapped, and stop scanning in that
3004                  * direction.  When the scan terminates in both directions
3005                  * we are done.
3006                  */
3007                 if (pmap_prefault_ok(pmap, addr) == 0) {
3008                         if (i & 1)
3009                                 noneg = 1;
3010                         else
3011                                 nopos = 1;
3012                         if (noneg && nopos)
3013                                 break;
3014                         continue;
3015                 }
3016
3017                 /*
3018                  * Follow the backing layers to obtain the page to be mapped
3019                  * into the pmap.
3020                  *
3021                  * If we reach the terminal object without finding a page
3022                  * and we determine it would be advantageous, then allocate
3023                  * a zero-fill page for the base object.  The base object
3024                  * is guaranteed to be OBJT_DEFAULT for this case.
3025                  *
3026                  * In order to not have to check the pager via *haspage*()
3027                  * we stop if any non-default object is encountered.  e.g.
3028                  * a vnode or swap object would stop the loop.
3029                  */
3030                 index = ((addr - entry->start) + entry->ba.offset) >>
3031                         PAGE_SHIFT;
3032                 last_ba = ba;
3033                 lobject = object;
3034                 pindex = index;
3035                 pprot = prot;
3036
3037                 /*vm_object_hold(lobject); implied */
3038
3039                 while ((m = vm_page_lookup_busy_try(lobject, pindex,
3040                                                     TRUE, &error)) == NULL) {
3041                         if (lobject->type != OBJT_DEFAULT)
3042                                 break;
3043                         if ((next_ba = last_ba->backing_ba) == NULL) {
3044                                 if (vm_fast_fault == 0)
3045                                         break;
3046                                 if ((prot & VM_PROT_WRITE) == 0 ||
3047                                     vm_page_count_min(0)) {
3048                                         break;
3049                                 }
3050
3051                                 /*
3052                                  * NOTE: Allocated from base object
3053                                  */
3054                                 m = vm_page_alloc(object, index,
3055                                                   VM_ALLOC_NORMAL |
3056                                                   VM_ALLOC_ZERO |
3057                                                   VM_ALLOC_USE_GD |
3058                                                   VM_ALLOC_NULL_OK);
3059                                 if (m == NULL)
3060                                         break;
3061                                 allocated = 1;
3062                                 pprot = prot;
3063                                 /* lobject = object .. not needed */
3064                                 break;
3065                         }
3066                         if (next_ba->offset & PAGE_MASK)
3067                                 break;
3068                         nobject = next_ba->object;
3069                         vm_object_hold(nobject);
3070                         pindex += next_ba->offset >> PAGE_SHIFT;
3071                         if (last_ba != ba) {
3072                                 vm_object_lock_swap();
3073                                 vm_object_drop(lobject);
3074                         }
3075                         lobject = nobject;
3076                         last_ba = next_ba;
3077                         pprot &= ~VM_PROT_WRITE;
3078                 }
3079
3080                 /*
3081                  * NOTE: A non-NULL (m) will be associated with lobject if
3082                  *       it was found there, otherwise it is probably a
3083                  *       zero-fill page associated with the base object.
3084                  *
3085                  * Give-up if no page is available.
3086                  */
3087                 if (m == NULL) {
3088                         if (last_ba != ba)
3089                                 vm_object_drop(lobject);
3090                         break;
3091                 }
3092
3093                 /*
3094                  * The object must be marked dirty if we are mapping a
3095                  * writable page.  m->object is either lobject or object,
3096                  * both of which are still held.  Do this before we
3097                  * potentially drop the object.
3098                  */
3099                 if (pprot & VM_PROT_WRITE)
3100                         vm_object_set_writeable_dirty(m->object);
3101
3102                 /*
3103                  * Do not conditionalize on PG_RAM.  If pages are present in
3104                  * the VM system we assume optimal caching.  If caching is
3105                  * not optimal the I/O gravy train will be restarted when we
3106                  * hit an unavailable page.  We do not want to try to restart
3107                  * the gravy train now because we really don't know how much
3108                  * of the object has been cached.  The cost for restarting
3109                  * the gravy train should be low (since accesses will likely
3110                  * be I/O bound anyway).
3111                  */
3112                 if (last_ba != ba)
3113                         vm_object_drop(lobject);
3114
3115                 /*
3116                  * Enter the page into the pmap if appropriate.  If we had
3117                  * allocated the page we have to place it on a queue.  If not
3118                  * we just have to make sure it isn't on the cache queue
3119                  * (pages on the cache queue are not allowed to be mapped).
3120                  */
3121                 if (allocated) {
3122                         /*
3123                          * Page must be zerod.
3124                          */
3125                         vm_page_zero_fill(m);
3126                         mycpu->gd_cnt.v_zfod++;
3127                         m->valid = VM_PAGE_BITS_ALL;
3128
3129                         /*
3130                          * Handle dirty page case
3131                          */
3132                         if (pprot & VM_PROT_WRITE)
3133                                 vm_set_nosync(m, entry);
3134                         pmap_enter(pmap, addr, m, pprot, 0, entry);
3135                         mycpu->gd_cnt.v_vm_faults++;
3136                         if (curthread->td_lwp)
3137                                 ++curthread->td_lwp->lwp_ru.ru_minflt;
3138                         vm_page_deactivate(m);
3139                         if (pprot & VM_PROT_WRITE) {
3140                                 /*vm_object_set_writeable_dirty(m->object);*/
3141                                 vm_set_nosync(m, entry);
3142                                 if (fault_flags & VM_FAULT_DIRTY) {
3143                                         vm_page_dirty(m);
3144                                         /*XXX*/
3145                                         swap_pager_unswapped(m);
3146                                 }
3147                         }
3148                         vm_page_wakeup(m);
3149                 } else if (error) {
3150                         /* couldn't busy page, no wakeup */
3151                 } else if (
3152                     ((m->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
3153                     (m->flags & PG_FICTITIOUS) == 0) {
3154                         /*
3155                          * A fully valid page not undergoing soft I/O can
3156                          * be immediately entered into the pmap.
3157                          */
3158                         if ((m->queue - m->pc) == PQ_CACHE)
3159                                 vm_page_deactivate(m);
3160                         if (pprot & VM_PROT_WRITE) {
3161                                 /*vm_object_set_writeable_dirty(m->object);*/
3162                                 vm_set_nosync(m, entry);
3163                                 if (fault_flags & VM_FAULT_DIRTY) {
3164                                         vm_page_dirty(m);
3165                                         /*XXX*/
3166                                         swap_pager_unswapped(m);
3167                                 }
3168                         }
3169                         if (pprot & VM_PROT_WRITE)
3170                                 vm_set_nosync(m, entry);
3171                         pmap_enter(pmap, addr, m, pprot, 0, entry);
3172                         mycpu->gd_cnt.v_vm_faults++;
3173                         if (curthread->td_lwp)
3174                                 ++curthread->td_lwp->lwp_ru.ru_minflt;
3175                         vm_page_wakeup(m);
3176                 } else {
3177                         vm_page_wakeup(m);
3178                 }
3179         }
3180         vm_object_drop(object);
3181 }
3182
3183 /*
3184  * Object can be held shared
3185  */
3186 static void
3187 vm_prefault_quick(pmap_t pmap, vm_offset_t addra,
3188                   vm_map_entry_t entry, int prot, int fault_flags)
3189 {
3190         struct lwp *lp;
3191         vm_page_t m;
3192         vm_offset_t addr;
3193         vm_pindex_t pindex;
3194         vm_object_t object;
3195         int i;
3196         int noneg;
3197         int nopos;
3198         int maxpages;
3199
3200         /*
3201          * Get stable max count value, disabled if set to 0
3202          */
3203         maxpages = vm_prefault_pages;
3204         cpu_ccfence();
3205         if (maxpages <= 0)
3206                 return;
3207
3208         /*
3209          * We do not currently prefault mappings that use virtual page
3210          * tables.  We do not prefault foreign pmaps.
3211          */
3212         if (entry->maptype != VM_MAPTYPE_NORMAL)
3213                 return;
3214         lp = curthread->td_lwp;
3215         if (lp == NULL || (pmap != vmspace_pmap(lp->lwp_vmspace)))
3216                 return;
3217         object = entry->ba.object;
3218         if (entry->ba.backing_ba != NULL)
3219                 return;
3220         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
3221
3222         /*
3223          * Limit pre-fault count to 1024 pages.
3224          */
3225         if (maxpages > 1024)
3226                 maxpages = 1024;
3227
3228         noneg = 0;
3229         nopos = 0;
3230         for (i = 0; i < maxpages; ++i) {
3231                 int error;
3232
3233                 /*
3234                  * Calculate the page to pre-fault, stopping the scan in
3235                  * each direction separately if the limit is reached.
3236                  */
3237                 if (i & 1) {
3238                         if (noneg)
3239                                 continue;
3240                         addr = addra - ((i + 1) >> 1) * PAGE_SIZE;
3241                 } else {
3242                         if (nopos)
3243                                 continue;
3244                         addr = addra + ((i + 2) >> 1) * PAGE_SIZE;
3245                 }
3246                 if (addr < entry->start) {
3247                         noneg = 1;
3248                         if (noneg && nopos)
3249                                 break;
3250                         continue;
3251                 }
3252                 if (addr >= entry->end) {
3253                         nopos = 1;
3254                         if (noneg && nopos)
3255                                 break;
3256                         continue;
3257                 }
3258
3259                 /*
3260                  * Follow the VM object chain to obtain the page to be mapped
3261                  * into the pmap.  This version of the prefault code only
3262                  * works with terminal objects.
3263                  *
3264                  * The page must already exist.  If we encounter a problem
3265                  * we stop here.
3266                  *
3267                  * WARNING!  We cannot call swap_pager_unswapped() or insert
3268                  *           a new vm_page with a shared token.
3269                  */
3270                 pindex = ((addr - entry->start) + entry->ba.offset) >>
3271                          PAGE_SHIFT;
3272
3273                 /*
3274                  * Skip pages already mapped, and stop scanning in that
3275                  * direction.  When the scan terminates in both directions
3276                  * we are done.
3277                  */
3278                 if (pmap_prefault_ok(pmap, addr) == 0) {
3279                         if (i & 1)
3280                                 noneg = 1;
3281                         else
3282                                 nopos = 1;
3283                         if (noneg && nopos)
3284                                 break;
3285                         continue;
3286                 }
3287
3288                 /*
3289                  * Shortcut the read-only mapping case using the far more
3290                  * efficient vm_page_lookup_sbusy_try() function.  This
3291                  * allows us to acquire the page soft-busied only which
3292                  * is especially nice for concurrent execs of the same
3293                  * program.
3294                  *
3295                  * The lookup function also validates page suitability
3296                  * (all valid bits set, and not fictitious).
3297                  *
3298                  * If the page is in PQ_CACHE we have to fall-through
3299                  * and hard-busy it so we can move it out of PQ_CACHE.
3300                  */
3301                 if ((prot & VM_PROT_WRITE) == 0) {
3302                         m = vm_page_lookup_sbusy_try(object, pindex,
3303                                                      0, PAGE_SIZE);
3304                         if (m == NULL)
3305                                 break;
3306                         if ((m->queue - m->pc) != PQ_CACHE) {
3307                                 pmap_enter(pmap, addr, m, prot, 0, entry);
3308                                 mycpu->gd_cnt.v_vm_faults++;
3309                                 if (curthread->td_lwp)
3310                                         ++curthread->td_lwp->lwp_ru.ru_minflt;
3311                                 vm_page_sbusy_drop(m);
3312                                 continue;
3313                         }
3314                         vm_page_sbusy_drop(m);
3315                 }
3316
3317                 /*
3318                  * Fallback to normal vm_page lookup code.  This code
3319                  * hard-busies the page.  Not only that, but the page
3320                  * can remain in that state for a significant period
3321                  * time due to pmap_enter()'s overhead.
3322                  */
3323                 m = vm_page_lookup_busy_try(object, pindex, TRUE, &error);
3324                 if (m == NULL || error)
3325                         break;
3326
3327                 /*
3328                  * Stop if the page cannot be trivially entered into the
3329                  * pmap.
3330                  */
3331                 if (((m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) ||
3332                     (m->flags & PG_FICTITIOUS) ||
3333                     ((m->flags & PG_SWAPPED) &&
3334                      (prot & VM_PROT_WRITE) &&
3335                      (fault_flags & VM_FAULT_DIRTY))) {
3336                         vm_page_wakeup(m);
3337                         break;
3338                 }
3339
3340                 /*
3341                  * Enter the page into the pmap.  The object might be held
3342                  * shared so we can't do any (serious) modifying operation
3343                  * on it.
3344                  */
3345                 if ((m->queue - m->pc) == PQ_CACHE)
3346                         vm_page_deactivate(m);
3347                 if (prot & VM_PROT_WRITE) {
3348                         vm_object_set_writeable_dirty(m->object);
3349                         vm_set_nosync(m, entry);
3350                         if (fault_flags & VM_FAULT_DIRTY) {
3351                                 vm_page_dirty(m);
3352                                 /* can't happeen due to conditional above */
3353                                 /* swap_pager_unswapped(m); */
3354                         }
3355                 }
3356                 pmap_enter(pmap, addr, m, prot, 0, entry);
3357                 mycpu->gd_cnt.v_vm_faults++;
3358                 if (curthread->td_lwp)
3359                         ++curthread->td_lwp->lwp_ru.ru_minflt;
3360                 vm_page_wakeup(m);
3361         }
3362 }