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