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