kernel - VM rework part 13 - Core pmap work, stabilize & optimize
[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 = 1;
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
169 /*
170  * Define here for debugging ioctls.  Note that these are globals, so
171  * they were cause a ton of cache line bouncing.  Only use for debugging
172  * purposes.
173  */
174 /*#define VM_FAULT_QUICK_DEBUG */
175 #ifdef VM_FAULT_QUICK_DEBUG
176 static long vm_fault_quick_success_count = 0;
177 SYSCTL_LONG(_vm, OID_AUTO, fault_quick_success_count, CTLFLAG_RW,
178                 &vm_fault_quick_success_count, 0, "");
179 static long vm_fault_quick_failure_count1 = 0;
180 SYSCTL_LONG(_vm, OID_AUTO, fault_quick_failure_count1, CTLFLAG_RW,
181                 &vm_fault_quick_failure_count1, 0, "");
182 static long vm_fault_quick_failure_count2 = 0;
183 SYSCTL_LONG(_vm, OID_AUTO, fault_quick_failure_count2, CTLFLAG_RW,
184                 &vm_fault_quick_failure_count2, 0, "");
185 static long vm_fault_quick_failure_count3 = 0;
186 SYSCTL_LONG(_vm, OID_AUTO, fault_quick_failure_count3, CTLFLAG_RW,
187                 &vm_fault_quick_failure_count3, 0, "");
188 static long vm_fault_quick_failure_count4 = 0;
189 SYSCTL_LONG(_vm, OID_AUTO, fault_quick_failure_count4, CTLFLAG_RW,
190                 &vm_fault_quick_failure_count4, 0, "");
191 #endif
192
193 static int vm_fault_quick(struct faultstate *fs, vm_pindex_t first_pindex,
194                         vm_prot_t fault_type);
195 static int vm_fault_object(struct faultstate *, vm_pindex_t, vm_prot_t, int);
196 static int vm_fault_vpagetable(struct faultstate *, vm_pindex_t *,
197                         vpte_t, int, int);
198 #if 0
199 static int vm_fault_additional_pages (vm_page_t, int, int, vm_page_t *, int *);
200 #endif
201 static void vm_set_nosync(vm_page_t m, vm_map_entry_t entry);
202 static void vm_prefault(pmap_t pmap, vm_offset_t addra,
203                         vm_map_entry_t entry, int prot, int fault_flags);
204 static void vm_prefault_quick(pmap_t pmap, vm_offset_t addra,
205                         vm_map_entry_t entry, int prot, int fault_flags);
206
207 static __inline void
208 release_page(struct faultstate *fs)
209 {
210         vm_page_deactivate(fs->m);
211         vm_page_wakeup(fs->m);
212         fs->m = NULL;
213 }
214
215 static __inline void
216 unlock_map(struct faultstate *fs)
217 {
218         if (fs->ba != fs->first_ba)
219                 vm_object_drop(fs->ba->object);
220         if (fs->first_ba && fs->first_ba_held == 1) {
221                 vm_object_drop(fs->first_ba->object);
222                 fs->first_ba_held = 0;
223                 fs->first_ba = NULL;
224         }
225         fs->ba = NULL;
226
227         /*
228          * NOTE: If lookup_still_valid == -1 the map is assumed to be locked
229          *       and caller expects it to remain locked atomically.
230          */
231         if (fs->lookup_still_valid == 1 && fs->map) {
232                 vm_map_lookup_done(fs->map, fs->entry, 0);
233                 fs->lookup_still_valid = 0;
234                 fs->entry = NULL;
235         }
236 }
237
238 /*
239  * Clean up after a successful call to vm_fault_object() so another call
240  * to vm_fault_object() can be made.
241  */
242 static void
243 cleanup_fault(struct faultstate *fs)
244 {
245         /*
246          * We allocated a junk page for a COW operation that did
247          * not occur, the page must be freed.
248          */
249         if (fs->ba != fs->first_ba) {
250                 KKASSERT(fs->first_shared == 0);
251
252                 /*
253                  * first_m could be completely valid and we got here
254                  * because of a PG_RAM, don't mistakenly free it!
255                  */
256                 if ((fs->first_m->valid & VM_PAGE_BITS_ALL) ==
257                     VM_PAGE_BITS_ALL) {
258                         vm_page_wakeup(fs->first_m);
259                 } else {
260                         vm_page_free(fs->first_m);
261                 }
262                 vm_object_pip_wakeup(fs->ba->object);
263                 fs->first_m = NULL;
264
265                 /*
266                  * Reset fs->ba (used by vm_fault_vpagetahble() without
267                  * calling unlock_map(), so we need a little duplication.
268                  */
269                 vm_object_drop(fs->ba->object);
270                 fs->ba = fs->first_ba;
271         }
272 }
273
274 static void
275 unlock_things(struct faultstate *fs)
276 {
277         cleanup_fault(fs);
278         unlock_map(fs); 
279         if (fs->vp != NULL) { 
280                 vput(fs->vp);
281                 fs->vp = NULL;
282         }
283 }
284
285 #if 0
286 /*
287  * Virtual copy tests.   Used by the fault code to determine if a
288  * page can be moved from an orphan vm_object into its shadow
289  * instead of copying its contents.
290  */
291 static __inline int
292 virtual_copy_test(struct faultstate *fs)
293 {
294         /*
295          * Must be holding exclusive locks
296          */
297         if (fs->first_shared || fs->shared || virtual_copy_enable == 0)
298                 return 0;
299
300         /*
301          * Map, if present, has not changed
302          */
303         if (fs->map && fs->map_generation != fs->map->timestamp)
304                 return 0;
305
306         /*
307          * No refs, except us
308          */
309         if (fs->ba->object->ref_count != 1)
310                 return 0;
311
312         /*
313          * No one else can look this object up
314          */
315         if (fs->ba->object->handle != NULL)
316                 return 0;
317
318         /*
319          * No other ways to look the object up
320          */
321         if (fs->ba->object->type != OBJT_DEFAULT &&
322             fs->ba->object->type != OBJT_SWAP)
323                 return 0;
324
325         /*
326          * We don't chase down the shadow chain
327          */
328         if (fs->ba != fs->first_ba->backing_ba)
329                 return 0;
330
331         return 1;
332 }
333
334 static __inline int
335 virtual_copy_ok(struct faultstate *fs)
336 {
337         if (virtual_copy_test(fs)) {
338                 /*
339                  * Grab the lock and re-test changeable items.
340                  */
341                 if (fs->lookup_still_valid == 0 && fs->map) {
342                         if (lockmgr(&fs->map->lock, LK_EXCLUSIVE|LK_NOWAIT))
343                                 return 0;
344                         fs->lookup_still_valid = 1;
345                         if (virtual_copy_test(fs)) {
346                                 fs->map_generation = ++fs->map->timestamp;
347                                 return 1;
348                         }
349                         fs->lookup_still_valid = 0;
350                         lockmgr(&fs->map->lock, LK_RELEASE);
351                 }
352         }
353         return 0;
354 }
355 #endif
356
357 /*
358  * TRYPAGER 
359  *
360  * Determine if the pager for the current object *might* contain the page.
361  *
362  * We only need to try the pager if this is not a default object (default
363  * objects are zero-fill and have no real pager), and if we are not taking
364  * a wiring fault or if the FS entry is wired.
365  */
366 #define TRYPAGER(fs)    \
367                 (fs->ba->object->type != OBJT_DEFAULT &&                \
368                 (((fs->fault_flags & VM_FAULT_WIRE_MASK) == 0) ||       \
369                  (fs->wflags & FW_WIRED)))
370
371 /*
372  * vm_fault:
373  *
374  * Handle a page fault occuring at the given address, requiring the given
375  * permissions, in the map specified.  If successful, the page is inserted
376  * into the associated physical map.
377  *
378  * NOTE: The given address should be truncated to the proper page address.
379  *
380  * KERN_SUCCESS is returned if the page fault is handled; otherwise,
381  * a standard error specifying why the fault is fatal is returned.
382  *
383  * The map in question must be referenced, and remains so.
384  * The caller may hold no locks.
385  * No other requirements.
386  */
387 int
388 vm_fault(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type, int fault_flags)
389 {
390         int result;
391         vm_pindex_t first_pindex;
392         struct faultstate fs;
393         struct lwp *lp;
394         struct proc *p;
395         thread_t td;
396         struct vm_map_ilock ilock;
397         int didilock;
398         int growstack;
399         int retry = 0;
400         int inherit_prot;
401
402         inherit_prot = fault_type & VM_PROT_NOSYNC;
403         fs.hardfault = 0;
404         fs.fault_flags = fault_flags;
405         fs.vp = NULL;
406         fs.shared = vm_shared_fault;
407         fs.first_shared = vm_shared_fault;
408         growstack = 1;
409
410         /*
411          * vm_map interactions
412          */
413         td = curthread;
414         if ((lp = td->td_lwp) != NULL)
415                 lp->lwp_flags |= LWP_PAGING;
416
417 RetryFault:
418         /*
419          * vm_fault_quick() can shortcut us.
420          */
421         fs.msoftonly = 0;
422         fs.first_ba_held = 0;
423
424         /*
425          * Find the vm_map_entry representing the backing store and resolve
426          * the top level object and page index.  This may have the side
427          * effect of executing a copy-on-write on the map entry,
428          * creating a shadow object, or splitting an anonymous entry for
429          * performance, but will not COW any actual VM pages.
430          *
431          * On success fs.map is left read-locked and various other fields 
432          * are initialized but not otherwise referenced or locked.
433          *
434          * NOTE!  vm_map_lookup will try to upgrade the fault_type to
435          *        VM_FAULT_WRITE if the map entry is a virtual page table
436          *        and also writable, so we can set the 'A'accessed bit in
437          *        the virtual page table entry.
438          */
439         fs.map = map;
440         result = vm_map_lookup(&fs.map, vaddr, fault_type,
441                                &fs.entry, &fs.first_ba,
442                                &first_pindex, &fs.first_prot, &fs.wflags);
443
444         /*
445          * If the lookup failed or the map protections are incompatible,
446          * the fault generally fails.
447          *
448          * The failure could be due to TDF_NOFAULT if vm_map_lookup()
449          * tried to do a COW fault.
450          *
451          * If the caller is trying to do a user wiring we have more work
452          * to do.
453          */
454         if (result != KERN_SUCCESS) {
455                 if (result == KERN_FAILURE_NOFAULT) {
456                         result = KERN_FAILURE;
457                         goto done;
458                 }
459                 if (result != KERN_PROTECTION_FAILURE ||
460                     (fs.fault_flags & VM_FAULT_WIRE_MASK) != VM_FAULT_USER_WIRE)
461                 {
462                         if (result == KERN_INVALID_ADDRESS && growstack &&
463                             map != &kernel_map && curproc != NULL) {
464                                 result = vm_map_growstack(map, vaddr);
465                                 if (result == KERN_SUCCESS) {
466                                         growstack = 0;
467                                         ++retry;
468                                         goto RetryFault;
469                                 }
470                                 result = KERN_FAILURE;
471                         }
472                         goto done;
473                 }
474
475                 /*
476                  * If we are user-wiring a r/w segment, and it is COW, then
477                  * we need to do the COW operation.  Note that we don't
478                  * currently COW RO sections now, because it is NOT desirable
479                  * to COW .text.  We simply keep .text from ever being COW'ed
480                  * and take the heat that one cannot debug wired .text sections.
481                  *
482                  * XXX Try to allow the above by specifying OVERRIDE_WRITE.
483                  */
484                 result = vm_map_lookup(&fs.map, vaddr,
485                                        VM_PROT_READ|VM_PROT_WRITE|
486                                         VM_PROT_OVERRIDE_WRITE,
487                                        &fs.entry, &fs.first_ba,
488                                        &first_pindex, &fs.first_prot,
489                                        &fs.wflags);
490                 if (result != KERN_SUCCESS) {
491                         /* could also be KERN_FAILURE_NOFAULT */
492                         result = KERN_FAILURE;
493                         goto done;
494                 }
495
496                 /*
497                  * If we don't COW now, on a user wire, the user will never
498                  * be able to write to the mapping.  If we don't make this
499                  * restriction, the bookkeeping would be nearly impossible.
500                  *
501                  * XXX We have a shared lock, this will have a MP race but
502                  * I don't see how it can hurt anything.
503                  */
504                 if ((fs.entry->protection & VM_PROT_WRITE) == 0) {
505                         atomic_clear_char(&fs.entry->max_protection,
506                                           VM_PROT_WRITE);
507                 }
508         }
509
510         /*
511          * fs.map is read-locked
512          *
513          * Misc checks.  Save the map generation number to detect races.
514          */
515         fs.lookup_still_valid = 1;
516         fs.first_m = NULL;
517         fs.ba = fs.first_ba;            /* so unlock_things() works */
518         fs.prot = fs.first_prot;        /* default (used by uksmap) */
519
520         if (fs.entry->eflags & (MAP_ENTRY_NOFAULT | MAP_ENTRY_KSTACK)) {
521                 if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
522                         panic("vm_fault: fault on nofault entry, addr: %p",
523                               (void *)vaddr);
524                 }
525                 if ((fs.entry->eflags & MAP_ENTRY_KSTACK) &&
526                     vaddr >= fs.entry->ba.start &&
527                     vaddr < fs.entry->ba.start + PAGE_SIZE) {
528                         panic("vm_fault: fault on stack guard, addr: %p",
529                               (void *)vaddr);
530                 }
531         }
532
533         /*
534          * A user-kernel shared map has no VM object and bypasses
535          * everything.  We execute the uksmap function with a temporary
536          * fictitious vm_page.  The address is directly mapped with no
537          * management.
538          */
539         if (fs.entry->maptype == VM_MAPTYPE_UKSMAP) {
540                 struct vm_page fakem;
541
542                 bzero(&fakem, sizeof(fakem));
543                 fakem.pindex = first_pindex;
544                 fakem.flags = PG_FICTITIOUS | PG_UNMANAGED;
545                 fakem.busy_count = PBUSY_LOCKED;
546                 fakem.valid = VM_PAGE_BITS_ALL;
547                 fakem.pat_mode = VM_MEMATTR_DEFAULT;
548                 if (fs.entry->ba.uksmap(fs.entry->aux.dev, &fakem)) {
549                         result = KERN_FAILURE;
550                         unlock_things(&fs);
551                         goto done2;
552                 }
553                 pmap_enter(fs.map->pmap, vaddr, &fakem, fs.prot | inherit_prot,
554                            (fs.wflags & FW_WIRED), fs.entry);
555                 goto done_success;
556         }
557
558         /*
559          * A system map entry may return a NULL object.  No object means
560          * no pager means an unrecoverable kernel fault.
561          */
562         if (fs.first_ba == NULL) {
563                 panic("vm_fault: unrecoverable fault at %p in entry %p",
564                         (void *)vaddr, fs.entry);
565         }
566
567         /*
568          * Fail here if not a trivial anonymous page fault and TDF_NOFAULT
569          * is set.
570          *
571          * Unfortunately a deadlock can occur if we are forced to page-in
572          * from swap, but diving all the way into the vm_pager_get_page()
573          * function to find out is too much.  Just check the object type.
574          *
575          * The deadlock is a CAM deadlock on a busy VM page when trying
576          * to finish an I/O if another process gets stuck in
577          * vop_helper_read_shortcut() due to a swap fault.
578          */
579         if ((td->td_flags & TDF_NOFAULT) &&
580             (retry ||
581              fs.first_ba->object->type == OBJT_VNODE ||
582              fs.first_ba->object->type == OBJT_SWAP ||
583              fs.first_ba->backing_ba)) {
584                 result = KERN_FAILURE;
585                 unlock_things(&fs);
586                 goto done2;
587         }
588
589         /*
590          * If the entry is wired we cannot change the page protection.
591          */
592         if (fs.wflags & FW_WIRED)
593                 fault_type = fs.first_prot;
594
595         /*
596          * We generally want to avoid unnecessary exclusive modes on backing
597          * and terminal objects because this can seriously interfere with
598          * heavily fork()'d processes (particularly /bin/sh scripts).
599          *
600          * However, we also want to avoid unnecessary retries due to needed
601          * shared->exclusive promotion for common faults.  Exclusive mode is
602          * always needed if any page insertion, rename, or free occurs in an
603          * object (and also indirectly if any I/O is done).
604          *
605          * The main issue here is going to be fs.first_shared.  If the
606          * first_object has a backing object which isn't shadowed and the
607          * process is single-threaded we might as well use an exclusive
608          * lock/chain right off the bat.
609          */
610 #if 0
611         /* WORK IN PROGRESS, CODE REMOVED */
612         if (fs.first_shared && fs.first_object->backing_object &&
613             LIST_EMPTY(&fs.first_object->shadow_head) &&
614             td->td_proc && td->td_proc->p_nthreads == 1) {
615                 fs.first_shared = 0;
616         }
617 #endif
618
619         /*
620          * VM_FAULT_UNSWAP - swap_pager_unswapped() needs an exclusive object
621          * VM_FAULT_DIRTY  - may require swap_pager_unswapped() later, but
622          *                   we can try shared first.
623          */
624         if (fault_flags & VM_FAULT_UNSWAP)
625                 fs.first_shared = 0;
626
627         /*
628          * Try to shortcut the entire mess and run the fault lockless.
629          */
630         if (vm_fault_quick_enable &&
631             vm_fault_quick(&fs, first_pindex, fault_type) == KERN_SUCCESS) {
632                 didilock = 0;
633                 fault_flags &= ~VM_FAULT_BURST;
634                 goto success;
635         }
636
637         /*
638          * Exclusive heuristic (alloc page vs page exists)
639          */
640         if (fs.first_ba->flags & VM_MAP_BACK_EXCL_HEUR)
641                 fs.first_shared = 0;
642
643         /*
644          * Obtain a top-level object lock, shared or exclusive depending
645          * on fs.first_shared.  If a shared lock winds up being insufficient
646          * we will retry with an exclusive lock.
647          *
648          * The vnode pager lock is always shared.
649          */
650         if (fs.first_shared)
651                 vm_object_hold_shared(fs.first_ba->object);
652         else
653                 vm_object_hold(fs.first_ba->object);
654         if (fs.vp == NULL)
655                 fs.vp = vnode_pager_lock(fs.first_ba);
656         fs.first_ba_held = 1;
657
658         /*
659          * The page we want is at (first_object, first_pindex), but if the
660          * vm_map_entry is VM_MAPTYPE_VPAGETABLE we have to traverse the
661          * page table to figure out the actual pindex.
662          *
663          * NOTE!  DEVELOPMENT IN PROGRESS, THIS IS AN INITIAL IMPLEMENTATION
664          * ONLY
665          */
666         didilock = 0;
667         if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
668                 vm_map_interlock(fs.map, &ilock, vaddr, vaddr + PAGE_SIZE);
669                 didilock = 1;
670                 result = vm_fault_vpagetable(&fs, &first_pindex,
671                                              fs.entry->aux.master_pde,
672                                              fault_type, 1);
673                 if (result == KERN_TRY_AGAIN) {
674                         vm_map_deinterlock(fs.map, &ilock);
675                         ++retry;
676                         goto RetryFault;
677                 }
678                 if (result != KERN_SUCCESS) {
679                         vm_map_deinterlock(fs.map, &ilock);
680                         goto done;
681                 }
682         }
683
684         /*
685          * Now we have the actual (object, pindex), fault in the page.  If
686          * vm_fault_object() fails it will unlock and deallocate the FS
687          * data.   If it succeeds everything remains locked and fs->ba->object
688          * will have an additional PIP count if fs->ba != fs->first_ba.
689          *
690          * vm_fault_object will set fs->prot for the pmap operation.  It is
691          * allowed to set VM_PROT_WRITE if fault_type == VM_PROT_READ if the
692          * page can be safely written.  However, it will force a read-only
693          * mapping for a read fault if the memory is managed by a virtual
694          * page table.
695          *
696          * If the fault code uses the shared object lock shortcut
697          * we must not try to burst (we can't allocate VM pages).
698          */
699         result = vm_fault_object(&fs, first_pindex, fault_type, 1);
700
701         if (debug_fault > 0) {
702                 --debug_fault;
703                 kprintf("VM_FAULT result %d addr=%jx type=%02x flags=%02x "
704                         "fs.m=%p fs.prot=%02x fs.wflags=%02x fs.entry=%p\n",
705                         result, (intmax_t)vaddr, fault_type, fault_flags,
706                         fs.m, fs.prot, fs.wflags, fs.entry);
707         }
708
709         if (result == KERN_TRY_AGAIN) {
710                 if (didilock)
711                         vm_map_deinterlock(fs.map, &ilock);
712                 ++retry;
713                 goto RetryFault;
714         }
715         if (result != KERN_SUCCESS) {
716                 if (didilock)
717                         vm_map_deinterlock(fs.map, &ilock);
718                 goto done;
719         }
720
721 success:
722         /*
723          * On success vm_fault_object() does not unlock or deallocate, and fs.m
724          * will contain a busied page.  It does drop fs->ba if appropriate.
725          *
726          * Enter the page into the pmap and do pmap-related adjustments.
727          *
728          * WARNING! Soft-busied fs.m's can only be manipulated in limited
729          *          ways.
730          */
731         KKASSERT(fs.lookup_still_valid != 0);
732         vm_page_flag_set(fs.m, PG_REFERENCED);
733         pmap_enter(fs.map->pmap, vaddr, fs.m, fs.prot | inherit_prot,
734                    fs.wflags & FW_WIRED, fs.entry);
735
736         if (didilock)
737                 vm_map_deinterlock(fs.map, &ilock);
738
739         /*
740          * If the page is not wired down, then put it where the pageout daemon
741          * can find it.
742          *
743          * NOTE: We cannot safely wire, unwire, or adjust queues for a
744          *       soft-busied page.
745          */
746         if (fs.msoftonly) {
747                 KKASSERT(fs.m->busy_count & PBUSY_MASK);
748                 KKASSERT((fs.fault_flags & VM_FAULT_WIRE_MASK) == 0);
749                 vm_page_sbusy_drop(fs.m);
750         } else {
751                 if (fs.fault_flags & VM_FAULT_WIRE_MASK) {
752                         if (fs.wflags & FW_WIRED)
753                                 vm_page_wire(fs.m);
754                         else
755                                 vm_page_unwire(fs.m, 1);
756                 } else {
757                         vm_page_activate(fs.m);
758                 }
759                 KKASSERT(fs.m->busy_count & PBUSY_LOCKED);
760                 vm_page_wakeup(fs.m);
761         }
762
763         /*
764          * Burst in a few more pages if possible.  The fs.map should still
765          * be locked.  To avoid interlocking against a vnode->getblk
766          * operation we had to be sure to unbusy our primary vm_page above
767          * first.
768          *
769          * A normal burst can continue down backing store, only execute
770          * if we are holding an exclusive lock, otherwise the exclusive
771          * locks the burst code gets might cause excessive SMP collisions.
772          *
773          * A quick burst can be utilized when there is no backing object
774          * (i.e. a shared file mmap).
775          */
776         if ((fault_flags & VM_FAULT_BURST) &&
777             (fs.fault_flags & VM_FAULT_WIRE_MASK) == 0 &&
778             (fs.wflags & FW_WIRED) == 0) {
779                 if (fs.first_shared == 0 && fs.shared == 0) {
780                         vm_prefault(fs.map->pmap, vaddr,
781                                     fs.entry, fs.prot, fault_flags);
782                 } else {
783                         vm_prefault_quick(fs.map->pmap, vaddr,
784                                           fs.entry, fs.prot, fault_flags);
785                 }
786         }
787
788 done_success:
789         mycpu->gd_cnt.v_vm_faults++;
790         if (td->td_lwp)
791                 ++td->td_lwp->lwp_ru.ru_minflt;
792
793         /*
794          * Unlock everything, and return
795          */
796         unlock_things(&fs);
797
798         if (td->td_lwp) {
799                 if (fs.hardfault) {
800                         td->td_lwp->lwp_ru.ru_majflt++;
801                 } else {
802                         td->td_lwp->lwp_ru.ru_minflt++;
803                 }
804         }
805
806         /*vm_object_deallocate(fs.first_ba->object);*/
807         /*fs.m = NULL; */
808
809         result = KERN_SUCCESS;
810 done:
811         if (fs.first_ba && fs.first_ba->object && fs.first_ba_held == 1) {
812                 vm_object_drop(fs.first_ba->object);
813                 fs.first_ba_held = 0;
814         }
815 done2:
816         if (lp)
817                 lp->lwp_flags &= ~LWP_PAGING;
818
819 #if !defined(NO_SWAPPING)
820         /*
821          * Check the process RSS limit and force deactivation and
822          * (asynchronous) paging if necessary.  This is a complex operation,
823          * only do it for direct user-mode faults, for now.
824          *
825          * To reduce overhead implement approximately a ~16MB hysteresis.
826          */
827         p = td->td_proc;
828         if ((fault_flags & VM_FAULT_USERMODE) && lp &&
829             p->p_limit && map->pmap && vm_pageout_memuse_mode >= 1 &&
830             map != &kernel_map) {
831                 vm_pindex_t limit;
832                 vm_pindex_t size;
833
834                 limit = OFF_TO_IDX(qmin(p->p_rlimit[RLIMIT_RSS].rlim_cur,
835                                         p->p_rlimit[RLIMIT_RSS].rlim_max));
836                 size = pmap_resident_tlnw_count(map->pmap);
837                 if (limit >= 0 && size > 4096 && size - 4096 >= limit) {
838                         vm_pageout_map_deactivate_pages(map, limit);
839                 }
840         }
841 #endif
842
843         if (result != KERN_SUCCESS && debug_fault < 0) {
844                 kprintf("VM_FAULT %d:%d (%s) result %d "
845                         "addr=%jx type=%02x flags=%02x "
846                         "fs.m=%p fs.prot=%02x fs.wflags=%02x fs.entry=%p\n",
847                         (curthread->td_proc ? curthread->td_proc->p_pid : -1),
848                         (curthread->td_lwp ? curthread->td_lwp->lwp_tid : -1),
849                         curthread->td_comm,
850                         result,
851                         (intmax_t)vaddr, fault_type, fault_flags,
852                         fs.m, fs.prot, fs.wflags, fs.entry);
853                 while (debug_fault < 0 && (debug_fault & 1))
854                         tsleep(&debug_fault, 0, "DEBUG", hz);
855         }
856
857         return (result);
858 }
859
860 /*
861  * Attempt a lockless vm_fault() shortcut.  The stars have to align for this
862  * to work.  But if it does we can get our page only soft-busied and not
863  * have to touch the vm_object or vnode locks at all.
864  */
865 static
866 int
867 vm_fault_quick(struct faultstate *fs, vm_pindex_t first_pindex,
868                vm_prot_t fault_type)
869 {
870         vm_page_t m;
871         vm_object_t obj;        /* NOT LOCKED */
872
873         /*
874          * Don't waste time if the object is only being used by one vm_map.
875          */
876         obj = fs->first_ba->object;
877         if (obj->flags & OBJ_ONEMAPPING)
878                 return KERN_FAILURE;
879
880         /*
881          * This will try to wire/unwire a page, which can't be done with
882          * a soft-busied page.
883          */
884         if (fs->fault_flags & VM_FAULT_WIRE_MASK)
885                 return KERN_FAILURE;
886
887         /*
888          * Ick, can't handle this
889          */
890         if (fs->entry->maptype == VM_MAPTYPE_VPAGETABLE) {
891 #ifdef VM_FAULT_QUICK_DEBUG
892                 ++vm_fault_quick_failure_count1;
893 #endif
894                 return KERN_FAILURE;
895         }
896
897         /*
898          * Ok, try to get the vm_page quickly via the hash table.  The
899          * page will be soft-busied on success (NOT hard-busied).
900          */
901         m = vm_page_hash_get(obj, first_pindex);
902         if (m == NULL) {
903 #ifdef VM_FAULT_QUICK_DEBUG
904                 ++vm_fault_quick_failure_count2;
905 #endif
906                 return KERN_FAILURE;
907         }
908         if ((obj->flags & OBJ_DEAD) ||
909             m->valid != VM_PAGE_BITS_ALL ||
910             m->queue - m->pc == PQ_CACHE ||
911             (m->flags & PG_SWAPPED)) {
912                 vm_page_sbusy_drop(m);
913 #ifdef VM_FAULT_QUICK_DEBUG
914                 ++vm_fault_quick_failure_count3;
915 #endif
916                 return KERN_FAILURE;
917         }
918
919         /*
920          * The page is already fully valid, ACTIVE, and is not PG_SWAPPED.
921          *
922          * Don't map the page writable when emulating the dirty bit, a
923          * fault must be taken for proper emulation (vkernel).
924          */
925         if (curthread->td_lwp && curthread->td_lwp->lwp_vmspace &&
926             pmap_emulate_ad_bits(&curthread->td_lwp->lwp_vmspace->vm_pmap)) {
927                 if ((fault_type & VM_PROT_WRITE) == 0)
928                         fs->prot &= ~VM_PROT_WRITE;
929         }
930
931         /*
932          * If this is a write fault the object and the page must already
933          * be writable.  Since we don't hold an object lock and only a
934          * soft-busy on the page, we cannot manipulate the object or
935          * the page state (other than the page queue).
936          */
937         if (fs->prot & VM_PROT_WRITE) {
938                 if ((obj->flags & (OBJ_WRITEABLE | OBJ_MIGHTBEDIRTY)) !=
939                     (OBJ_WRITEABLE | OBJ_MIGHTBEDIRTY) ||
940                     m->dirty != VM_PAGE_BITS_ALL) {
941                         vm_page_sbusy_drop(m);
942 #ifdef VM_FAULT_QUICK_DEBUG
943                         ++vm_fault_quick_failure_count4;
944 #endif
945                         return KERN_FAILURE;
946                 }
947                 vm_set_nosync(m, fs->entry);
948         }
949
950         /*
951          * Even though we are only soft-busied we can still move pages
952          * around in the normal queue(s).  The soft-busy prevents the
953          * page from being removed from the object, etc (normal operation).
954          *
955          * However, in this fast path it is excessively important to avoid
956          * any hard locks, so we use a special passive version of activate.
957          */
958         vm_page_soft_activate(m);
959         fs->m = m;
960         fs->msoftonly = 1;
961 #ifdef VM_FAULT_QUICK_DEBUG
962         ++vm_fault_quick_success_count;
963 #endif
964
965         return KERN_SUCCESS;
966 }
967
968 /*
969  * Fault in the specified virtual address in the current process map, 
970  * returning a held VM page or NULL.  See vm_fault_page() for more 
971  * information.
972  *
973  * No requirements.
974  */
975 vm_page_t
976 vm_fault_page_quick(vm_offset_t va, vm_prot_t fault_type,
977                     int *errorp, int *busyp)
978 {
979         struct lwp *lp = curthread->td_lwp;
980         vm_page_t m;
981
982         m = vm_fault_page(&lp->lwp_vmspace->vm_map, va, 
983                           fault_type, VM_FAULT_NORMAL,
984                           errorp, busyp);
985         return(m);
986 }
987
988 /*
989  * Fault in the specified virtual address in the specified map, doing all
990  * necessary manipulation of the object store and all necessary I/O.  Return
991  * a held VM page or NULL, and set *errorp.  The related pmap is not
992  * updated.
993  *
994  * If busyp is not NULL then *busyp will be set to TRUE if this routine
995  * decides to return a busied page (aka VM_PROT_WRITE), or FALSE if it
996  * does not (VM_PROT_WRITE not specified or busyp is NULL).  If busyp is
997  * NULL the returned page is only held.
998  *
999  * If the caller has no intention of writing to the page's contents, busyp
1000  * can be passed as NULL along with VM_PROT_WRITE to force a COW operation
1001  * without busying the page.
1002  *
1003  * The returned page will also be marked PG_REFERENCED.
1004  *
1005  * If the page cannot be faulted writable and VM_PROT_WRITE was specified, an
1006  * error will be returned.
1007  *
1008  * No requirements.
1009  */
1010 vm_page_t
1011 vm_fault_page(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
1012               int fault_flags, int *errorp, int *busyp)
1013 {
1014         vm_pindex_t first_pindex;
1015         struct faultstate fs;
1016         int result;
1017         int retry;
1018         int growstack;
1019         int didcow;
1020         vm_prot_t orig_fault_type = fault_type;
1021
1022         retry = 0;
1023         didcow = 0;
1024         fs.hardfault = 0;
1025         fs.fault_flags = fault_flags;
1026         KKASSERT((fault_flags & VM_FAULT_WIRE_MASK) == 0);
1027
1028         /*
1029          * Dive the pmap (concurrency possible).  If we find the
1030          * appropriate page we can terminate early and quickly.
1031          *
1032          * This works great for normal programs but will always return
1033          * NULL for host lookups of vkernel maps in VMM mode.
1034          *
1035          * NOTE: pmap_fault_page_quick() might not busy the page.  If
1036          *       VM_PROT_WRITE is set in fault_type and pmap_fault_page_quick()
1037          *       returns non-NULL, it will safely dirty the returned vm_page_t
1038          *       for us.  We cannot safely dirty it here (it might not be
1039          *       busy).
1040          */
1041         fs.m = pmap_fault_page_quick(map->pmap, vaddr, fault_type, busyp);
1042         if (fs.m) {
1043                 *errorp = 0;
1044                 return(fs.m);
1045         }
1046
1047         /*
1048          * Otherwise take a concurrency hit and do a formal page
1049          * fault.
1050          */
1051         fs.vp = NULL;
1052         fs.shared = vm_shared_fault;
1053         fs.first_shared = vm_shared_fault;
1054         fs.msoftonly = 0;
1055         growstack = 1;
1056
1057         /*
1058          * VM_FAULT_UNSWAP - swap_pager_unswapped() needs an exclusive object
1059          * VM_FAULT_DIRTY  - may require swap_pager_unswapped() later, but
1060          *                   we can try shared first.
1061          */
1062         if (fault_flags & VM_FAULT_UNSWAP) {
1063                 fs.first_shared = 0;
1064         }
1065
1066 RetryFault:
1067         /*
1068          * Find the vm_map_entry representing the backing store and resolve
1069          * the top level object and page index.  This may have the side
1070          * effect of executing a copy-on-write on the map entry and/or
1071          * creating a shadow object, but will not COW any actual VM pages.
1072          *
1073          * On success fs.map is left read-locked and various other fields 
1074          * are initialized but not otherwise referenced or locked.
1075          *
1076          * NOTE!  vm_map_lookup will upgrade the fault_type to VM_FAULT_WRITE
1077          *        if the map entry is a virtual page table and also writable,
1078          *        so we can set the 'A'accessed bit in the virtual page table
1079          *        entry.
1080          */
1081         fs.map = map;
1082         fs.first_ba_held = 0;
1083         result = vm_map_lookup(&fs.map, vaddr, fault_type,
1084                                &fs.entry, &fs.first_ba,
1085                                &first_pindex, &fs.first_prot, &fs.wflags);
1086
1087         if (result != KERN_SUCCESS) {
1088                 if (result == KERN_FAILURE_NOFAULT) {
1089                         *errorp = KERN_FAILURE;
1090                         fs.m = NULL;
1091                         goto done;
1092                 }
1093                 if (result != KERN_PROTECTION_FAILURE ||
1094                     (fs.fault_flags & VM_FAULT_WIRE_MASK) != VM_FAULT_USER_WIRE)
1095                 {
1096                         if (result == KERN_INVALID_ADDRESS && growstack &&
1097                             map != &kernel_map && curproc != NULL) {
1098                                 result = vm_map_growstack(map, vaddr);
1099                                 if (result == KERN_SUCCESS) {
1100                                         growstack = 0;
1101                                         ++retry;
1102                                         goto RetryFault;
1103                                 }
1104                                 result = KERN_FAILURE;
1105                         }
1106                         fs.m = NULL;
1107                         *errorp = result;
1108                         goto done;
1109                 }
1110
1111                 /*
1112                  * If we are user-wiring a r/w segment, and it is COW, then
1113                  * we need to do the COW operation.  Note that we don't
1114                  * currently COW RO sections now, because it is NOT desirable
1115                  * to COW .text.  We simply keep .text from ever being COW'ed
1116                  * and take the heat that one cannot debug wired .text sections.
1117                  */
1118                 result = vm_map_lookup(&fs.map, vaddr,
1119                                        VM_PROT_READ|VM_PROT_WRITE|
1120                                         VM_PROT_OVERRIDE_WRITE,
1121                                        &fs.entry, &fs.first_ba,
1122                                        &first_pindex, &fs.first_prot,
1123                                        &fs.wflags);
1124                 if (result != KERN_SUCCESS) {
1125                         /* could also be KERN_FAILURE_NOFAULT */
1126                         *errorp = KERN_FAILURE;
1127                         fs.m = NULL;
1128                         goto done;
1129                 }
1130
1131                 /*
1132                  * If we don't COW now, on a user wire, the user will never
1133                  * be able to write to the mapping.  If we don't make this
1134                  * restriction, the bookkeeping would be nearly impossible.
1135                  *
1136                  * XXX We have a shared lock, this will have a MP race but
1137                  * I don't see how it can hurt anything.
1138                  */
1139                 if ((fs.entry->protection & VM_PROT_WRITE) == 0) {
1140                         atomic_clear_char(&fs.entry->max_protection,
1141                                           VM_PROT_WRITE);
1142                 }
1143         }
1144
1145         /*
1146          * fs.map is read-locked
1147          *
1148          * Misc checks.  Save the map generation number to detect races.
1149          */
1150         fs.lookup_still_valid = 1;
1151         fs.first_m = NULL;
1152         fs.ba = fs.first_ba;
1153
1154         if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
1155                 panic("vm_fault: fault on nofault entry, addr: %lx",
1156                     (u_long)vaddr);
1157         }
1158
1159         /*
1160          * A user-kernel shared map has no VM object and bypasses
1161          * everything.  We execute the uksmap function with a temporary
1162          * fictitious vm_page.  The address is directly mapped with no
1163          * management.
1164          */
1165         if (fs.entry->maptype == VM_MAPTYPE_UKSMAP) {
1166                 struct vm_page fakem;
1167
1168                 bzero(&fakem, sizeof(fakem));
1169                 fakem.pindex = first_pindex;
1170                 fakem.flags = PG_FICTITIOUS | PG_UNMANAGED;
1171                 fakem.busy_count = PBUSY_LOCKED;
1172                 fakem.valid = VM_PAGE_BITS_ALL;
1173                 fakem.pat_mode = VM_MEMATTR_DEFAULT;
1174                 if (fs.entry->ba.uksmap(fs.entry->aux.dev, &fakem)) {
1175                         *errorp = KERN_FAILURE;
1176                         fs.m = NULL;
1177                         unlock_things(&fs);
1178                         goto done2;
1179                 }
1180                 fs.m = PHYS_TO_VM_PAGE(fakem.phys_addr);
1181                 vm_page_hold(fs.m);
1182                 if (busyp)
1183                         *busyp = 0;     /* don't need to busy R or W */
1184                 unlock_things(&fs);
1185                 *errorp = 0;
1186                 goto done;
1187         }
1188
1189
1190         /*
1191          * A system map entry may return a NULL object.  No object means
1192          * no pager means an unrecoverable kernel fault.
1193          */
1194         if (fs.first_ba == NULL) {
1195                 panic("vm_fault: unrecoverable fault at %p in entry %p",
1196                         (void *)vaddr, fs.entry);
1197         }
1198
1199         /*
1200          * Fail here if not a trivial anonymous page fault and TDF_NOFAULT
1201          * is set.
1202          *
1203          * Unfortunately a deadlock can occur if we are forced to page-in
1204          * from swap, but diving all the way into the vm_pager_get_page()
1205          * function to find out is too much.  Just check the object type.
1206          */
1207         if ((curthread->td_flags & TDF_NOFAULT) &&
1208             (retry ||
1209              fs.first_ba->object->type == OBJT_VNODE ||
1210              fs.first_ba->object->type == OBJT_SWAP ||
1211              fs.first_ba->backing_ba)) {
1212                 *errorp = KERN_FAILURE;
1213                 unlock_things(&fs);
1214                 fs.m = NULL;
1215                 goto done2;
1216         }
1217
1218         /*
1219          * If the entry is wired we cannot change the page protection.
1220          */
1221         if (fs.wflags & FW_WIRED)
1222                 fault_type = fs.first_prot;
1223
1224         /*
1225          * Make a reference to this object to prevent its disposal while we
1226          * are messing with it.  Once we have the reference, the map is free
1227          * to be diddled.  Since objects reference their shadows (and copies),
1228          * they will stay around as well.
1229          *
1230          * The reference should also prevent an unexpected collapse of the
1231          * parent that might move pages from the current object into the
1232          * parent unexpectedly, resulting in corruption.
1233          *
1234          * Bump the paging-in-progress count to prevent size changes (e.g.
1235          * truncation operations) during I/O.  This must be done after
1236          * obtaining the vnode lock in order to avoid possible deadlocks.
1237          */
1238         if (fs.first_ba->flags & VM_MAP_BACK_EXCL_HEUR)
1239                 fs.first_shared = 0;
1240
1241         if (fs.first_shared)
1242                 vm_object_hold_shared(fs.first_ba->object);
1243         else
1244                 vm_object_hold(fs.first_ba->object);
1245         fs.first_ba_held = 1;
1246         if (fs.vp == NULL)
1247                 fs.vp = vnode_pager_lock(fs.first_ba);  /* shared */
1248
1249         /*
1250          * The page we want is at (first_object, first_pindex), but if the
1251          * vm_map_entry is VM_MAPTYPE_VPAGETABLE we have to traverse the
1252          * page table to figure out the actual pindex.
1253          *
1254          * NOTE!  DEVELOPMENT IN PROGRESS, THIS IS AN INITIAL IMPLEMENTATION
1255          * ONLY
1256          */
1257         if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
1258                 result = vm_fault_vpagetable(&fs, &first_pindex,
1259                                              fs.entry->aux.master_pde,
1260                                              fault_type, 1);
1261                 if (result == KERN_TRY_AGAIN) {
1262                         ++retry;
1263                         goto RetryFault;
1264                 }
1265                 if (result != KERN_SUCCESS) {
1266                         *errorp = result;
1267                         fs.m = NULL;
1268                         goto done;
1269                 }
1270         }
1271
1272         /*
1273          * Now we have the actual (object, pindex), fault in the page.  If
1274          * vm_fault_object() fails it will unlock and deallocate the FS
1275          * data.   If it succeeds everything remains locked and fs->ba->object
1276          * will have an additinal PIP count if fs->ba != fs->first_ba.
1277          */
1278         fs.m = NULL;
1279         result = vm_fault_object(&fs, first_pindex, fault_type, 1);
1280
1281         if (result == KERN_TRY_AGAIN) {
1282                 KKASSERT(fs.first_ba_held == 0);
1283                 ++retry;
1284                 didcow |= fs.wflags & FW_DIDCOW;
1285                 goto RetryFault;
1286         }
1287         if (result != KERN_SUCCESS) {
1288                 *errorp = result;
1289                 fs.m = NULL;
1290                 goto done;
1291         }
1292
1293         if ((orig_fault_type & VM_PROT_WRITE) &&
1294             (fs.prot & VM_PROT_WRITE) == 0) {
1295                 *errorp = KERN_PROTECTION_FAILURE;
1296                 unlock_things(&fs);
1297                 fs.m = NULL;
1298                 goto done;
1299         }
1300
1301         /*
1302          * Generally speaking we don't want to update the pmap because
1303          * this routine can be called many times for situations that do
1304          * not require updating the pmap, not to mention the page might
1305          * already be in the pmap.
1306          *
1307          * However, if our vm_map_lookup() results in a COW, we need to
1308          * at least remove the pte from the pmap to guarantee proper
1309          * visibility of modifications made to the process.  For example,
1310          * modifications made by vkernel uiocopy/related routines and
1311          * modifications made by ptrace().
1312          */
1313         vm_page_flag_set(fs.m, PG_REFERENCED);
1314 #if 0
1315         pmap_enter(fs.map->pmap, vaddr, fs.m, fs.prot,
1316                    fs.wflags & FW_WIRED, NULL);
1317         mycpu->gd_cnt.v_vm_faults++;
1318         if (curthread->td_lwp)
1319                 ++curthread->td_lwp->lwp_ru.ru_minflt;
1320 #endif
1321         if ((fs.wflags | didcow) | FW_DIDCOW) {
1322                 pmap_remove(fs.map->pmap,
1323                             vaddr & ~PAGE_MASK,
1324                             (vaddr & ~PAGE_MASK) + PAGE_SIZE);
1325         }
1326
1327         /*
1328          * On success vm_fault_object() does not unlock or deallocate, and fs.m
1329          * will contain a busied page.  So we must unlock here after having
1330          * messed with the pmap.
1331          */
1332         unlock_things(&fs);
1333
1334         /*
1335          * Return a held page.  We are not doing any pmap manipulation so do
1336          * not set PG_MAPPED.  However, adjust the page flags according to
1337          * the fault type because the caller may not use a managed pmapping
1338          * (so we don't want to lose the fact that the page will be dirtied
1339          * if a write fault was specified).
1340          */
1341         if (fault_type & VM_PROT_WRITE)
1342                 vm_page_dirty(fs.m);
1343         vm_page_activate(fs.m);
1344
1345         if (curthread->td_lwp) {
1346                 if (fs.hardfault) {
1347                         curthread->td_lwp->lwp_ru.ru_majflt++;
1348                 } else {
1349                         curthread->td_lwp->lwp_ru.ru_minflt++;
1350                 }
1351         }
1352
1353         /*
1354          * Unlock everything, and return the held or busied page.
1355          */
1356         if (busyp) {
1357                 if (fault_type & VM_PROT_WRITE) {
1358                         vm_page_dirty(fs.m);
1359                         *busyp = 1;
1360                 } else {
1361                         *busyp = 0;
1362                         vm_page_hold(fs.m);
1363                         vm_page_wakeup(fs.m);
1364                 }
1365         } else {
1366                 vm_page_hold(fs.m);
1367                 vm_page_wakeup(fs.m);
1368         }
1369         /*vm_object_deallocate(fs.first_ba->object);*/
1370         *errorp = 0;
1371
1372 done:
1373         KKASSERT(fs.first_ba_held == 0);
1374 done2:
1375         return(fs.m);
1376 }
1377
1378 /*
1379  * Fault in the specified (object,offset), dirty the returned page as
1380  * needed.  If the requested fault_type cannot be done NULL and an
1381  * error is returned.
1382  *
1383  * A held (but not busied) page is returned.
1384  *
1385  * The passed in object must be held as specified by the shared
1386  * argument.
1387  */
1388 vm_page_t
1389 vm_fault_object_page(vm_object_t object, vm_ooffset_t offset,
1390                      vm_prot_t fault_type, int fault_flags,
1391                      int *sharedp, int *errorp)
1392 {
1393         int result;
1394         vm_pindex_t first_pindex;
1395         struct faultstate fs;
1396         struct vm_map_entry entry;
1397
1398         /*
1399          * Since we aren't actually faulting the page into a
1400          * pmap we can just fake the entry.ba.
1401          */
1402         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1403         bzero(&entry, sizeof(entry));
1404         entry.maptype = VM_MAPTYPE_NORMAL;
1405         entry.protection = entry.max_protection = fault_type;
1406         entry.ba.backing_ba = NULL;
1407         entry.ba.object = object;
1408         entry.ba.offset = 0;
1409
1410         fs.hardfault = 0;
1411         fs.fault_flags = fault_flags;
1412         fs.map = NULL;
1413         fs.shared = vm_shared_fault;
1414         fs.first_shared = *sharedp;
1415         fs.msoftonly = 0;
1416         fs.vp = NULL;
1417         fs.first_ba_held = -1;  /* object held across call, prevent drop */
1418         KKASSERT((fault_flags & VM_FAULT_WIRE_MASK) == 0);
1419
1420         /*
1421          * VM_FAULT_UNSWAP - swap_pager_unswapped() needs an exclusive object
1422          * VM_FAULT_DIRTY  - may require swap_pager_unswapped() later, but
1423          *                   we can try shared first.
1424          */
1425         if (fs.first_shared && (fault_flags & VM_FAULT_UNSWAP)) {
1426                 fs.first_shared = 0;
1427                 vm_object_upgrade(object);
1428         }
1429
1430         /*
1431          * Retry loop as needed (typically for shared->exclusive transitions)
1432          */
1433 RetryFault:
1434         *sharedp = fs.first_shared;
1435         first_pindex = OFF_TO_IDX(offset);
1436         fs.first_ba = &entry.ba;
1437         fs.ba = fs.first_ba;
1438         fs.entry = &entry;
1439         fs.first_prot = fault_type;
1440         fs.wflags = 0;
1441
1442         /*
1443          * Make a reference to this object to prevent its disposal while we
1444          * are messing with it.  Once we have the reference, the map is free
1445          * to be diddled.  Since objects reference their shadows (and copies),
1446          * they will stay around as well.
1447          *
1448          * The reference should also prevent an unexpected collapse of the
1449          * parent that might move pages from the current object into the
1450          * parent unexpectedly, resulting in corruption.
1451          *
1452          * Bump the paging-in-progress count to prevent size changes (e.g.
1453          * truncation operations) during I/O.  This must be done after
1454          * obtaining the vnode lock in order to avoid possible deadlocks.
1455          */
1456         if (fs.vp == NULL)
1457                 fs.vp = vnode_pager_lock(fs.first_ba);
1458
1459         fs.lookup_still_valid = 1;
1460         fs.first_m = NULL;
1461
1462 #if 0
1463         /* XXX future - ability to operate on VM object using vpagetable */
1464         if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
1465                 result = vm_fault_vpagetable(&fs, &first_pindex,
1466                                              fs.entry->aux.master_pde,
1467                                              fault_type, 0);
1468                 if (result == KERN_TRY_AGAIN) {
1469                         if (fs.first_shared == 0 && *sharedp)
1470                                 vm_object_upgrade(object);
1471                         goto RetryFault;
1472                 }
1473                 if (result != KERN_SUCCESS) {
1474                         *errorp = result;
1475                         return (NULL);
1476                 }
1477         }
1478 #endif
1479
1480         /*
1481          * Now we have the actual (object, pindex), fault in the page.  If
1482          * vm_fault_object() fails it will unlock and deallocate the FS
1483          * data.   If it succeeds everything remains locked and fs->ba->object
1484          * will have an additinal PIP count if fs->ba != fs->first_ba.
1485          *
1486          * On KERN_TRY_AGAIN vm_fault_object() leaves fs.first_ba intact.
1487          * We may have to upgrade its lock to handle the requested fault.
1488          */
1489         result = vm_fault_object(&fs, first_pindex, fault_type, 0);
1490
1491         if (result == KERN_TRY_AGAIN) {
1492                 if (fs.first_shared == 0 && *sharedp)
1493                         vm_object_upgrade(object);
1494                 goto RetryFault;
1495         }
1496         if (result != KERN_SUCCESS) {
1497                 *errorp = result;
1498                 return(NULL);
1499         }
1500
1501         if ((fault_type & VM_PROT_WRITE) && (fs.prot & VM_PROT_WRITE) == 0) {
1502                 *errorp = KERN_PROTECTION_FAILURE;
1503                 unlock_things(&fs);
1504                 return(NULL);
1505         }
1506
1507         /*
1508          * On success vm_fault_object() does not unlock or deallocate, so we
1509          * do it here.  Note that the returned fs.m will be busied.
1510          */
1511         unlock_things(&fs);
1512
1513         /*
1514          * Return a held page.  We are not doing any pmap manipulation so do
1515          * not set PG_MAPPED.  However, adjust the page flags according to
1516          * the fault type because the caller may not use a managed pmapping
1517          * (so we don't want to lose the fact that the page will be dirtied
1518          * if a write fault was specified).
1519          */
1520         vm_page_hold(fs.m);
1521         vm_page_activate(fs.m);
1522         if ((fault_type & VM_PROT_WRITE) || (fault_flags & VM_FAULT_DIRTY))
1523                 vm_page_dirty(fs.m);
1524         if (fault_flags & VM_FAULT_UNSWAP)
1525                 swap_pager_unswapped(fs.m);
1526
1527         /*
1528          * Indicate that the page was accessed.
1529          */
1530         vm_page_flag_set(fs.m, PG_REFERENCED);
1531
1532         if (curthread->td_lwp) {
1533                 if (fs.hardfault) {
1534                         curthread->td_lwp->lwp_ru.ru_majflt++;
1535                 } else {
1536                         curthread->td_lwp->lwp_ru.ru_minflt++;
1537                 }
1538         }
1539
1540         /*
1541          * Unlock everything, and return the held page.
1542          */
1543         vm_page_wakeup(fs.m);
1544         /*vm_object_deallocate(fs.first_ba->object);*/
1545
1546         *errorp = 0;
1547         return(fs.m);
1548 }
1549
1550 /*
1551  * Translate the virtual page number (first_pindex) that is relative
1552  * to the address space into a logical page number that is relative to the
1553  * backing object.  Use the virtual page table pointed to by (vpte).
1554  *
1555  * Possibly downgrade the protection based on the vpte bits.
1556  *
1557  * This implements an N-level page table.  Any level can terminate the
1558  * scan by setting VPTE_PS.   A linear mapping is accomplished by setting
1559  * VPTE_PS in the master page directory entry set via mcontrol(MADV_SETMAP).
1560  */
1561 static
1562 int
1563 vm_fault_vpagetable(struct faultstate *fs, vm_pindex_t *pindex,
1564                     vpte_t vpte, int fault_type, int allow_nofault)
1565 {
1566         struct lwbuf *lwb;
1567         struct lwbuf lwb_cache;
1568         int vshift = VPTE_FRAME_END - PAGE_SHIFT; /* index bits remaining */
1569         int result;
1570         vpte_t *ptep;
1571
1572         ASSERT_LWKT_TOKEN_HELD(vm_object_token(fs->first_ba->object));
1573         for (;;) {
1574                 /*
1575                  * We cannot proceed if the vpte is not valid, not readable
1576                  * for a read fault, not writable for a write fault, or
1577                  * not executable for an instruction execution fault.
1578                  */
1579                 if ((vpte & VPTE_V) == 0) {
1580                         unlock_things(fs);
1581                         return (KERN_FAILURE);
1582                 }
1583                 if ((fault_type & VM_PROT_WRITE) && (vpte & VPTE_RW) == 0) {
1584                         unlock_things(fs);
1585                         return (KERN_FAILURE);
1586                 }
1587                 if ((fault_type & VM_PROT_EXECUTE) && (vpte & VPTE_NX)) {
1588                         unlock_things(fs);
1589                         return (KERN_FAILURE);
1590                 }
1591                 if ((vpte & VPTE_PS) || vshift == 0)
1592                         break;
1593
1594                 /*
1595                  * Get the page table page.  Nominally we only read the page
1596                  * table, but since we are actively setting VPTE_M and VPTE_A,
1597                  * tell vm_fault_object() that we are writing it. 
1598                  *
1599                  * There is currently no real need to optimize this.
1600                  */
1601                 result = vm_fault_object(fs, (vpte & VPTE_FRAME) >> PAGE_SHIFT,
1602                                          VM_PROT_READ|VM_PROT_WRITE,
1603                                          allow_nofault);
1604                 if (result != KERN_SUCCESS)
1605                         return (result);
1606
1607                 /*
1608                  * Process the returned fs.m and look up the page table
1609                  * entry in the page table page.
1610                  */
1611                 vshift -= VPTE_PAGE_BITS;
1612                 lwb = lwbuf_alloc(fs->m, &lwb_cache);
1613                 ptep = ((vpte_t *)lwbuf_kva(lwb) +
1614                         ((*pindex >> vshift) & VPTE_PAGE_MASK));
1615                 vm_page_activate(fs->m);
1616
1617                 /*
1618                  * Page table write-back - entire operation including
1619                  * validation of the pte must be atomic to avoid races
1620                  * against the vkernel changing the pte.
1621                  *
1622                  * If the vpte is valid for the* requested operation, do
1623                  * a write-back to the page table.
1624                  *
1625                  * XXX VPTE_M is not set properly for page directory pages.
1626                  * It doesn't get set in the page directory if the page table
1627                  * is modified during a read access.
1628                  */
1629                 for (;;) {
1630                         vpte_t nvpte;
1631
1632                         /*
1633                          * Reload for the cmpset, but make sure the pte is
1634                          * still valid.
1635                          */
1636                         vpte = *ptep;
1637                         cpu_ccfence();
1638                         nvpte = vpte;
1639
1640                         if ((vpte & VPTE_V) == 0)
1641                                 break;
1642
1643                         if ((fault_type & VM_PROT_WRITE) && (vpte & VPTE_RW))
1644                                 nvpte |= VPTE_M | VPTE_A;
1645                         if (fault_type & (VM_PROT_READ | VM_PROT_EXECUTE))
1646                                 nvpte |= VPTE_A;
1647                         if (vpte == nvpte)
1648                                 break;
1649                         if (atomic_cmpset_long(ptep, vpte, nvpte)) {
1650                                 vm_page_dirty(fs->m);
1651                                 break;
1652                         }
1653                 }
1654                 lwbuf_free(lwb);
1655                 vm_page_flag_set(fs->m, PG_REFERENCED);
1656                 vm_page_wakeup(fs->m);
1657                 fs->m = NULL;
1658                 cleanup_fault(fs);
1659         }
1660
1661         /*
1662          * When the vkernel sets VPTE_RW it expects the real kernel to
1663          * reflect VPTE_M back when the page is modified via the mapping.
1664          * In order to accomplish this the real kernel must map the page
1665          * read-only for read faults and use write faults to reflect VPTE_M
1666          * back.
1667          *
1668          * Once VPTE_M has been set, the real kernel's pte allows writing.
1669          * If the vkernel clears VPTE_M the vkernel must be sure to
1670          * MADV_INVAL the real kernel's mappings to force the real kernel
1671          * to re-fault on the next write so oit can set VPTE_M again.
1672          */
1673         if ((fault_type & VM_PROT_WRITE) == 0 &&
1674             (vpte & (VPTE_RW | VPTE_M)) != (VPTE_RW | VPTE_M)) {
1675                 fs->first_prot &= ~VM_PROT_WRITE;
1676         }
1677
1678         /*
1679          * Disable EXECUTE perms if NX bit is set.
1680          */
1681         if (vpte & VPTE_NX)
1682                 fs->first_prot &= ~VM_PROT_EXECUTE;
1683
1684         /*
1685          * Combine remaining address bits with the vpte.
1686          */
1687         *pindex = ((vpte & VPTE_FRAME) >> PAGE_SHIFT) +
1688                   (*pindex & ((1L << vshift) - 1));
1689         return (KERN_SUCCESS);
1690 }
1691
1692
1693 /*
1694  * This is the core of the vm_fault code.
1695  *
1696  * Do all operations required to fault-in (fs.first_ba->object, pindex).
1697  * Run through the backing store as necessary and do required COW or virtual
1698  * copy operations.  The caller has already fully resolved the vm_map_entry
1699  * and, if appropriate, has created a copy-on-write layer.  All we need to
1700  * do is iterate the object chain.
1701  *
1702  * On failure (fs) is unlocked and deallocated and the caller may return or
1703  * retry depending on the failure code.  On success (fs) is NOT unlocked or
1704  * deallocated, fs.m will contained a resolved, busied page, and fs.ba's
1705  * object will have an additional PIP count if it is not equal to
1706  * fs.first_ba.
1707  *
1708  * If locks based on fs->first_shared or fs->shared are insufficient,
1709  * clear the appropriate field(s) and return RETRY.  COWs require that
1710  * first_shared be 0, while page allocations (or frees) require that
1711  * shared be 0.  Renames require that both be 0.
1712  *
1713  * NOTE! fs->[first_]shared might be set with VM_FAULT_DIRTY also set.
1714  *       we will have to retry with it exclusive if the vm_page is
1715  *       PG_SWAPPED.
1716  *
1717  * fs->first_ba->object must be held on call.
1718  */
1719 static
1720 int
1721 vm_fault_object(struct faultstate *fs, vm_pindex_t first_pindex,
1722                 vm_prot_t fault_type, int allow_nofault)
1723 {
1724         vm_map_backing_t next_ba;
1725         vm_pindex_t pindex;
1726         int error;
1727
1728         ASSERT_LWKT_TOKEN_HELD(vm_object_token(fs->first_ba->object));
1729         fs->prot = fs->first_prot;
1730         pindex = first_pindex;
1731         KKASSERT(fs->ba == fs->first_ba);
1732
1733         vm_object_pip_add(fs->first_ba->object, 1);
1734
1735         /* 
1736          * If a read fault occurs we try to upgrade the page protection
1737          * and make it also writable if possible.  There are three cases
1738          * where we cannot make the page mapping writable:
1739          *
1740          * (1) The mapping is read-only or the VM object is read-only,
1741          *     fs->prot above will simply not have VM_PROT_WRITE set.
1742          *
1743          * (2) If the mapping is a virtual page table fs->first_prot will
1744          *     have already been properly adjusted by vm_fault_vpagetable().
1745          *     to detect writes so we can set VPTE_M in the virtual page
1746          *     table.  Used by vkernels.
1747          *
1748          * (3) If the VM page is read-only or copy-on-write, upgrading would
1749          *     just result in an unnecessary COW fault.
1750          *
1751          * (4) If the pmap specifically requests A/M bit emulation, downgrade
1752          *     here.
1753          */
1754 #if 0
1755         /* see vpagetable code */
1756         if (fs->entry->maptype == VM_MAPTYPE_VPAGETABLE) {
1757                 if ((fault_type & VM_PROT_WRITE) == 0)
1758                         fs->prot &= ~VM_PROT_WRITE;
1759         }
1760 #endif
1761
1762         if (curthread->td_lwp && curthread->td_lwp->lwp_vmspace &&
1763             pmap_emulate_ad_bits(&curthread->td_lwp->lwp_vmspace->vm_pmap)) {
1764                 if ((fault_type & VM_PROT_WRITE) == 0)
1765                         fs->prot &= ~VM_PROT_WRITE;
1766         }
1767
1768         /* vm_object_hold(fs->ba->object); implied b/c ba == first_ba */
1769
1770         for (;;) {
1771                 /*
1772                  * If the object is dead, we stop here
1773                  */
1774                 if (fs->ba->object->flags & OBJ_DEAD) {
1775                         vm_object_pip_wakeup(fs->first_ba->object);
1776                         unlock_things(fs);
1777                         return (KERN_PROTECTION_FAILURE);
1778                 }
1779
1780                 /*
1781                  * See if the page is resident.  Wait/Retry if the page is
1782                  * busy (lots of stuff may have changed so we can't continue
1783                  * in that case).
1784                  *
1785                  * We can theoretically allow the soft-busy case on a read
1786                  * fault if the page is marked valid, but since such
1787                  * pages are typically already pmap'd, putting that
1788                  * special case in might be more effort then it is
1789                  * worth.  We cannot under any circumstances mess
1790                  * around with a vm_page_t->busy page except, perhaps,
1791                  * to pmap it.
1792                  */
1793                 fs->m = vm_page_lookup_busy_try(fs->ba->object, pindex,
1794                                                 TRUE, &error);
1795                 if (error) {
1796                         vm_object_pip_wakeup(fs->first_ba->object);
1797                         unlock_things(fs);
1798                         vm_page_sleep_busy(fs->m, TRUE, "vmpfw");
1799                         mycpu->gd_cnt.v_intrans++;
1800                         fs->m = NULL;
1801                         return (KERN_TRY_AGAIN);
1802                 }
1803                 if (fs->m) {
1804                         /*
1805                          * The page is busied for us.
1806                          *
1807                          * If reactivating a page from PQ_CACHE we may have
1808                          * to rate-limit.
1809                          */
1810                         int queue = fs->m->queue;
1811                         vm_page_unqueue_nowakeup(fs->m);
1812
1813                         if ((queue - fs->m->pc) == PQ_CACHE && 
1814                             vm_page_count_severe()) {
1815                                 vm_page_activate(fs->m);
1816                                 vm_page_wakeup(fs->m);
1817                                 fs->m = NULL;
1818                                 vm_object_pip_wakeup(fs->first_ba->object);
1819                                 unlock_things(fs);
1820                                 if (allow_nofault == 0 ||
1821                                     (curthread->td_flags & TDF_NOFAULT) == 0) {
1822                                         thread_t td;
1823
1824                                         vm_wait_pfault();
1825                                         td = curthread;
1826                                         if (td->td_proc && (td->td_proc->p_flags & P_LOWMEMKILL))
1827                                                 return (KERN_PROTECTION_FAILURE);
1828                                 }
1829                                 return (KERN_TRY_AGAIN);
1830                         }
1831
1832                         /*
1833                          * If it still isn't completely valid (readable),
1834                          * or if a read-ahead-mark is set on the VM page,
1835                          * jump to readrest, else we found the page and
1836                          * can return.
1837                          *
1838                          * We can release the spl once we have marked the
1839                          * page busy.
1840                          */
1841                         if (fs->m->object != &kernel_object) {
1842                                 if ((fs->m->valid & VM_PAGE_BITS_ALL) !=
1843                                     VM_PAGE_BITS_ALL) {
1844                                         goto readrest;
1845                                 }
1846                                 if (fs->m->flags & PG_RAM) {
1847                                         if (debug_cluster)
1848                                                 kprintf("R");
1849                                         vm_page_flag_clear(fs->m, PG_RAM);
1850                                         goto readrest;
1851                                 }
1852                         }
1853                         fs->first_ba->flags &= ~VM_MAP_BACK_EXCL_HEUR;
1854                         break; /* break to PAGE HAS BEEN FOUND */
1855                 }
1856
1857                 /*
1858                  * Page is not resident, If this is the search termination
1859                  * or the pager might contain the page, allocate a new page.
1860                  */
1861                 if (TRYPAGER(fs) || fs->ba == fs->first_ba) {
1862                         /*
1863                          * If this is a SWAP object we can use the shared
1864                          * lock to check existence of a swap block.  If
1865                          * there isn't one we can skip to the next object.
1866                          *
1867                          * However, if this is the first object we allocate
1868                          * a page now just in case we need to copy to it
1869                          * later.
1870                          */
1871                         if (fs->ba != fs->first_ba &&
1872                             fs->ba->object->type == OBJT_SWAP) {
1873                                 if (swap_pager_haspage_locked(fs->ba->object,
1874                                                               pindex) == 0) {
1875                                         goto next;
1876                                 }
1877                         }
1878
1879                         /*
1880                          * Allocating, must be exclusive.
1881                          */
1882                         fs->first_ba->flags |= VM_MAP_BACK_EXCL_HEUR;
1883                         if (fs->ba == fs->first_ba && fs->first_shared) {
1884                                 fs->first_shared = 0;
1885                                 vm_object_pip_wakeup(fs->first_ba->object);
1886                                 unlock_things(fs);
1887                                 return (KERN_TRY_AGAIN);
1888                         }
1889                         if (fs->ba != fs->first_ba && fs->shared) {
1890                                 fs->first_shared = 0;
1891                                 fs->shared = 0;
1892                                 vm_object_pip_wakeup(fs->first_ba->object);
1893                                 unlock_things(fs);
1894                                 return (KERN_TRY_AGAIN);
1895                         }
1896
1897                         /*
1898                          * If the page is beyond the object size we fail
1899                          */
1900                         if (pindex >= fs->ba->object->size) {
1901                                 vm_object_pip_wakeup(fs->first_ba->object);
1902                                 unlock_things(fs);
1903                                 return (KERN_PROTECTION_FAILURE);
1904                         }
1905
1906                         /*
1907                          * Allocate a new page for this object/offset pair.
1908                          *
1909                          * It is possible for the allocation to race, so
1910                          * handle the case.
1911                          */
1912                         fs->m = NULL;
1913                         if (!vm_page_count_severe()) {
1914                                 fs->m = vm_page_alloc(fs->ba->object, pindex,
1915                                     ((fs->vp || fs->ba->backing_ba) ?
1916                                         VM_ALLOC_NULL_OK | VM_ALLOC_NORMAL :
1917                                         VM_ALLOC_NULL_OK | VM_ALLOC_NORMAL |
1918                                         VM_ALLOC_USE_GD | VM_ALLOC_ZERO));
1919                         }
1920                         if (fs->m == NULL) {
1921                                 vm_object_pip_wakeup(fs->first_ba->object);
1922                                 unlock_things(fs);
1923                                 if (allow_nofault == 0 ||
1924                                     (curthread->td_flags & TDF_NOFAULT) == 0) {
1925                                         thread_t td;
1926
1927                                         vm_wait_pfault();
1928                                         td = curthread;
1929                                         if (td->td_proc && (td->td_proc->p_flags & P_LOWMEMKILL))
1930                                                 return (KERN_PROTECTION_FAILURE);
1931                                 }
1932                                 return (KERN_TRY_AGAIN);
1933                         }
1934
1935                         /*
1936                          * Fall through to readrest.  We have a new page which
1937                          * will have to be paged (since m->valid will be 0).
1938                          */
1939                 }
1940
1941 readrest:
1942                 /*
1943                  * We have found an invalid or partially valid page, a
1944                  * page with a read-ahead mark which might be partially or
1945                  * fully valid (and maybe dirty too), or we have allocated
1946                  * a new page.
1947                  *
1948                  * Attempt to fault-in the page if there is a chance that the
1949                  * pager has it, and potentially fault in additional pages
1950                  * at the same time.
1951                  *
1952                  * If TRYPAGER is true then fs.m will be non-NULL and busied
1953                  * for us.
1954                  */
1955                 if (TRYPAGER(fs)) {
1956                         u_char behavior = vm_map_entry_behavior(fs->entry);
1957                         vm_object_t object;
1958                         vm_page_t first_m;
1959                         int seqaccess;
1960                         int rv;
1961
1962                         if (behavior == MAP_ENTRY_BEHAV_RANDOM)
1963                                 seqaccess = 0;
1964                         else
1965                                 seqaccess = -1;
1966
1967                         /*
1968                          * Doing I/O may synchronously insert additional
1969                          * pages so we can't be shared at this point either.
1970                          *
1971                          * NOTE: We can't free fs->m here in the allocated
1972                          *       case (fs->ba != fs->first_ba) as this
1973                          *       would require an exclusively locked
1974                          *       VM object.
1975                          */
1976                         if (fs->ba == fs->first_ba && fs->first_shared) {
1977                                 vm_page_deactivate(fs->m);
1978                                 vm_page_wakeup(fs->m);
1979                                 fs->m = NULL;
1980                                 fs->first_shared = 0;
1981                                 vm_object_pip_wakeup(fs->first_ba->object);
1982                                 unlock_things(fs);
1983                                 return (KERN_TRY_AGAIN);
1984                         }
1985                         if (fs->ba != fs->first_ba && fs->shared) {
1986                                 vm_page_deactivate(fs->m);
1987                                 vm_page_wakeup(fs->m);
1988                                 fs->m = NULL;
1989                                 fs->first_shared = 0;
1990                                 fs->shared = 0;
1991                                 vm_object_pip_wakeup(fs->first_ba->object);
1992                                 unlock_things(fs);
1993                                 return (KERN_TRY_AGAIN);
1994                         }
1995
1996                         object = fs->ba->object;
1997                         first_m = NULL;
1998
1999                         /* object is held, no more access to entry or ba's */
2000
2001                         /*
2002                          * Acquire the page data.  We still hold object
2003                          * and the page has been BUSY's.
2004                          *
2005                          * We own the page, but we must re-issue the lookup
2006                          * because the pager may have replaced it (for example,
2007                          * in order to enter a fictitious page into the
2008                          * object).  In this situation the pager will have
2009                          * cleaned up the old page and left the new one
2010                          * busy for us.
2011                          *
2012                          * If we got here through a PG_RAM read-ahead
2013                          * mark the page may be partially dirty and thus
2014                          * not freeable.  Don't bother checking to see
2015                          * if the pager has the page because we can't free
2016                          * it anyway.  We have to depend on the get_page
2017                          * operation filling in any gaps whether there is
2018                          * backing store or not.
2019                          *
2020                          * We must dispose of the page (fs->m) and also
2021                          * possibly first_m (the fronting layer).  If
2022                          * this is a write fault leave the page intact
2023                          * because we will probably have to copy fs->m
2024                          * to fs->first_m on the retry.  If this is a
2025                          * read fault we probably won't need the page.
2026                          */
2027                         rv = vm_pager_get_page(object, &fs->m, seqaccess);
2028
2029                         if (rv == VM_PAGER_OK) {
2030                                 ++fs->hardfault;
2031                                 fs->m = vm_page_lookup(object, pindex);
2032                                 if (fs->m) {
2033                                         vm_page_activate(fs->m);
2034                                         vm_page_wakeup(fs->m);
2035                                         fs->m = NULL;
2036                                 }
2037
2038                                 if (fs->m) {
2039                                         /* have page */
2040                                         break;
2041                                 }
2042                                 vm_object_pip_wakeup(fs->first_ba->object);
2043                                 unlock_things(fs);
2044                                 return (KERN_TRY_AGAIN);
2045                         }
2046
2047                         /*
2048                          * If the pager doesn't have the page, continue on
2049                          * to the next object.  Retain the vm_page if this
2050                          * is the first object, we may need to copy into
2051                          * it later.
2052                          */
2053                         if (rv == VM_PAGER_FAIL) {
2054                                 if (fs->ba != fs->first_ba) {
2055                                         vm_page_free(fs->m);
2056                                         fs->m = NULL;
2057                                 }
2058                                 goto next;
2059                         }
2060
2061                         /*
2062                          * Remove the bogus page (which does not exist at this
2063                          * object/offset).
2064                          *
2065                          * Also wake up any other process that may want to bring
2066                          * in this page.
2067                          *
2068                          * If this is the top-level object, we must leave the
2069                          * busy page to prevent another process from rushing
2070                          * past us, and inserting the page in that object at
2071                          * the same time that we are.
2072                          */
2073                         if (rv == VM_PAGER_ERROR) {
2074                                 if (curproc) {
2075                                         kprintf("vm_fault: pager read error, "
2076                                                 "pid %d (%s)\n",
2077                                                 curproc->p_pid,
2078                                                 curproc->p_comm);
2079                                 } else {
2080                                         kprintf("vm_fault: pager read error, "
2081                                                 "thread %p (%s)\n",
2082                                                 curthread,
2083                                                 curthread->td_comm);
2084                                 }
2085                         }
2086
2087                         /*
2088                          * I/O error or data outside pager's range.
2089                          */
2090                         if (fs->m) {
2091                                 vnode_pager_freepage(fs->m);
2092                                 fs->m = NULL;
2093                         }
2094                         if (first_m) {
2095                                 vm_page_free(first_m);
2096                                 first_m = NULL;         /* safety */
2097                         }
2098                         vm_object_pip_wakeup(object);
2099                         unlock_things(fs);
2100
2101                         switch(rv) {
2102                         case VM_PAGER_ERROR:
2103                                 return (KERN_FAILURE);
2104                         case VM_PAGER_BAD:
2105                                 return (KERN_PROTECTION_FAILURE);
2106                         default:
2107                                 return (KERN_PROTECTION_FAILURE);
2108                         }
2109
2110 #if 0
2111                         /*
2112                          * Data outside the range of the pager or an I/O error
2113                          *
2114                          * The page may have been wired during the pagein,
2115                          * e.g. by the buffer cache, and cannot simply be
2116                          * freed.  Call vnode_pager_freepage() to deal with it.
2117                          *
2118                          * The object is not held shared so we can safely
2119                          * free the page.
2120                          */
2121                         if (fs->ba != fs->first_ba) {
2122
2123                                 /*
2124                                  * XXX - we cannot just fall out at this
2125                                  * point, m has been freed and is invalid!
2126                                  */
2127                         }
2128
2129                         /*
2130                          * XXX - the check for kernel_map is a kludge to work
2131                          * around having the machine panic on a kernel space
2132                          * fault w/ I/O error.
2133                          */
2134                         if (((fs->map != &kernel_map) &&
2135                             (rv == VM_PAGER_ERROR)) || (rv == VM_PAGER_BAD)) {
2136                                 if (fs->m) {
2137                                         /* from just above */
2138                                         KKASSERT(fs->first_shared == 0);
2139                                         vnode_pager_freepage(fs->m);
2140                                         fs->m = NULL;
2141                                 }
2142                                 /* NOT REACHED */
2143                         }
2144 #endif
2145                 }
2146
2147 next:
2148                 /*
2149                  * We get here if the object has a default pager (or unwiring) 
2150                  * or the pager doesn't have the page.
2151                  *
2152                  * fs->first_m will be used for the COW unless we find a
2153                  * deeper page to be mapped read-only, in which case the
2154                  * unlock*(fs) will free first_m.
2155                  */
2156                 if (fs->ba == fs->first_ba)
2157                         fs->first_m = fs->m;
2158
2159                 /*
2160                  * Move on to the next object.  The chain lock should prevent
2161                  * the backing_object from getting ripped out from under us.
2162                  *
2163                  * The object lock for the next object is governed by
2164                  * fs->shared.
2165                  */
2166                 next_ba = fs->ba->backing_ba;
2167                 if (next_ba == NULL) {
2168                         /*
2169                          * If there's no object left, fill the page in the top
2170                          * object with zeros.
2171                          */
2172                         if (fs->ba != fs->first_ba) {
2173                                 vm_object_pip_wakeup(fs->ba->object);
2174                                 vm_object_drop(fs->ba->object);
2175                                 fs->ba = fs->first_ba;
2176                                 pindex = first_pindex;
2177                                 fs->m = fs->first_m;
2178                         }
2179                         fs->first_m = NULL;
2180
2181                         /*
2182                          * Zero the page and mark it valid.
2183                          */
2184                         vm_page_zero_fill(fs->m);
2185                         mycpu->gd_cnt.v_zfod++;
2186                         fs->m->valid = VM_PAGE_BITS_ALL;
2187                         break;  /* break to PAGE HAS BEEN FOUND */
2188                 }
2189
2190                 if (fs->shared)
2191                         vm_object_hold_shared(next_ba->object);
2192                 else
2193                         vm_object_hold(next_ba->object);
2194                 KKASSERT(next_ba == fs->ba->backing_ba);
2195                 pindex -= OFF_TO_IDX(fs->ba->offset);
2196                 pindex += OFF_TO_IDX(next_ba->offset);
2197
2198                 if (fs->ba != fs->first_ba) {
2199                         vm_object_pip_wakeup(fs->ba->object);
2200                         vm_object_lock_swap();  /* flip ba/next_ba */
2201                         vm_object_drop(fs->ba->object);
2202                 }
2203                 fs->ba = next_ba;
2204                 vm_object_pip_add(next_ba->object, 1);
2205         }
2206
2207         /*
2208          * PAGE HAS BEEN FOUND. [Loop invariant still holds -- the object lock
2209          * is held.]
2210          *
2211          * object still held.
2212          * vm_map may not be locked (determined by fs->lookup_still_valid)
2213          *
2214          * local shared variable may be different from fs->shared.
2215          *
2216          * If the page is being written, but isn't already owned by the
2217          * top-level object, we have to copy it into a new page owned by the
2218          * top-level object.
2219          */
2220         KASSERT((fs->m->busy_count & PBUSY_LOCKED) != 0,
2221                 ("vm_fault: not busy after main loop"));
2222
2223         if (fs->ba != fs->first_ba) {
2224                 /*
2225                  * We only really need to copy if we want to write it.
2226                  */
2227                 if (fault_type & VM_PROT_WRITE) {
2228 #if 0
2229                         /* CODE REFACTOR IN PROGRESS, REMOVE OPTIMIZATION */
2230                         /*
2231                          * This allows pages to be virtually copied from a 
2232                          * backing_object into the first_object, where the 
2233                          * backing object has no other refs to it, and cannot
2234                          * gain any more refs.  Instead of a bcopy, we just 
2235                          * move the page from the backing object to the 
2236                          * first object.  Note that we must mark the page 
2237                          * dirty in the first object so that it will go out 
2238                          * to swap when needed.
2239                          */
2240                         if (virtual_copy_ok(fs)) {
2241                                 /*
2242                                  * (first_m) and (m) are both busied.  We have
2243                                  * move (m) into (first_m)'s object/pindex
2244                                  * in an atomic fashion, then free (first_m).
2245                                  *
2246                                  * first_object is held so second remove
2247                                  * followed by the rename should wind
2248                                  * up being atomic.  vm_page_free() might
2249                                  * block so we don't do it until after the
2250                                  * rename.
2251                                  */
2252                                 vm_page_protect(fs->first_m, VM_PROT_NONE);
2253                                 vm_page_remove(fs->first_m);
2254                                 vm_page_rename(fs->m,
2255                                                fs->first_ba->object,
2256                                                first_pindex);
2257                                 vm_page_free(fs->first_m);
2258                                 fs->first_m = fs->m;
2259                                 fs->m = NULL;
2260                                 mycpu->gd_cnt.v_cow_optim++;
2261                         } else
2262 #endif
2263                         {
2264                                 /*
2265                                  * Oh, well, lets copy it.
2266                                  *
2267                                  * We used to unmap the original page here
2268                                  * because vm_fault_page() didn't and this
2269                                  * would cause havoc for the umtx*() code
2270                                  * and the procfs code.
2271                                  *
2272                                  * This is no longer necessary.  The
2273                                  * vm_fault_page() routine will now unmap the
2274                                  * page after a COW, and the umtx code will
2275                                  * recover on its own.
2276                                  */
2277                                 /*
2278                                  * NOTE: Since fs->m is a backing page, it
2279                                  *       is read-only, so there isn't any
2280                                  *       copy race vs writers.
2281                                  */
2282                                 KKASSERT(fs->first_shared == 0);
2283                                 vm_page_copy(fs->m, fs->first_m);
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->ba.start;
2456         end = entry->ba.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->ba.start;
2520         end = entry->ba.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->ba.start;
2576         all_shadowed = 1;
2577
2578         while (scan < entry->ba.end) {
2579                 pindex = OFF_TO_IDX(entry->ba.offset + (scan - entry->ba.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->ba.start, entry->ba.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->ba.start, dst_offset = 0;
2660              vaddr < dst_entry->ba.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->ba.start) {
2990                         noneg = 1;
2991                         if (noneg && nopos)
2992                                 break;
2993                         continue;
2994                 }
2995                 if (addr >= entry->ba.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->ba.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 -= last_ba->offset >> PAGE_SHIFT;
3071                         pindex += next_ba->offset >> PAGE_SHIFT;
3072                         if (last_ba != ba) {
3073                                 vm_object_lock_swap();
3074                                 vm_object_drop(lobject);
3075                         }
3076                         lobject = nobject;
3077                         last_ba = next_ba;
3078                         pprot &= ~VM_PROT_WRITE;
3079                 }
3080
3081                 /*
3082                  * NOTE: A non-NULL (m) will be associated with lobject if
3083                  *       it was found there, otherwise it is probably a
3084                  *       zero-fill page associated with the base object.
3085                  *
3086                  * Give-up if no page is available.
3087                  */
3088                 if (m == NULL) {
3089                         if (last_ba != ba)
3090                                 vm_object_drop(lobject);
3091                         break;
3092                 }
3093
3094                 /*
3095                  * The object must be marked dirty if we are mapping a
3096                  * writable page.  m->object is either lobject or object,
3097                  * both of which are still held.  Do this before we
3098                  * potentially drop the object.
3099                  */
3100                 if (pprot & VM_PROT_WRITE)
3101                         vm_object_set_writeable_dirty(m->object);
3102
3103                 /*
3104                  * Do not conditionalize on PG_RAM.  If pages are present in
3105                  * the VM system we assume optimal caching.  If caching is
3106                  * not optimal the I/O gravy train will be restarted when we
3107                  * hit an unavailable page.  We do not want to try to restart
3108                  * the gravy train now because we really don't know how much
3109                  * of the object has been cached.  The cost for restarting
3110                  * the gravy train should be low (since accesses will likely
3111                  * be I/O bound anyway).
3112                  */
3113                 if (last_ba != ba)
3114                         vm_object_drop(lobject);
3115
3116                 /*
3117                  * Enter the page into the pmap if appropriate.  If we had
3118                  * allocated the page we have to place it on a queue.  If not
3119                  * we just have to make sure it isn't on the cache queue
3120                  * (pages on the cache queue are not allowed to be mapped).
3121                  */
3122                 if (allocated) {
3123                         /*
3124                          * Page must be zerod.
3125                          */
3126                         vm_page_zero_fill(m);
3127                         mycpu->gd_cnt.v_zfod++;
3128                         m->valid = VM_PAGE_BITS_ALL;
3129
3130                         /*
3131                          * Handle dirty page case
3132                          */
3133                         if (pprot & VM_PROT_WRITE)
3134                                 vm_set_nosync(m, entry);
3135                         pmap_enter(pmap, addr, m, pprot, 0, entry);
3136                         mycpu->gd_cnt.v_vm_faults++;
3137                         if (curthread->td_lwp)
3138                                 ++curthread->td_lwp->lwp_ru.ru_minflt;
3139                         vm_page_deactivate(m);
3140                         if (pprot & VM_PROT_WRITE) {
3141                                 /*vm_object_set_writeable_dirty(m->object);*/
3142                                 vm_set_nosync(m, entry);
3143                                 if (fault_flags & VM_FAULT_DIRTY) {
3144                                         vm_page_dirty(m);
3145                                         /*XXX*/
3146                                         swap_pager_unswapped(m);
3147                                 }
3148                         }
3149                         vm_page_wakeup(m);
3150                 } else if (error) {
3151                         /* couldn't busy page, no wakeup */
3152                 } else if (
3153                     ((m->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
3154                     (m->flags & PG_FICTITIOUS) == 0) {
3155                         /*
3156                          * A fully valid page not undergoing soft I/O can
3157                          * be immediately entered into the pmap.
3158                          */
3159                         if ((m->queue - m->pc) == PQ_CACHE)
3160                                 vm_page_deactivate(m);
3161                         if (pprot & VM_PROT_WRITE) {
3162                                 /*vm_object_set_writeable_dirty(m->object);*/
3163                                 vm_set_nosync(m, entry);
3164                                 if (fault_flags & VM_FAULT_DIRTY) {
3165                                         vm_page_dirty(m);
3166                                         /*XXX*/
3167                                         swap_pager_unswapped(m);
3168                                 }
3169                         }
3170                         if (pprot & VM_PROT_WRITE)
3171                                 vm_set_nosync(m, entry);
3172                         pmap_enter(pmap, addr, m, pprot, 0, entry);
3173                         mycpu->gd_cnt.v_vm_faults++;
3174                         if (curthread->td_lwp)
3175                                 ++curthread->td_lwp->lwp_ru.ru_minflt;
3176                         vm_page_wakeup(m);
3177                 } else {
3178                         vm_page_wakeup(m);
3179                 }
3180         }
3181         vm_object_drop(object);
3182 }
3183
3184 /*
3185  * Object can be held shared
3186  */
3187 static void
3188 vm_prefault_quick(pmap_t pmap, vm_offset_t addra,
3189                   vm_map_entry_t entry, int prot, int fault_flags)
3190 {
3191         struct lwp *lp;
3192         vm_page_t m;
3193         vm_offset_t addr;
3194         vm_pindex_t pindex;
3195         vm_object_t object;
3196         int i;
3197         int noneg;
3198         int nopos;
3199         int maxpages;
3200
3201         /*
3202          * Get stable max count value, disabled if set to 0
3203          */
3204         maxpages = vm_prefault_pages;
3205         cpu_ccfence();
3206         if (maxpages <= 0)
3207                 return;
3208
3209         /*
3210          * We do not currently prefault mappings that use virtual page
3211          * tables.  We do not prefault foreign pmaps.
3212          */
3213         if (entry->maptype != VM_MAPTYPE_NORMAL)
3214                 return;
3215         lp = curthread->td_lwp;
3216         if (lp == NULL || (pmap != vmspace_pmap(lp->lwp_vmspace)))
3217                 return;
3218         object = entry->ba.object;
3219         if (entry->ba.backing_ba != NULL)
3220                 return;
3221         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
3222
3223         /*
3224          * Limit pre-fault count to 1024 pages.
3225          */
3226         if (maxpages > 1024)
3227                 maxpages = 1024;
3228
3229         noneg = 0;
3230         nopos = 0;
3231         for (i = 0; i < maxpages; ++i) {
3232                 int error;
3233
3234                 /*
3235                  * Calculate the page to pre-fault, stopping the scan in
3236                  * each direction separately if the limit is reached.
3237                  */
3238                 if (i & 1) {
3239                         if (noneg)
3240                                 continue;
3241                         addr = addra - ((i + 1) >> 1) * PAGE_SIZE;
3242                 } else {
3243                         if (nopos)
3244                                 continue;
3245                         addr = addra + ((i + 2) >> 1) * PAGE_SIZE;
3246                 }
3247                 if (addr < entry->ba.start) {
3248                         noneg = 1;
3249                         if (noneg && nopos)
3250                                 break;
3251                         continue;
3252                 }
3253                 if (addr >= entry->ba.end) {
3254                         nopos = 1;
3255                         if (noneg && nopos)
3256                                 break;
3257                         continue;
3258                 }
3259
3260                 /*
3261                  * Follow the VM object chain to obtain the page to be mapped
3262                  * into the pmap.  This version of the prefault code only
3263                  * works with terminal objects.
3264                  *
3265                  * The page must already exist.  If we encounter a problem
3266                  * we stop here.
3267                  *
3268                  * WARNING!  We cannot call swap_pager_unswapped() or insert
3269                  *           a new vm_page with a shared token.
3270                  */
3271                 pindex = ((addr - entry->ba.start) + entry->ba.offset) >>
3272                          PAGE_SHIFT;
3273
3274                 /*
3275                  * Skip pages already mapped, and stop scanning in that
3276                  * direction.  When the scan terminates in both directions
3277                  * we are done.
3278                  */
3279                 if (pmap_prefault_ok(pmap, addr) == 0) {
3280                         if (i & 1)
3281                                 noneg = 1;
3282                         else
3283                                 nopos = 1;
3284                         if (noneg && nopos)
3285                                 break;
3286                         continue;
3287                 }
3288
3289                 /*
3290                  * Shortcut the read-only mapping case using the far more
3291                  * efficient vm_page_lookup_sbusy_try() function.  This
3292                  * allows us to acquire the page soft-busied only which
3293                  * is especially nice for concurrent execs of the same
3294                  * program.
3295                  *
3296                  * The lookup function also validates page suitability
3297                  * (all valid bits set, and not fictitious).
3298                  *
3299                  * If the page is in PQ_CACHE we have to fall-through
3300                  * and hard-busy it so we can move it out of PQ_CACHE.
3301                  */
3302                 if ((prot & VM_PROT_WRITE) == 0) {
3303                         m = vm_page_lookup_sbusy_try(object, pindex,
3304                                                      0, PAGE_SIZE);
3305                         if (m == NULL)
3306                                 break;
3307                         if ((m->queue - m->pc) != PQ_CACHE) {
3308                                 pmap_enter(pmap, addr, m, prot, 0, entry);
3309                                 mycpu->gd_cnt.v_vm_faults++;
3310                                 if (curthread->td_lwp)
3311                                         ++curthread->td_lwp->lwp_ru.ru_minflt;
3312                                 vm_page_sbusy_drop(m);
3313                                 continue;
3314                         }
3315                         vm_page_sbusy_drop(m);
3316                 }
3317
3318                 /*
3319                  * Fallback to normal vm_page lookup code.  This code
3320                  * hard-busies the page.  Not only that, but the page
3321                  * can remain in that state for a significant period
3322                  * time due to pmap_enter()'s overhead.
3323                  */
3324                 m = vm_page_lookup_busy_try(object, pindex, TRUE, &error);
3325                 if (m == NULL || error)
3326                         break;
3327
3328                 /*
3329                  * Stop if the page cannot be trivially entered into the
3330                  * pmap.
3331                  */
3332                 if (((m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) ||
3333                     (m->flags & PG_FICTITIOUS) ||
3334                     ((m->flags & PG_SWAPPED) &&
3335                      (prot & VM_PROT_WRITE) &&
3336                      (fault_flags & VM_FAULT_DIRTY))) {
3337                         vm_page_wakeup(m);
3338                         break;
3339                 }
3340
3341                 /*
3342                  * Enter the page into the pmap.  The object might be held
3343                  * shared so we can't do any (serious) modifying operation
3344                  * on it.
3345                  */
3346                 if ((m->queue - m->pc) == PQ_CACHE)
3347                         vm_page_deactivate(m);
3348                 if (prot & VM_PROT_WRITE) {
3349                         vm_object_set_writeable_dirty(m->object);
3350                         vm_set_nosync(m, entry);
3351                         if (fault_flags & VM_FAULT_DIRTY) {
3352                                 vm_page_dirty(m);
3353                                 /* can't happeen due to conditional above */
3354                                 /* swap_pager_unswapped(m); */
3355                         }
3356                 }
3357                 pmap_enter(pmap, addr, m, prot, 0, entry);
3358                 mycpu->gd_cnt.v_vm_faults++;
3359                 if (curthread->td_lwp)
3360                         ++curthread->td_lwp->lwp_ru.ru_minflt;
3361                 vm_page_wakeup(m);
3362         }
3363 }