c1b3626ddb088944efd3079d03ed5d1fde09e5b2
[dragonfly.git] / sys / vm / vm_fault.c
1 /*
2  * Copyright (c) 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1994 John S. Dyson
5  * All rights reserved.
6  * Copyright (c) 1994 David Greenman
7  * All rights reserved.
8  *
9  *
10  * This code is derived from software contributed to Berkeley by
11  * The Mach Operating System project at Carnegie-Mellon University.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. All advertising materials mentioning features or use of this software
22  *    must display the following acknowledgement:
23  *      This product includes software developed by the University of
24  *      California, Berkeley and its contributors.
25  * 4. Neither the name of the University nor the names of its contributors
26  *    may be used to endorse or promote products derived from this software
27  *    without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39  * SUCH DAMAGE.
40  *
41  *      from: @(#)vm_fault.c    8.4 (Berkeley) 1/12/94
42  *
43  *
44  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
45  * All rights reserved.
46  *
47  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
48  *
49  * Permission to use, copy, modify and distribute this software and
50  * its documentation is hereby granted, provided that both the copyright
51  * notice and this permission notice appear in all copies of the
52  * software, derivative works or modified versions, and any portions
53  * thereof, and that both notices appear in supporting documentation.
54  *
55  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
56  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
57  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
58  *
59  * Carnegie Mellon requests users of this software to return to
60  *
61  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
62  *  School of Computer Science
63  *  Carnegie Mellon University
64  *  Pittsburgh PA 15213-3890
65  *
66  * any improvements or extensions that they make and grant Carnegie the
67  * rights to redistribute these changes.
68  *
69  * $FreeBSD: src/sys/vm/vm_fault.c,v 1.108.2.8 2002/02/26 05:49:27 silby Exp $
70  * $DragonFly: src/sys/vm/vm_fault.c,v 1.39 2007/01/11 10:15:21 dillon Exp $
71  */
72
73 /*
74  *      Page fault handling module.
75  */
76
77 #include <sys/param.h>
78 #include <sys/systm.h>
79 #include <sys/kernel.h>
80 #include <sys/proc.h>
81 #include <sys/vnode.h>
82 #include <sys/resourcevar.h>
83 #include <sys/vmmeter.h>
84 #include <sys/vkernel.h>
85 #include <sys/sfbuf.h>
86 #include <sys/lock.h>
87
88 #include <vm/vm.h>
89 #include <vm/vm_param.h>
90 #include <vm/pmap.h>
91 #include <vm/vm_map.h>
92 #include <vm/vm_object.h>
93 #include <vm/vm_page.h>
94 #include <vm/vm_pageout.h>
95 #include <vm/vm_kern.h>
96 #include <vm/vm_pager.h>
97 #include <vm/vnode_pager.h>
98 #include <vm/vm_extern.h>
99
100 #include <sys/thread2.h>
101 #include <vm/vm_page2.h>
102
103 #define VM_FAULT_READ_AHEAD 8
104 #define VM_FAULT_READ_BEHIND 7
105 #define VM_FAULT_READ (VM_FAULT_READ_AHEAD+VM_FAULT_READ_BEHIND+1)
106
107 struct faultstate {
108         vm_page_t m;
109         vm_object_t object;
110         vm_pindex_t pindex;
111         vm_prot_t prot;
112         vm_page_t first_m;
113         vm_object_t first_object;
114         vm_prot_t first_prot;
115         vm_map_t map;
116         vm_map_entry_t entry;
117         int lookup_still_valid;
118         int didlimit;
119         int hardfault;
120         int fault_flags;
121         int map_generation;
122         boolean_t wired;
123         struct vnode *vp;
124 };
125
126 static int vm_fault_object(struct faultstate *, vm_pindex_t, vm_prot_t);
127 static int vm_fault_vpagetable(struct faultstate *, vm_pindex_t *, vpte_t, int);
128 static int vm_fault_additional_pages (vm_page_t, int, int, vm_page_t *, int *);
129 static int vm_fault_ratelimit(struct vmspace *);
130
131 static __inline void
132 release_page(struct faultstate *fs)
133 {
134         vm_page_wakeup(fs->m);
135         vm_page_deactivate(fs->m);
136         fs->m = NULL;
137 }
138
139 static __inline void
140 unlock_map(struct faultstate *fs)
141 {
142         if (fs->lookup_still_valid) {
143                 vm_map_lookup_done(fs->map, fs->entry, 0);
144                 fs->lookup_still_valid = FALSE;
145         }
146 }
147
148 /*
149  * Clean up after a successful call to vm_fault_object() so another call
150  * to vm_fault_object() can be made.
151  */
152 static void
153 _cleanup_successful_fault(struct faultstate *fs, int relock)
154 {
155         if (fs->object != fs->first_object) {
156                 vm_page_free(fs->first_m);
157                 vm_object_pip_wakeup(fs->object);
158                 fs->first_m = NULL;
159         }
160         fs->object = fs->first_object;
161         if (relock && fs->lookup_still_valid == FALSE) {
162                 vm_map_lock_read(fs->map);
163                 fs->lookup_still_valid = TRUE;
164         }
165 }
166
167 static void
168 _unlock_things(struct faultstate *fs, int dealloc)
169 {
170         vm_object_pip_wakeup(fs->first_object);
171         _cleanup_successful_fault(fs, 0);
172         if (dealloc) {
173                 vm_object_deallocate(fs->first_object);
174         }
175         unlock_map(fs); 
176         if (fs->vp != NULL) { 
177                 vput(fs->vp);
178                 fs->vp = NULL;
179         }
180 }
181
182 #define unlock_things(fs) _unlock_things(fs, 0)
183 #define unlock_and_deallocate(fs) _unlock_things(fs, 1)
184 #define cleanup_successful_fault(fs) _cleanup_successful_fault(fs, 1)
185
186 /*
187  * TRYPAGER 
188  *
189  * Determine if the pager for the current object *might* contain the page.
190  *
191  * We only need to try the pager if this is not a default object (default
192  * objects are zero-fill and have no real pager), and if we are not taking
193  * a wiring fault or if the FS entry is wired.
194  */
195 #define TRYPAGER(fs)    \
196                 (fs->object->type != OBJT_DEFAULT && \
197                 (((fs->fault_flags & VM_FAULT_WIRE_MASK) == 0) || fs->wired))
198
199 /*
200  * vm_fault:
201  *
202  * Handle a page fault occuring at the given address, requiring the given
203  * permissions, in the map specified.  If successful, the page is inserted
204  * into the associated physical map.
205  *
206  * NOTE: The given address should be truncated to the proper page address.
207  *
208  * KERN_SUCCESS is returned if the page fault is handled; otherwise,
209  * a standard error specifying why the fault is fatal is returned.
210  *
211  * The map in question must be referenced, and remains so.
212  * The caller may hold no locks.
213  */
214 int
215 vm_fault(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type, int fault_flags)
216 {
217         int result;
218         vm_pindex_t first_pindex;
219         struct faultstate fs;
220
221         mycpu->gd_cnt.v_vm_faults++;
222
223         fs.didlimit = 0;
224         fs.hardfault = 0;
225         fs.fault_flags = fault_flags;
226
227 RetryFault:
228         /*
229          * Find the vm_map_entry representing the backing store and resolve
230          * the top level object and page index.  This may have the side
231          * effect of executing a copy-on-write on the map entry and/or
232          * creating a shadow object, but will not COW any actual VM pages.
233          *
234          * On success fs.map is left read-locked and various other fields 
235          * are initialized but not otherwise referenced or locked.
236          *
237          * NOTE!  vm_map_lookup will try to upgrade the fault_type to
238          * VM_FAULT_WRITE if the map entry is a virtual page table and also
239          * writable, so we can set the 'A'accessed bit in the virtual page
240          * table entry.
241          */
242         fs.map = map;
243         result = vm_map_lookup(&fs.map, vaddr, fault_type,
244                                &fs.entry, &fs.first_object,
245                                &first_pindex, &fs.first_prot, &fs.wired);
246
247         /*
248          * If the lookup failed or the map protections are incompatible,
249          * the fault generally fails.  However, if the caller is trying
250          * to do a user wiring we have more work to do.
251          */
252         if (result != KERN_SUCCESS) {
253                 if (result != KERN_PROTECTION_FAILURE)
254                         return result;
255                 if ((fs.fault_flags & VM_FAULT_WIRE_MASK) != VM_FAULT_USER_WIRE)
256                         return result;
257
258                 /*
259                  * If we are user-wiring a r/w segment, and it is COW, then
260                  * we need to do the COW operation.  Note that we don't
261                  * currently COW RO sections now, because it is NOT desirable
262                  * to COW .text.  We simply keep .text from ever being COW'ed
263                  * and take the heat that one cannot debug wired .text sections.
264                  */
265                 result = vm_map_lookup(&fs.map, vaddr,
266                                        VM_PROT_READ|VM_PROT_WRITE|
267                                         VM_PROT_OVERRIDE_WRITE,
268                                        &fs.entry, &fs.first_object,
269                                        &first_pindex, &fs.first_prot,
270                                        &fs.wired);
271                 if (result != KERN_SUCCESS)
272                         return result;
273
274                 /*
275                  * If we don't COW now, on a user wire, the user will never
276                  * be able to write to the mapping.  If we don't make this
277                  * restriction, the bookkeeping would be nearly impossible.
278                  */
279                 if ((fs.entry->protection & VM_PROT_WRITE) == 0)
280                         fs.entry->max_protection &= ~VM_PROT_WRITE;
281         }
282
283         /*
284          * fs.map is read-locked
285          *
286          * Misc checks.  Save the map generation number to detect races.
287          */
288         fs.map_generation = fs.map->timestamp;
289
290         if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
291                 panic("vm_fault: fault on nofault entry, addr: %lx",
292                     (u_long)vaddr);
293         }
294
295         /*
296          * A system map entry may return a NULL object.  No object means
297          * no pager means an unrecoverable kernel fault.
298          */
299         if (fs.first_object == NULL) {
300                 panic("vm_fault: unrecoverable fault at %p in entry %p",
301                         (void *)vaddr, fs.entry);
302         }
303
304         /*
305          * Make a reference to this object to prevent its disposal while we
306          * are messing with it.  Once we have the reference, the map is free
307          * to be diddled.  Since objects reference their shadows (and copies),
308          * they will stay around as well.
309          *
310          * Bump the paging-in-progress count to prevent size changes (e.g.
311          * truncation operations) during I/O.  This must be done after
312          * obtaining the vnode lock in order to avoid possible deadlocks.
313          */
314         vm_object_reference(fs.first_object);
315         fs.vp = vnode_pager_lock(fs.first_object);
316         vm_object_pip_add(fs.first_object, 1);
317
318         fs.lookup_still_valid = TRUE;
319         fs.first_m = NULL;
320         fs.object = fs.first_object;    /* so unlock_and_deallocate works */
321
322         /*
323          * If the entry is wired we cannot change the page protection.
324          */
325         if (fs.wired)
326                 fault_type = fs.first_prot;
327
328         /*
329          * The page we want is at (first_object, first_pindex), but if the
330          * vm_map_entry is VM_MAPTYPE_VPAGETABLE we have to traverse the
331          * page table to figure out the actual pindex.
332          *
333          * NOTE!  DEVELOPMENT IN PROGRESS, THIS IS AN INITIAL IMPLEMENTATION
334          * ONLY
335          */
336         if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
337                 result = vm_fault_vpagetable(&fs, &first_pindex,
338                                              fs.entry->aux.master_pde,
339                                              fault_type);
340                 if (result == KERN_TRY_AGAIN)
341                         goto RetryFault;
342                 if (result != KERN_SUCCESS)
343                         return (result);
344         }
345
346         /*
347          * Now we have the actual (object, pindex), fault in the page.  If
348          * vm_fault_object() fails it will unlock and deallocate the FS
349          * data.   If it succeeds everything remains locked and fs->object
350          * will have an additinal PIP count if it is not equal to
351          * fs->first_object
352          *
353          * vm_fault_object will set fs->prot for the pmap operation.  It is
354          * allowed to set VM_PROT_WRITE if fault_type == VM_PROT_READ if the
355          * page can be safely written.  However, it will force a read-only
356          * mapping for a read fault if the memory is managed by a virtual
357          * page table.
358          */
359         result = vm_fault_object(&fs, first_pindex, fault_type);
360
361         if (result == KERN_TRY_AGAIN)
362                 goto RetryFault;
363         if (result != KERN_SUCCESS)
364                 return (result);
365
366         /*
367          * On success vm_fault_object() does not unlock or deallocate, and fs.m
368          * will contain a busied page.
369          *
370          * Enter the page into the pmap and do pmap-related adjustments.
371          */
372         unlock_things(&fs);
373         pmap_enter(fs.map->pmap, vaddr, fs.m, fs.prot, fs.wired);
374
375         if (((fs.fault_flags & VM_FAULT_WIRE_MASK) == 0) && (fs.wired == 0)) {
376                 pmap_prefault(fs.map->pmap, vaddr, fs.entry);
377         }
378
379         vm_page_flag_clear(fs.m, PG_ZERO);
380         vm_page_flag_set(fs.m, PG_MAPPED|PG_REFERENCED);
381
382         /*
383          * If the page is not wired down, then put it where the pageout daemon
384          * can find it.
385          */
386         if (fs.fault_flags & VM_FAULT_WIRE_MASK) {
387                 if (fs.wired)
388                         vm_page_wire(fs.m);
389                 else
390                         vm_page_unwire(fs.m, 1);
391         } else {
392                 vm_page_activate(fs.m);
393         }
394
395         if (curthread->td_lwp) {
396                 if (fs.hardfault) {
397                         curthread->td_lwp->lwp_ru.ru_majflt++;
398                 } else {
399                         curthread->td_lwp->lwp_ru.ru_minflt++;
400                 }
401         }
402
403         /*
404          * Unlock everything, and return
405          */
406         vm_page_wakeup(fs.m);
407         vm_object_deallocate(fs.first_object);
408
409         return (KERN_SUCCESS);
410 }
411
412 /*
413  * Fault in the specified virtual address in the current process map, 
414  * returning a held VM page or NULL.  See vm_fault_page() for more 
415  * information.
416  */
417 vm_page_t
418 vm_fault_page_quick(vm_offset_t va, vm_prot_t fault_type, int *errorp)
419 {
420         vm_page_t m;
421
422         m = vm_fault_page(&curproc->p_vmspace->vm_map, va, 
423                           fault_type, VM_FAULT_NORMAL, errorp);
424         return(m);
425 }
426
427 /*
428  * Fault in the specified virtual address in the specified map, doing all
429  * necessary manipulation of the object store and all necessary I/O.  Return
430  * a held VM page or NULL, and set *errorp.  The related pmap is not
431  * updated.
432  *
433  * The returned page will be properly dirtied if VM_PROT_WRITE was specified,
434  * and marked PG_REFERENCED as well.
435  */
436 vm_page_t
437 vm_fault_page(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
438               int fault_flags, int *errorp)
439 {
440         int result;
441         vm_pindex_t first_pindex;
442         struct faultstate fs;
443
444         mycpu->gd_cnt.v_vm_faults++;
445
446         fs.didlimit = 0;
447         fs.hardfault = 0;
448         fs.fault_flags = fault_flags;
449         KKASSERT((fault_flags & VM_FAULT_WIRE_MASK) == 0);
450
451 RetryFault:
452         /*
453          * Find the vm_map_entry representing the backing store and resolve
454          * the top level object and page index.  This may have the side
455          * effect of executing a copy-on-write on the map entry and/or
456          * creating a shadow object, but will not COW any actual VM pages.
457          *
458          * On success fs.map is left read-locked and various other fields 
459          * are initialized but not otherwise referenced or locked.
460          *
461          * NOTE!  vm_map_lookup will upgrade the fault_type to VM_FAULT_WRITE
462          * if the map entry is a virtual page table and also writable,
463          * so we can set the 'A'accessed bit in the virtual page table entry.
464          */
465         fs.map = map;
466         result = vm_map_lookup(&fs.map, vaddr, fault_type,
467                                &fs.entry, &fs.first_object,
468                                &first_pindex, &fs.first_prot, &fs.wired);
469
470         if (result != KERN_SUCCESS) {
471                 *errorp = result;
472                 return (NULL);
473         }
474
475         /*
476          * fs.map is read-locked
477          *
478          * Misc checks.  Save the map generation number to detect races.
479          */
480         fs.map_generation = fs.map->timestamp;
481
482         if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
483                 panic("vm_fault: fault on nofault entry, addr: %lx",
484                     (u_long)vaddr);
485         }
486
487         /*
488          * A system map entry may return a NULL object.  No object means
489          * no pager means an unrecoverable kernel fault.
490          */
491         if (fs.first_object == NULL) {
492                 panic("vm_fault: unrecoverable fault at %p in entry %p",
493                         (void *)vaddr, fs.entry);
494         }
495
496         /*
497          * Make a reference to this object to prevent its disposal while we
498          * are messing with it.  Once we have the reference, the map is free
499          * to be diddled.  Since objects reference their shadows (and copies),
500          * they will stay around as well.
501          *
502          * Bump the paging-in-progress count to prevent size changes (e.g.
503          * truncation operations) during I/O.  This must be done after
504          * obtaining the vnode lock in order to avoid possible deadlocks.
505          */
506         vm_object_reference(fs.first_object);
507         fs.vp = vnode_pager_lock(fs.first_object);
508         vm_object_pip_add(fs.first_object, 1);
509
510         fs.lookup_still_valid = TRUE;
511         fs.first_m = NULL;
512         fs.object = fs.first_object;    /* so unlock_and_deallocate works */
513
514         /*
515          * If the entry is wired we cannot change the page protection.
516          */
517         if (fs.wired)
518                 fault_type = fs.first_prot;
519
520         /*
521          * The page we want is at (first_object, first_pindex), but if the
522          * vm_map_entry is VM_MAPTYPE_VPAGETABLE we have to traverse the
523          * page table to figure out the actual pindex.
524          *
525          * NOTE!  DEVELOPMENT IN PROGRESS, THIS IS AN INITIAL IMPLEMENTATION
526          * ONLY
527          */
528         if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
529                 result = vm_fault_vpagetable(&fs, &first_pindex,
530                                              fs.entry->aux.master_pde,
531                                              fault_type);
532                 if (result == KERN_TRY_AGAIN)
533                         goto RetryFault;
534                 if (result != KERN_SUCCESS) {
535                         *errorp = result;
536                         return (NULL);
537                 }
538         }
539
540         /*
541          * Now we have the actual (object, pindex), fault in the page.  If
542          * vm_fault_object() fails it will unlock and deallocate the FS
543          * data.   If it succeeds everything remains locked and fs->object
544          * will have an additinal PIP count if it is not equal to
545          * fs->first_object
546          */
547         result = vm_fault_object(&fs, first_pindex, fault_type);
548
549         if (result == KERN_TRY_AGAIN)
550                 goto RetryFault;
551         if (result != KERN_SUCCESS) {
552                 *errorp = result;
553                 return(NULL);
554         }
555
556         /*
557          * On success vm_fault_object() does not unlock or deallocate, and fs.m
558          * will contain a busied page.
559          */
560         unlock_things(&fs);
561
562         /*
563          * Return a held page.  We are not doing any pmap manipulation so do
564          * not set PG_MAPPED.  However, adjust the page flags according to
565          * the fault type because the caller may not use a managed pmapping
566          * (so we don't want to lose the fact that the page will be dirtied
567          * if a write fault was specified).
568          */
569         vm_page_hold(fs.m);
570         vm_page_flag_clear(fs.m, PG_ZERO);
571         if (fault_type & VM_PROT_WRITE)
572                 vm_page_dirty(fs.m);
573
574         /*
575          * Update the pmap.  We really only have to do this if a COW
576          * occured to replace the read-only page with the new page.  For
577          * now just do it unconditionally. XXX
578          */
579         pmap_enter(fs.map->pmap, vaddr, fs.m, fs.prot, fs.wired);
580         vm_page_flag_set(fs.m, PG_REFERENCED|PG_MAPPED);
581
582         /*
583          * Unbusy the page by activating it.  It remains held and will not
584          * be reclaimed.
585          */
586         vm_page_activate(fs.m);
587
588         if (curthread->td_lwp) {
589                 if (fs.hardfault) {
590                         curthread->td_lwp->lwp_ru.ru_majflt++;
591                 } else {
592                         curthread->td_lwp->lwp_ru.ru_minflt++;
593                 }
594         }
595
596         /*
597          * Unlock everything, and return the held page.
598          */
599         vm_page_wakeup(fs.m);
600         vm_object_deallocate(fs.first_object);
601
602         *errorp = 0;
603         return(fs.m);
604 }
605
606 /*
607  * Translate the virtual page number (first_pindex) that is relative
608  * to the address space into a logical page number that is relative to the
609  * backing object.  Use the virtual page table pointed to by (vpte).
610  *
611  * This implements an N-level page table.  Any level can terminate the
612  * scan by setting VPTE_PS.   A linear mapping is accomplished by setting
613  * VPTE_PS in the master page directory entry set via mcontrol(MADV_SETMAP).
614  */
615 static
616 int
617 vm_fault_vpagetable(struct faultstate *fs, vm_pindex_t *pindex,
618                     vpte_t vpte, int fault_type)
619 {
620         struct sf_buf *sf;
621         int vshift = 32 - PAGE_SHIFT;   /* page index bits remaining */
622         int result = KERN_SUCCESS;
623         vpte_t *ptep;
624
625         for (;;) {
626                 /*
627                  * We cannot proceed if the vpte is not valid, not readable
628                  * for a read fault, or not writable for a write fault.
629                  */
630                 if ((vpte & VPTE_V) == 0) {
631                         unlock_and_deallocate(fs);
632                         return (KERN_FAILURE);
633                 }
634                 if ((fault_type & VM_PROT_READ) && (vpte & VPTE_R) == 0) {
635                         unlock_and_deallocate(fs);
636                         return (KERN_FAILURE);
637                 }
638                 if ((fault_type & VM_PROT_WRITE) && (vpte & VPTE_W) == 0) {
639                         unlock_and_deallocate(fs);
640                         return (KERN_FAILURE);
641                 }
642                 if ((vpte & VPTE_PS) || vshift == 0)
643                         break;
644                 KKASSERT(vshift >= VPTE_PAGE_BITS);
645
646                 /*
647                  * Get the page table page.  Nominally we only read the page
648                  * table, but since we are actively setting VPTE_M and VPTE_A,
649                  * tell vm_fault_object() that we are writing it. 
650                  *
651                  * There is currently no real need to optimize this.
652                  */
653                 result = vm_fault_object(fs, vpte >> PAGE_SHIFT,
654                                          VM_PROT_READ|VM_PROT_WRITE);
655                 if (result != KERN_SUCCESS)
656                         return (result);
657
658                 /*
659                  * Process the returned fs.m and look up the page table
660                  * entry in the page table page.
661                  */
662                 vshift -= VPTE_PAGE_BITS;
663                 sf = sf_buf_alloc(fs->m, SFB_CPUPRIVATE);
664                 ptep = ((vpte_t *)sf_buf_kva(sf) +
665                         ((*pindex >> vshift) & VPTE_PAGE_MASK));
666                 vpte = *ptep;
667
668                 /*
669                  * Page table write-back.  If the vpte is valid for the
670                  * requested operation, do a write-back to the page table.
671                  *
672                  * XXX VPTE_M is not set properly for page directory pages.
673                  * It doesn't get set in the page directory if the page table
674                  * is modified during a read access.
675                  */
676                 if ((fault_type & VM_PROT_WRITE) && (vpte & VPTE_V) &&
677                     (vpte & VPTE_W)) {
678                         if ((vpte & (VPTE_M|VPTE_A)) != (VPTE_M|VPTE_A)) {
679                                 atomic_set_int(ptep, VPTE_M|VPTE_A);
680                                 vm_page_dirty(fs->m);
681                         }
682                 }
683                 if ((fault_type & VM_PROT_READ) && (vpte & VPTE_V) &&
684                     (vpte & VPTE_R)) {
685                         if ((vpte & VPTE_A) == 0) {
686                                 atomic_set_int(ptep, VPTE_A);
687                                 vm_page_dirty(fs->m);
688                         }
689                 }
690                 sf_buf_free(sf);
691                 vm_page_flag_set(fs->m, PG_REFERENCED);
692                 vm_page_activate(fs->m);
693                 vm_page_wakeup(fs->m);
694                 cleanup_successful_fault(fs);
695         }
696         /*
697          * Combine remaining address bits with the vpte.
698          */
699         *pindex = (vpte >> PAGE_SHIFT) +
700                   (*pindex & ((1 << vshift) - 1));
701         return (KERN_SUCCESS);
702 }
703
704
705 /*
706  * Do all operations required to fault-in (fs.first_object, pindex).  Run
707  * through the shadow chain as necessary and do required COW or virtual
708  * copy operations.  The caller has already fully resolved the vm_map_entry
709  * and, if appropriate, has created a copy-on-write layer.  All we need to
710  * do is iterate the object chain.
711  *
712  * On failure (fs) is unlocked and deallocated and the caller may return or
713  * retry depending on the failure code.  On success (fs) is NOT unlocked or
714  * deallocated, fs.m will contained a resolved, busied page, and fs.object
715  * will have an additional PIP count if it is not equal to fs.first_object.
716  */
717 static
718 int
719 vm_fault_object(struct faultstate *fs,
720                 vm_pindex_t first_pindex, vm_prot_t fault_type)
721 {
722         vm_object_t next_object;
723         vm_page_t marray[VM_FAULT_READ];
724         vm_pindex_t pindex;
725         int faultcount;
726
727         fs->prot = fs->first_prot;
728         fs->object = fs->first_object;
729         pindex = first_pindex;
730
731         /* 
732          * If a read fault occurs we try to make the page writable if
733          * possible.  There are three cases where we cannot make the
734          * page mapping writable:
735          *
736          * (1) The mapping is read-only or the VM object is read-only,
737          *     fs->prot above will simply not have VM_PROT_WRITE set.
738          *
739          * (2) If the mapping is a virtual page table we need to be able
740          *     to detect writes so we can set VPTE_M.
741          *
742          * (3) If the VM page is read-only or copy-on-write, upgrading would
743          *     just result in an unnecessary COW fault.
744          *
745          * VM_PROT_VPAGED is set if faulting via a virtual page table and
746          * causes adjustments to the 'M'odify bit to also turn off write
747          * access to force a re-fault.
748          */
749         if (fs->entry->maptype == VM_MAPTYPE_VPAGETABLE) {
750                 if ((fault_type & VM_PROT_WRITE) == 0)
751                         fs->prot &= ~VM_PROT_WRITE;
752         }
753
754         for (;;) {
755                 /*
756                  * If the object is dead, we stop here
757                  */
758                 if (fs->object->flags & OBJ_DEAD) {
759                         unlock_and_deallocate(fs);
760                         return (KERN_PROTECTION_FAILURE);
761                 }
762
763                 /*
764                  * See if page is resident.  spl protection is required
765                  * to avoid an interrupt unbusy/free race against our
766                  * lookup.  We must hold the protection through a page
767                  * allocation or busy.
768                  */
769                 crit_enter();
770                 fs->m = vm_page_lookup(fs->object, pindex);
771                 if (fs->m != NULL) {
772                         int queue;
773                         /*
774                          * Wait/Retry if the page is busy.  We have to do this
775                          * if the page is busy via either PG_BUSY or 
776                          * vm_page_t->busy because the vm_pager may be using
777                          * vm_page_t->busy for pageouts ( and even pageins if
778                          * it is the vnode pager ), and we could end up trying
779                          * to pagein and pageout the same page simultaneously.
780                          *
781                          * We can theoretically allow the busy case on a read
782                          * fault if the page is marked valid, but since such
783                          * pages are typically already pmap'd, putting that
784                          * special case in might be more effort then it is 
785                          * worth.  We cannot under any circumstances mess
786                          * around with a vm_page_t->busy page except, perhaps,
787                          * to pmap it.
788                          */
789                         if ((fs->m->flags & PG_BUSY) || fs->m->busy) {
790                                 unlock_things(fs);
791                                 vm_page_sleep_busy(fs->m, TRUE, "vmpfw");
792                                 mycpu->gd_cnt.v_intrans++;
793                                 vm_object_deallocate(fs->first_object);
794                                 crit_exit();
795                                 return (KERN_TRY_AGAIN);
796                         }
797
798                         /*
799                          * If reactivating a page from PQ_CACHE we may have
800                          * to rate-limit.
801                          */
802                         queue = fs->m->queue;
803                         vm_page_unqueue_nowakeup(fs->m);
804
805                         if ((queue - fs->m->pc) == PQ_CACHE && 
806                             vm_page_count_severe()) {
807                                 vm_page_activate(fs->m);
808                                 unlock_and_deallocate(fs);
809                                 vm_waitpfault();
810                                 crit_exit();
811                                 return (KERN_TRY_AGAIN);
812                         }
813
814                         /*
815                          * Mark page busy for other processes, and the 
816                          * pagedaemon.  If it still isn't completely valid
817                          * (readable), jump to readrest, else we found the
818                          * page and can return.
819                          *
820                          * We can release the spl once we have marked the
821                          * page busy.
822                          */
823                         vm_page_busy(fs->m);
824                         crit_exit();
825
826                         if (((fs->m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) &&
827                             fs->m->object != &kernel_object) {
828                                 goto readrest;
829                         }
830                         break; /* break to PAGE HAS BEEN FOUND */
831                 }
832
833                 /*
834                  * Page is not resident, If this is the search termination
835                  * or the pager might contain the page, allocate a new page.
836                  *
837                  * NOTE: We are still in a critical section.
838                  */
839                 if (TRYPAGER(fs) || fs->object == fs->first_object) {
840                         /*
841                          * If the page is beyond the object size we fail
842                          */
843                         if (pindex >= fs->object->size) {
844                                 crit_exit();
845                                 unlock_and_deallocate(fs);
846                                 return (KERN_PROTECTION_FAILURE);
847                         }
848
849                         /*
850                          * Ratelimit.
851                          */
852                         if (fs->didlimit == 0 && curproc != NULL) {
853                                 int limticks;
854
855                                 limticks = vm_fault_ratelimit(curproc->p_vmspace);
856                                 if (limticks) {
857                                         crit_exit();
858                                         unlock_and_deallocate(fs);
859                                         tsleep(curproc, 0, "vmrate", limticks);
860                                         fs->didlimit = 1;
861                                         return (KERN_TRY_AGAIN);
862                                 }
863                         }
864
865                         /*
866                          * Allocate a new page for this object/offset pair.
867                          */
868                         fs->m = NULL;
869                         if (!vm_page_count_severe()) {
870                                 fs->m = vm_page_alloc(fs->object, pindex,
871                                     (fs->vp || fs->object->backing_object) ? VM_ALLOC_NORMAL : VM_ALLOC_NORMAL | VM_ALLOC_ZERO);
872                         }
873                         if (fs->m == NULL) {
874                                 crit_exit();
875                                 unlock_and_deallocate(fs);
876                                 vm_waitpfault();
877                                 return (KERN_TRY_AGAIN);
878                         }
879                 }
880                 crit_exit();
881
882 readrest:
883                 /*
884                  * We have found a valid page or we have allocated a new page.
885                  * The page thus may not be valid or may not be entirely 
886                  * valid.
887                  *
888                  * Attempt to fault-in the page if there is a chance that the
889                  * pager has it, and potentially fault in additional pages
890                  * at the same time.
891                  *
892                  * We are NOT in splvm here and if TRYPAGER is true then
893                  * fs.m will be non-NULL and will be PG_BUSY for us.
894                  */
895
896                 if (TRYPAGER(fs)) {
897                         int rv;
898                         int reqpage;
899                         int ahead, behind;
900                         u_char behavior = vm_map_entry_behavior(fs->entry);
901
902                         if (behavior == MAP_ENTRY_BEHAV_RANDOM) {
903                                 ahead = 0;
904                                 behind = 0;
905                         } else {
906                                 behind = pindex;
907                                 if (behind > VM_FAULT_READ_BEHIND)
908                                         behind = VM_FAULT_READ_BEHIND;
909
910                                 ahead = fs->object->size - pindex;
911                                 if (ahead < 1)
912                                         ahead = 1;
913                                 if (ahead > VM_FAULT_READ_AHEAD)
914                                         ahead = VM_FAULT_READ_AHEAD;
915                         }
916
917                         if ((fs->first_object->type != OBJT_DEVICE) &&
918                             (behavior == MAP_ENTRY_BEHAV_SEQUENTIAL ||
919                                 (behavior != MAP_ENTRY_BEHAV_RANDOM &&
920                                 pindex >= fs->entry->lastr &&
921                                 pindex < fs->entry->lastr + VM_FAULT_READ))
922                         ) {
923                                 vm_pindex_t firstpindex, tmppindex;
924
925                                 if (first_pindex < 2 * VM_FAULT_READ)
926                                         firstpindex = 0;
927                                 else
928                                         firstpindex = first_pindex - 2 * VM_FAULT_READ;
929
930                                 /*
931                                  * note: partially valid pages cannot be 
932                                  * included in the lookahead - NFS piecemeal
933                                  * writes will barf on it badly.
934                                  *
935                                  * spl protection is required to avoid races
936                                  * between the lookup and an interrupt
937                                  * unbusy/free sequence occuring prior to
938                                  * our busy check.
939                                  */
940                                 crit_enter();
941                                 for (tmppindex = first_pindex - 1;
942                                     tmppindex >= firstpindex;
943                                     --tmppindex
944                                 ) {
945                                         vm_page_t mt;
946
947                                         mt = vm_page_lookup(fs->first_object, tmppindex);
948                                         if (mt == NULL || (mt->valid != VM_PAGE_BITS_ALL))
949                                                 break;
950                                         if (mt->busy ||
951                                                 (mt->flags & (PG_BUSY | PG_FICTITIOUS | PG_UNMANAGED)) ||
952                                                 mt->hold_count ||
953                                                 mt->wire_count) 
954                                                 continue;
955                                         if (mt->dirty == 0)
956                                                 vm_page_test_dirty(mt);
957                                         if (mt->dirty) {
958                                                 vm_page_protect(mt, VM_PROT_NONE);
959                                                 vm_page_deactivate(mt);
960                                         } else {
961                                                 vm_page_cache(mt);
962                                         }
963                                 }
964                                 crit_exit();
965
966                                 ahead += behind;
967                                 behind = 0;
968                         }
969
970                         /*
971                          * now we find out if any other pages should be paged
972                          * in at this time this routine checks to see if the
973                          * pages surrounding this fault reside in the same
974                          * object as the page for this fault.  If they do,
975                          * then they are faulted in also into the object.  The
976                          * array "marray" returned contains an array of
977                          * vm_page_t structs where one of them is the
978                          * vm_page_t passed to the routine.  The reqpage
979                          * return value is the index into the marray for the
980                          * vm_page_t passed to the routine.
981                          *
982                          * fs.m plus the additional pages are PG_BUSY'd.
983                          */
984                         faultcount = vm_fault_additional_pages(
985                             fs->m, behind, ahead, marray, &reqpage);
986
987                         /*
988                          * update lastr imperfectly (we do not know how much
989                          * getpages will actually read), but good enough.
990                          */
991                         fs->entry->lastr = pindex + faultcount - behind;
992
993                         /*
994                          * Call the pager to retrieve the data, if any, after
995                          * releasing the lock on the map.  We hold a ref on
996                          * fs.object and the pages are PG_BUSY'd.
997                          */
998                         unlock_map(fs);
999
1000                         if (faultcount) {
1001                                 rv = vm_pager_get_pages(fs->object, marray, 
1002                                                         faultcount, reqpage);
1003                         } else {
1004                                 rv = VM_PAGER_FAIL;
1005                         }
1006
1007                         if (rv == VM_PAGER_OK) {
1008                                 /*
1009                                  * Found the page. Leave it busy while we play
1010                                  * with it.
1011                                  */
1012
1013                                 /*
1014                                  * Relookup in case pager changed page. Pager
1015                                  * is responsible for disposition of old page
1016                                  * if moved.
1017                                  *
1018                                  * XXX other code segments do relookups too.
1019                                  * It's a bad abstraction that needs to be
1020                                  * fixed/removed.
1021                                  */
1022                                 fs->m = vm_page_lookup(fs->object, pindex);
1023                                 if (fs->m == NULL) {
1024                                         unlock_and_deallocate(fs);
1025                                         return (KERN_TRY_AGAIN);
1026                                 }
1027
1028                                 ++fs->hardfault;
1029                                 break; /* break to PAGE HAS BEEN FOUND */
1030                         }
1031
1032                         /*
1033                          * Remove the bogus page (which does not exist at this
1034                          * object/offset); before doing so, we must get back
1035                          * our object lock to preserve our invariant.
1036                          *
1037                          * Also wake up any other process that may want to bring
1038                          * in this page.
1039                          *
1040                          * If this is the top-level object, we must leave the
1041                          * busy page to prevent another process from rushing
1042                          * past us, and inserting the page in that object at
1043                          * the same time that we are.
1044                          */
1045                         if (rv == VM_PAGER_ERROR) {
1046                                 if (curproc)
1047                                         kprintf("vm_fault: pager read error, pid %d (%s)\n", curproc->p_pid, curproc->p_comm);
1048                                 else
1049                                         kprintf("vm_fault: pager read error, thread %p (%s)\n", curthread, curproc->p_comm);
1050                         }
1051                         /*
1052                          * Data outside the range of the pager or an I/O error
1053                          */
1054                         /*
1055                          * XXX - the check for kernel_map is a kludge to work
1056                          * around having the machine panic on a kernel space
1057                          * fault w/ I/O error.
1058                          */
1059                         if (((fs->map != &kernel_map) && (rv == VM_PAGER_ERROR)) ||
1060                                 (rv == VM_PAGER_BAD)) {
1061                                 vm_page_free(fs->m);
1062                                 fs->m = NULL;
1063                                 unlock_and_deallocate(fs);
1064                                 if (rv == VM_PAGER_ERROR)
1065                                         return (KERN_FAILURE);
1066                                 else
1067                                         return (KERN_PROTECTION_FAILURE);
1068                                 /* NOT REACHED */
1069                         }
1070                         if (fs->object != fs->first_object) {
1071                                 vm_page_free(fs->m);
1072                                 fs->m = NULL;
1073                                 /*
1074                                  * XXX - we cannot just fall out at this
1075                                  * point, m has been freed and is invalid!
1076                                  */
1077                         }
1078                 }
1079
1080                 /*
1081                  * We get here if the object has a default pager (or unwiring) 
1082                  * or the pager doesn't have the page.
1083                  */
1084                 if (fs->object == fs->first_object)
1085                         fs->first_m = fs->m;
1086
1087                 /*
1088                  * Move on to the next object.  Lock the next object before
1089                  * unlocking the current one.
1090                  */
1091                 pindex += OFF_TO_IDX(fs->object->backing_object_offset);
1092                 next_object = fs->object->backing_object;
1093                 if (next_object == NULL) {
1094                         /*
1095                          * If there's no object left, fill the page in the top
1096                          * object with zeros.
1097                          */
1098                         if (fs->object != fs->first_object) {
1099                                 vm_object_pip_wakeup(fs->object);
1100
1101                                 fs->object = fs->first_object;
1102                                 pindex = first_pindex;
1103                                 fs->m = fs->first_m;
1104                         }
1105                         fs->first_m = NULL;
1106
1107                         /*
1108                          * Zero the page if necessary and mark it valid.
1109                          */
1110                         if ((fs->m->flags & PG_ZERO) == 0) {
1111                                 vm_page_zero_fill(fs->m);
1112                         } else {
1113                                 mycpu->gd_cnt.v_ozfod++;
1114                         }
1115                         mycpu->gd_cnt.v_zfod++;
1116                         fs->m->valid = VM_PAGE_BITS_ALL;
1117                         break;  /* break to PAGE HAS BEEN FOUND */
1118                 } else {
1119                         if (fs->object != fs->first_object) {
1120                                 vm_object_pip_wakeup(fs->object);
1121                         }
1122                         KASSERT(fs->object != next_object, ("object loop %p", next_object));
1123                         fs->object = next_object;
1124                         vm_object_pip_add(fs->object, 1);
1125                 }
1126         }
1127
1128         KASSERT((fs->m->flags & PG_BUSY) != 0,
1129                 ("vm_fault: not busy after main loop"));
1130
1131         /*
1132          * PAGE HAS BEEN FOUND. [Loop invariant still holds -- the object lock
1133          * is held.]
1134          */
1135
1136         /*
1137          * If the page is being written, but isn't already owned by the
1138          * top-level object, we have to copy it into a new page owned by the
1139          * top-level object.
1140          */
1141         if (fs->object != fs->first_object) {
1142                 /*
1143                  * We only really need to copy if we want to write it.
1144                  */
1145                 if (fault_type & VM_PROT_WRITE) {
1146                         /*
1147                          * This allows pages to be virtually copied from a 
1148                          * backing_object into the first_object, where the 
1149                          * backing object has no other refs to it, and cannot
1150                          * gain any more refs.  Instead of a bcopy, we just 
1151                          * move the page from the backing object to the 
1152                          * first object.  Note that we must mark the page 
1153                          * dirty in the first object so that it will go out 
1154                          * to swap when needed.
1155                          */
1156                         if (fs->map_generation == fs->map->timestamp &&
1157                                 /*
1158                                  * Only one shadow object
1159                                  */
1160                                 (fs->object->shadow_count == 1) &&
1161                                 /*
1162                                  * No COW refs, except us
1163                                  */
1164                                 (fs->object->ref_count == 1) &&
1165                                 /*
1166                                  * No one else can look this object up
1167                                  */
1168                                 (fs->object->handle == NULL) &&
1169                                 /*
1170                                  * No other ways to look the object up
1171                                  */
1172                                 ((fs->object->type == OBJT_DEFAULT) ||
1173                                  (fs->object->type == OBJT_SWAP)) &&
1174                                 /*
1175                                  * We don't chase down the shadow chain
1176                                  */
1177                                 (fs->object == fs->first_object->backing_object) &&
1178
1179                                 /*
1180                                  * grab the lock if we need to
1181                                  */
1182                                 (fs->lookup_still_valid ||
1183                                  lockmgr(&fs->map->lock, LK_EXCLUSIVE|LK_NOWAIT) == 0)
1184                             ) {
1185                                 
1186                                 fs->lookup_still_valid = 1;
1187                                 /*
1188                                  * get rid of the unnecessary page
1189                                  */
1190                                 vm_page_protect(fs->first_m, VM_PROT_NONE);
1191                                 vm_page_free(fs->first_m);
1192                                 fs->first_m = NULL;
1193
1194                                 /*
1195                                  * grab the page and put it into the 
1196                                  * process'es object.  The page is 
1197                                  * automatically made dirty.
1198                                  */
1199                                 vm_page_rename(fs->m, fs->first_object, first_pindex);
1200                                 fs->first_m = fs->m;
1201                                 vm_page_busy(fs->first_m);
1202                                 fs->m = NULL;
1203                                 mycpu->gd_cnt.v_cow_optim++;
1204                         } else {
1205                                 /*
1206                                  * Oh, well, lets copy it.
1207                                  */
1208                                 vm_page_copy(fs->m, fs->first_m);
1209                         }
1210
1211                         if (fs->m) {
1212                                 /*
1213                                  * We no longer need the old page or object.
1214                                  */
1215                                 release_page(fs);
1216                         }
1217
1218                         /*
1219                          * fs->object != fs->first_object due to above 
1220                          * conditional
1221                          */
1222                         vm_object_pip_wakeup(fs->object);
1223
1224                         /*
1225                          * Only use the new page below...
1226                          */
1227
1228                         mycpu->gd_cnt.v_cow_faults++;
1229                         fs->m = fs->first_m;
1230                         fs->object = fs->first_object;
1231                         pindex = first_pindex;
1232                 } else {
1233                         /*
1234                          * If it wasn't a write fault avoid having to copy
1235                          * the page by mapping it read-only.
1236                          */
1237                         fs->prot &= ~VM_PROT_WRITE;
1238                 }
1239         }
1240
1241         /*
1242          * We may have had to unlock a map to do I/O.  If we did then
1243          * lookup_still_valid will be FALSE.  If the map generation count
1244          * also changed then all sorts of things could have happened while
1245          * we were doing the I/O and we need to retry.
1246          */
1247
1248         if (!fs->lookup_still_valid &&
1249             (fs->map->timestamp != fs->map_generation)) {
1250                 release_page(fs);
1251                 unlock_and_deallocate(fs);
1252                 return (KERN_TRY_AGAIN);
1253         }
1254
1255         /*
1256          * Put this page into the physical map. We had to do the unlock above
1257          * because pmap_enter may cause other faults.   We don't put the page
1258          * back on the active queue until later so that the page-out daemon
1259          * won't find us (yet).
1260          */
1261         if (fs->prot & VM_PROT_WRITE) {
1262                 vm_page_flag_set(fs->m, PG_WRITEABLE);
1263                 vm_object_set_writeable_dirty(fs->m->object);
1264
1265                 /*
1266                  * If the fault is a write, we know that this page is being
1267                  * written NOW so dirty it explicitly to save on 
1268                  * pmap_is_modified() calls later.
1269                  *
1270                  * If this is a NOSYNC mmap we do not want to set PG_NOSYNC
1271                  * if the page is already dirty to prevent data written with
1272                  * the expectation of being synced from not being synced.
1273                  * Likewise if this entry does not request NOSYNC then make
1274                  * sure the page isn't marked NOSYNC.  Applications sharing
1275                  * data should use the same flags to avoid ping ponging.
1276                  *
1277                  * Also tell the backing pager, if any, that it should remove
1278                  * any swap backing since the page is now dirty.
1279                  */
1280                 if (fs->entry->eflags & MAP_ENTRY_NOSYNC) {
1281                         if (fs->m->dirty == 0)
1282                                 vm_page_flag_set(fs->m, PG_NOSYNC);
1283                 } else {
1284                         vm_page_flag_clear(fs->m, PG_NOSYNC);
1285                 }
1286                 if (fs->fault_flags & VM_FAULT_DIRTY) {
1287                         crit_enter();
1288                         vm_page_dirty(fs->m);
1289                         vm_pager_page_unswapped(fs->m);
1290                         crit_exit();
1291                 }
1292         }
1293
1294         /*
1295          * Page had better still be busy.  We are still locked up and 
1296          * fs->object will have another PIP reference if it is not equal
1297          * to fs->first_object.
1298          */
1299         KASSERT(fs->m->flags & PG_BUSY,
1300                 ("vm_fault: page %p not busy!", fs->m));
1301
1302         /*
1303          * Sanity check: page must be completely valid or it is not fit to
1304          * map into user space.  vm_pager_get_pages() ensures this.
1305          */
1306         if (fs->m->valid != VM_PAGE_BITS_ALL) {
1307                 vm_page_zero_invalid(fs->m, TRUE);
1308                 kprintf("Warning: page %p partially invalid on fault\n", fs->m);
1309         }
1310
1311         return (KERN_SUCCESS);
1312 }
1313
1314 /*
1315  * quick version of vm_fault
1316  */
1317 int
1318 vm_fault_quick(caddr_t v, int prot)
1319 {
1320         int r;
1321
1322         if (prot & VM_PROT_WRITE)
1323                 r = subyte(v, fubyte(v));
1324         else
1325                 r = fubyte(v);
1326         return(r);
1327 }
1328
1329 /*
1330  * Wire down a range of virtual addresses in a map.  The entry in question
1331  * should be marked in-transition and the map must be locked.  We must
1332  * release the map temporarily while faulting-in the page to avoid a
1333  * deadlock.  Note that the entry may be clipped while we are blocked but
1334  * will never be freed.
1335  */
1336 int
1337 vm_fault_wire(vm_map_t map, vm_map_entry_t entry, boolean_t user_wire)
1338 {
1339         boolean_t fictitious;
1340         vm_offset_t start;
1341         vm_offset_t end;
1342         vm_offset_t va;
1343         vm_paddr_t pa;
1344         pmap_t pmap;
1345         int rv;
1346
1347         pmap = vm_map_pmap(map);
1348         start = entry->start;
1349         end = entry->end;
1350         fictitious = entry->object.vm_object &&
1351                         (entry->object.vm_object->type == OBJT_DEVICE);
1352
1353         vm_map_unlock(map);
1354         map->timestamp++;
1355
1356         /*
1357          * We simulate a fault to get the page and enter it in the physical
1358          * map.
1359          */
1360         for (va = start; va < end; va += PAGE_SIZE) {
1361                 if (user_wire) {
1362                         rv = vm_fault(map, va, VM_PROT_READ, 
1363                                         VM_FAULT_USER_WIRE);
1364                 } else {
1365                         rv = vm_fault(map, va, VM_PROT_READ|VM_PROT_WRITE,
1366                                         VM_FAULT_CHANGE_WIRING);
1367                 }
1368                 if (rv) {
1369                         while (va > start) {
1370                                 va -= PAGE_SIZE;
1371                                 if ((pa = pmap_extract(pmap, va)) == 0)
1372                                         continue;
1373                                 pmap_change_wiring(pmap, va, FALSE);
1374                                 if (!fictitious)
1375                                         vm_page_unwire(PHYS_TO_VM_PAGE(pa), 1);
1376                         }
1377                         vm_map_lock(map);
1378                         return (rv);
1379                 }
1380         }
1381         vm_map_lock(map);
1382         return (KERN_SUCCESS);
1383 }
1384
1385 /*
1386  * Unwire a range of virtual addresses in a map.  The map should be
1387  * locked.
1388  */
1389 void
1390 vm_fault_unwire(vm_map_t map, vm_map_entry_t entry)
1391 {
1392         boolean_t fictitious;
1393         vm_offset_t start;
1394         vm_offset_t end;
1395         vm_offset_t va;
1396         vm_paddr_t pa;
1397         pmap_t pmap;
1398
1399         pmap = vm_map_pmap(map);
1400         start = entry->start;
1401         end = entry->end;
1402         fictitious = entry->object.vm_object &&
1403                         (entry->object.vm_object->type == OBJT_DEVICE);
1404
1405         /*
1406          * Since the pages are wired down, we must be able to get their
1407          * mappings from the physical map system.
1408          */
1409         for (va = start; va < end; va += PAGE_SIZE) {
1410                 pa = pmap_extract(pmap, va);
1411                 if (pa != 0) {
1412                         pmap_change_wiring(pmap, va, FALSE);
1413                         if (!fictitious)
1414                                 vm_page_unwire(PHYS_TO_VM_PAGE(pa), 1);
1415                 }
1416         }
1417 }
1418
1419 /*
1420  * Reduce the rate at which memory is allocated to a process based
1421  * on the perceived load on the VM system. As the load increases
1422  * the allocation burst rate goes down and the delay increases. 
1423  *
1424  * Rate limiting does not apply when faulting active or inactive
1425  * pages.  When faulting 'cache' pages, rate limiting only applies
1426  * if the system currently has a severe page deficit.
1427  *
1428  * XXX vm_pagesupply should be increased when a page is freed.
1429  *
1430  * We sleep up to 1/10 of a second.
1431  */
1432 static int
1433 vm_fault_ratelimit(struct vmspace *vmspace)
1434 {
1435         if (vm_load_enable == 0)
1436                 return(0);
1437         if (vmspace->vm_pagesupply > 0) {
1438                 --vmspace->vm_pagesupply;
1439                 return(0);
1440         }
1441 #ifdef INVARIANTS
1442         if (vm_load_debug) {
1443                 kprintf("load %-4d give %d pgs, wait %d, pid %-5d (%s)\n",
1444                         vm_load, 
1445                         (1000 - vm_load ) / 10, vm_load * hz / 10000,
1446                         curproc->p_pid, curproc->p_comm);
1447         }
1448 #endif
1449         vmspace->vm_pagesupply = (1000 - vm_load) / 10;
1450         return(vm_load * hz / 10000);
1451 }
1452
1453 /*
1454  *      Routine:
1455  *              vm_fault_copy_entry
1456  *      Function:
1457  *              Copy all of the pages from a wired-down map entry to another.
1458  *
1459  *      In/out conditions:
1460  *              The source and destination maps must be locked for write.
1461  *              The source map entry must be wired down (or be a sharing map
1462  *              entry corresponding to a main map entry that is wired down).
1463  */
1464
1465 void
1466 vm_fault_copy_entry(vm_map_t dst_map, vm_map_t src_map,
1467     vm_map_entry_t dst_entry, vm_map_entry_t src_entry)
1468 {
1469         vm_object_t dst_object;
1470         vm_object_t src_object;
1471         vm_ooffset_t dst_offset;
1472         vm_ooffset_t src_offset;
1473         vm_prot_t prot;
1474         vm_offset_t vaddr;
1475         vm_page_t dst_m;
1476         vm_page_t src_m;
1477
1478 #ifdef  lint
1479         src_map++;
1480 #endif  /* lint */
1481
1482         src_object = src_entry->object.vm_object;
1483         src_offset = src_entry->offset;
1484
1485         /*
1486          * Create the top-level object for the destination entry. (Doesn't
1487          * actually shadow anything - we copy the pages directly.)
1488          */
1489         vm_map_entry_allocate_object(dst_entry);
1490         dst_object = dst_entry->object.vm_object;
1491
1492         prot = dst_entry->max_protection;
1493
1494         /*
1495          * Loop through all of the pages in the entry's range, copying each
1496          * one from the source object (it should be there) to the destination
1497          * object.
1498          */
1499         for (vaddr = dst_entry->start, dst_offset = 0;
1500             vaddr < dst_entry->end;
1501             vaddr += PAGE_SIZE, dst_offset += PAGE_SIZE) {
1502
1503                 /*
1504                  * Allocate a page in the destination object
1505                  */
1506                 do {
1507                         dst_m = vm_page_alloc(dst_object,
1508                                 OFF_TO_IDX(dst_offset), VM_ALLOC_NORMAL);
1509                         if (dst_m == NULL) {
1510                                 vm_wait();
1511                         }
1512                 } while (dst_m == NULL);
1513
1514                 /*
1515                  * Find the page in the source object, and copy it in.
1516                  * (Because the source is wired down, the page will be in
1517                  * memory.)
1518                  */
1519                 src_m = vm_page_lookup(src_object,
1520                         OFF_TO_IDX(dst_offset + src_offset));
1521                 if (src_m == NULL)
1522                         panic("vm_fault_copy_wired: page missing");
1523
1524                 vm_page_copy(src_m, dst_m);
1525
1526                 /*
1527                  * Enter it in the pmap...
1528                  */
1529
1530                 vm_page_flag_clear(dst_m, PG_ZERO);
1531                 pmap_enter(dst_map->pmap, vaddr, dst_m, prot, FALSE);
1532                 vm_page_flag_set(dst_m, PG_WRITEABLE|PG_MAPPED);
1533
1534                 /*
1535                  * Mark it no longer busy, and put it on the active list.
1536                  */
1537                 vm_page_activate(dst_m);
1538                 vm_page_wakeup(dst_m);
1539         }
1540 }
1541
1542
1543 /*
1544  * This routine checks around the requested page for other pages that
1545  * might be able to be faulted in.  This routine brackets the viable
1546  * pages for the pages to be paged in.
1547  *
1548  * Inputs:
1549  *      m, rbehind, rahead
1550  *
1551  * Outputs:
1552  *  marray (array of vm_page_t), reqpage (index of requested page)
1553  *
1554  * Return value:
1555  *  number of pages in marray
1556  */
1557 static int
1558 vm_fault_additional_pages(vm_page_t m, int rbehind, int rahead,
1559     vm_page_t *marray, int *reqpage)
1560 {
1561         int i,j;
1562         vm_object_t object;
1563         vm_pindex_t pindex, startpindex, endpindex, tpindex;
1564         vm_page_t rtm;
1565         int cbehind, cahead;
1566
1567         object = m->object;
1568         pindex = m->pindex;
1569
1570         /*
1571          * we don't fault-ahead for device pager
1572          */
1573         if (object->type == OBJT_DEVICE) {
1574                 *reqpage = 0;
1575                 marray[0] = m;
1576                 return 1;
1577         }
1578
1579         /*
1580          * if the requested page is not available, then give up now
1581          */
1582
1583         if (!vm_pager_has_page(object, pindex, &cbehind, &cahead)) {
1584                 return 0;
1585         }
1586
1587         if ((cbehind == 0) && (cahead == 0)) {
1588                 *reqpage = 0;
1589                 marray[0] = m;
1590                 return 1;
1591         }
1592
1593         if (rahead > cahead) {
1594                 rahead = cahead;
1595         }
1596
1597         if (rbehind > cbehind) {
1598                 rbehind = cbehind;
1599         }
1600
1601         /*
1602          * try to do any readahead that we might have free pages for.
1603          */
1604         if ((rahead + rbehind) >
1605                 ((vmstats.v_free_count + vmstats.v_cache_count) - vmstats.v_free_reserved)) {
1606                 pagedaemon_wakeup();
1607                 marray[0] = m;
1608                 *reqpage = 0;
1609                 return 1;
1610         }
1611
1612         /*
1613          * scan backward for the read behind pages -- in memory 
1614          *
1615          * Assume that if the page is not found an interrupt will not
1616          * create it.  Theoretically interrupts can only remove (busy)
1617          * pages, not create new associations.
1618          */
1619         if (pindex > 0) {
1620                 if (rbehind > pindex) {
1621                         rbehind = pindex;
1622                         startpindex = 0;
1623                 } else {
1624                         startpindex = pindex - rbehind;
1625                 }
1626
1627                 crit_enter();
1628                 for ( tpindex = pindex - 1; tpindex >= startpindex; tpindex -= 1) {
1629                         if (vm_page_lookup( object, tpindex)) {
1630                                 startpindex = tpindex + 1;
1631                                 break;
1632                         }
1633                         if (tpindex == 0)
1634                                 break;
1635                 }
1636
1637                 for(i = 0, tpindex = startpindex; tpindex < pindex; i++, tpindex++) {
1638
1639                         rtm = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL);
1640                         if (rtm == NULL) {
1641                                 crit_exit();
1642                                 for (j = 0; j < i; j++) {
1643                                         vm_page_free(marray[j]);
1644                                 }
1645                                 marray[0] = m;
1646                                 *reqpage = 0;
1647                                 return 1;
1648                         }
1649
1650                         marray[i] = rtm;
1651                 }
1652                 crit_exit();
1653         } else {
1654                 startpindex = 0;
1655                 i = 0;
1656         }
1657
1658         marray[i] = m;
1659         /* page offset of the required page */
1660         *reqpage = i;
1661
1662         tpindex = pindex + 1;
1663         i++;
1664
1665         /*
1666          * scan forward for the read ahead pages
1667          */
1668         endpindex = tpindex + rahead;
1669         if (endpindex > object->size)
1670                 endpindex = object->size;
1671
1672         crit_enter();
1673         for( ; tpindex < endpindex; i++, tpindex++) {
1674
1675                 if (vm_page_lookup(object, tpindex)) {
1676                         break;
1677                 }
1678
1679                 rtm = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL);
1680                 if (rtm == NULL) {
1681                         break;
1682                 }
1683
1684                 marray[i] = rtm;
1685         }
1686         crit_exit();
1687
1688         /* return number of bytes of pages */
1689         return i;
1690 }