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