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