Modify the trapframe sigcontext, ucontext, etc. Add %gs to the trapframe
[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.36 2007/01/08 03:33:43 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         if (fs.fault_flags & VM_FAULT_HOLD)
382                 vm_page_hold(fs.m);
383
384         /*
385          * If the page is not wired down, then put it where the pageout daemon
386          * can find it.
387          */
388         if (fs.fault_flags & VM_FAULT_WIRE_MASK) {
389                 if (fs.wired)
390                         vm_page_wire(fs.m);
391                 else
392                         vm_page_unwire(fs.m, 1);
393         } else {
394                 vm_page_activate(fs.m);
395         }
396
397         if (curthread->td_lwp) {
398                 if (fs.hardfault) {
399                         curthread->td_lwp->lwp_ru.ru_majflt++;
400                 } else {
401                         curthread->td_lwp->lwp_ru.ru_minflt++;
402                 }
403         }
404
405         /*
406          * Unlock everything, and return
407          */
408         vm_page_wakeup(fs.m);
409         vm_object_deallocate(fs.first_object);
410
411         return (KERN_SUCCESS);
412 }
413
414 /*
415  * Fault-in the specified virtual address in the specified map, doing all
416  * necessary manipulation of the object store and all necessary I/O.  Return
417  * a held VM page or NULL, and set *errorp.  The related pmap is not
418  * updated.
419  *
420  * Since the pmap is not updated, this routine may not be used to wire
421  * the page.
422  */
423 vm_page_t
424 vm_fault_page(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
425               int fault_flags, int *errorp)
426 {
427         int result;
428         vm_pindex_t first_pindex;
429         struct faultstate fs;
430
431         mycpu->gd_cnt.v_vm_faults++;
432
433         fs.didlimit = 0;
434         fs.hardfault = 0;
435         fs.fault_flags = fault_flags;
436         KKASSERT((fault_flags & VM_FAULT_WIRE_MASK) == 0);
437
438 RetryFault:
439         /*
440          * Find the vm_map_entry representing the backing store and resolve
441          * the top level object and page index.  This may have the side
442          * effect of executing a copy-on-write on the map entry and/or
443          * creating a shadow object, but will not COW any actual VM pages.
444          *
445          * On success fs.map is left read-locked and various other fields 
446          * are initialized but not otherwise referenced or locked.
447          *
448          * NOTE!  vm_map_lookup will upgrade the fault_type to VM_FAULT_WRITE
449          * if the map entry is a virtual page table and also writable,
450          * so we can set the 'A'accessed bit in the virtual page table entry.
451          */
452         fs.map = map;
453         result = vm_map_lookup(&fs.map, vaddr, fault_type,
454                                &fs.entry, &fs.first_object,
455                                &first_pindex, &fs.first_prot, &fs.wired);
456
457         if (result != KERN_SUCCESS) {
458                 *errorp = result;
459                 return (NULL);
460         }
461
462         /*
463          * fs.map is read-locked
464          *
465          * Misc checks.  Save the map generation number to detect races.
466          */
467         fs.map_generation = fs.map->timestamp;
468
469         if (fs.entry->eflags & MAP_ENTRY_NOFAULT) {
470                 panic("vm_fault: fault on nofault entry, addr: %lx",
471                     (u_long)vaddr);
472         }
473
474         /*
475          * A system map entry may return a NULL object.  No object means
476          * no pager means an unrecoverable kernel fault.
477          */
478         if (fs.first_object == NULL) {
479                 panic("vm_fault: unrecoverable fault at %p in entry %p",
480                         (void *)vaddr, fs.entry);
481         }
482
483         /*
484          * Make a reference to this object to prevent its disposal while we
485          * are messing with it.  Once we have the reference, the map is free
486          * to be diddled.  Since objects reference their shadows (and copies),
487          * they will stay around as well.
488          *
489          * Bump the paging-in-progress count to prevent size changes (e.g.
490          * truncation operations) during I/O.  This must be done after
491          * obtaining the vnode lock in order to avoid possible deadlocks.
492          */
493         vm_object_reference(fs.first_object);
494         fs.vp = vnode_pager_lock(fs.first_object);
495         vm_object_pip_add(fs.first_object, 1);
496
497         fs.lookup_still_valid = TRUE;
498         fs.first_m = NULL;
499         fs.object = fs.first_object;    /* so unlock_and_deallocate works */
500
501         /*
502          * If the entry is wired we cannot change the page protection.
503          */
504         if (fs.wired)
505                 fault_type = fs.first_prot;
506
507         /*
508          * The page we want is at (first_object, first_pindex), but if the
509          * vm_map_entry is VM_MAPTYPE_VPAGETABLE we have to traverse the
510          * page table to figure out the actual pindex.
511          *
512          * NOTE!  DEVELOPMENT IN PROGRESS, THIS IS AN INITIAL IMPLEMENTATION
513          * ONLY
514          */
515         if (fs.entry->maptype == VM_MAPTYPE_VPAGETABLE) {
516                 result = vm_fault_vpagetable(&fs, &first_pindex,
517                                              fs.entry->aux.master_pde,
518                                              fault_type);
519                 if (result == KERN_TRY_AGAIN)
520                         goto RetryFault;
521                 if (result != KERN_SUCCESS) {
522                         *errorp = result;
523                         return (NULL);
524                 }
525         }
526
527         /*
528          * Now we have the actual (object, pindex), fault in the page.  If
529          * vm_fault_object() fails it will unlock and deallocate the FS
530          * data.   If it succeeds everything remains locked and fs->object
531          * will have an additinal PIP count if it is not equal to
532          * fs->first_object
533          */
534         result = vm_fault_object(&fs, first_pindex, fault_type);
535
536         if (result == KERN_TRY_AGAIN)
537                 goto RetryFault;
538         if (result != KERN_SUCCESS) {
539                 *errorp = result;
540                 return(NULL);
541         }
542
543         /*
544          * On success vm_fault_object() does not unlock or deallocate, and fs.m
545          * will contain a busied page.
546          */
547         unlock_things(&fs);
548
549         /*
550          * Return a held page.  We are not doing any pmap manipulation so do
551          * not set PG_MAPPED.
552          */
553         vm_page_flag_clear(fs.m, PG_ZERO);
554         vm_page_flag_set(fs.m, PG_REFERENCED);
555         vm_page_hold(fs.m);
556
557         /*
558          * Unbusy the page by activating it.  It remains held and will not
559          * be reclaimed.
560          */
561         vm_page_activate(fs.m);
562
563         if (curthread->td_lwp) {
564                 if (fs.hardfault) {
565                         curthread->td_lwp->lwp_ru.ru_majflt++;
566                 } else {
567                         curthread->td_lwp->lwp_ru.ru_minflt++;
568                 }
569         }
570
571         /*
572          * Unlock everything, and return the held page.
573          */
574         vm_page_wakeup(fs.m);
575         vm_object_deallocate(fs.first_object);
576
577         *errorp = 0;
578         return(fs.m);
579 }
580
581 /*
582  * Translate the virtual page number (first_pindex) that is relative
583  * to the address space into a logical page number that is relative to the
584  * backing object.  Use the virtual page table pointed to by (vpte).
585  *
586  * This implements an N-level page table.  Any level can terminate the
587  * scan by setting VPTE_PS.   A linear mapping is accomplished by setting
588  * VPTE_PS in the master page directory entry set via mcontrol(MADV_SETMAP).
589  */
590 static
591 int
592 vm_fault_vpagetable(struct faultstate *fs, vm_pindex_t *pindex,
593                     vpte_t vpte, int fault_type)
594 {
595         struct sf_buf *sf;
596         int vshift = 32 - PAGE_SHIFT;   /* page index bits remaining */
597         int result = KERN_SUCCESS;
598         vpte_t *ptep;
599
600         for (;;) {
601                 /*
602                  * We cannot proceed if the vpte is not valid, not readable
603                  * for a read fault, or not writable for a write fault.
604                  */
605                 if ((vpte & VPTE_V) == 0) {
606                         unlock_and_deallocate(fs);
607                         return (KERN_FAILURE);
608                 }
609                 if ((fault_type & VM_PROT_READ) && (vpte & VPTE_R) == 0) {
610                         unlock_and_deallocate(fs);
611                         return (KERN_FAILURE);
612                 }
613                 if ((fault_type & VM_PROT_WRITE) && (vpte & VPTE_W) == 0) {
614                         unlock_and_deallocate(fs);
615                         return (KERN_FAILURE);
616                 }
617                 if ((vpte & VPTE_PS) || vshift == 0)
618                         break;
619                 KKASSERT(vshift >= VPTE_PAGE_BITS);
620
621                 /*
622                  * Get the page table page.  Nominally we only read the page
623                  * table, but since we are actively setting VPTE_M and VPTE_A,
624                  * tell vm_fault_object() that we are writing it. 
625                  *
626                  * There is currently no real need to optimize this.
627                  */
628                 result = vm_fault_object(fs, vpte >> PAGE_SHIFT, VM_PROT_WRITE);
629                 if (result != KERN_SUCCESS)
630                         return (result);
631
632                 /*
633                  * Process the returned fs.m and look up the page table
634                  * entry in the page table page.
635                  */
636                 vshift -= VPTE_PAGE_BITS;
637                 sf = sf_buf_alloc(fs->m, SFB_CPUPRIVATE);
638                 ptep = ((vpte_t *)sf_buf_kva(sf) +
639                         ((*pindex >> vshift) & VPTE_PAGE_MASK));
640                 vpte = *ptep;
641
642                 /*
643                  * Page table write-back.  If the vpte is valid for the
644                  * requested operation, do a write-back to the page table.
645                  *
646                  * XXX VPTE_M is not set properly for page directory pages.
647                  * It doesn't get set in the page directory if the page table
648                  * is modified during a read access.
649                  */
650                 if ((fault_type & VM_PROT_WRITE) && (vpte & VPTE_V) &&
651                     (vpte & VPTE_W)) {
652                         if ((vpte & (VPTE_M|VPTE_A)) == 0) {
653                                 atomic_set_int(ptep, VPTE_M|VPTE_A);
654                                 vm_page_dirty(fs->m);
655                         }
656                 }
657                 if ((fault_type & VM_PROT_READ) && (vpte & VPTE_V) &&
658                     (vpte & VPTE_R)) {
659                         if ((vpte & VPTE_A) == 0) {
660                                 atomic_set_int(ptep, VPTE_A);
661                                 vm_page_dirty(fs->m);
662                         }
663                 }
664                 sf_buf_free(sf);
665                 vm_page_flag_set(fs->m, PG_REFERENCED);
666                 vm_page_activate(fs->m);
667                 vm_page_wakeup(fs->m);
668                 cleanup_successful_fault(fs);
669         }
670         /*
671          * Combine remaining address bits with the vpte.
672          */
673         *pindex = (vpte >> PAGE_SHIFT) +
674                   (*pindex & ((1 << vshift) - 1));
675         return (KERN_SUCCESS);
676 }
677
678
679 /*
680  * Do all operations required to fault-in (fs.first_object, pindex).  Run
681  * through the shadow chain as necessary and do required COW or virtual
682  * copy operations.  The caller has already fully resolved the vm_map_entry
683  * and, if appropriate, has created a copy-on-write layer.  All we need to
684  * do is iterate the object chain.
685  *
686  * On failure (fs) is unlocked and deallocated and the caller may return or
687  * retry depending on the failure code.  On success (fs) is NOT unlocked or
688  * deallocated, fs.m will contained a resolved, busied page, and fs.object
689  * will have an additional PIP count if it is not equal to fs.first_object.
690  */
691 static
692 int
693 vm_fault_object(struct faultstate *fs,
694                 vm_pindex_t first_pindex, vm_prot_t fault_type)
695 {
696         vm_object_t next_object;
697         vm_page_t marray[VM_FAULT_READ];
698         vm_pindex_t pindex;
699         int faultcount;
700
701         fs->prot = fs->first_prot;
702         fs->object = fs->first_object;
703         pindex = first_pindex;
704
705         /* 
706          * If a read fault occurs we try to make the page writable if
707          * possible.  There are three cases where we cannot make the
708          * page mapping writable:
709          *
710          * (1) The mapping is read-only or the VM object is read-only,
711          *     fs->prot above will simply not have VM_PROT_WRITE SET.
712          *
713          * (2) If the mapping is a virtual page table we need to be able
714          *     to detect writes so we can set VPTE_M.
715          *
716          * (3) If the VM page is read-only or copy-on-write, upgrading would
717          *     just result in an unnecessary COW fault.
718          */
719         if (fault_type == VM_PROT_READ && 
720             fs->entry->maptype == VM_MAPTYPE_VPAGETABLE) {
721                 fs->prot &= ~VM_PROT_WRITE;
722         }
723
724         for (;;) {
725                 /*
726                  * If the object is dead, we stop here
727                  */
728                 if (fs->object->flags & OBJ_DEAD) {
729                         unlock_and_deallocate(fs);
730                         return (KERN_PROTECTION_FAILURE);
731                 }
732
733                 /*
734                  * See if page is resident.  spl protection is required
735                  * to avoid an interrupt unbusy/free race against our
736                  * lookup.  We must hold the protection through a page
737                  * allocation or busy.
738                  */
739                 crit_enter();
740                 fs->m = vm_page_lookup(fs->object, pindex);
741                 if (fs->m != NULL) {
742                         int queue;
743                         /*
744                          * Wait/Retry if the page is busy.  We have to do this
745                          * if the page is busy via either PG_BUSY or 
746                          * vm_page_t->busy because the vm_pager may be using
747                          * vm_page_t->busy for pageouts ( and even pageins if
748                          * it is the vnode pager ), and we could end up trying
749                          * to pagein and pageout the same page simultaneously.
750                          *
751                          * We can theoretically allow the busy case on a read
752                          * fault if the page is marked valid, but since such
753                          * pages are typically already pmap'd, putting that
754                          * special case in might be more effort then it is 
755                          * worth.  We cannot under any circumstances mess
756                          * around with a vm_page_t->busy page except, perhaps,
757                          * to pmap it.
758                          */
759                         if ((fs->m->flags & PG_BUSY) || fs->m->busy) {
760                                 unlock_things(fs);
761                                 vm_page_sleep_busy(fs->m, TRUE, "vmpfw");
762                                 mycpu->gd_cnt.v_intrans++;
763                                 vm_object_deallocate(fs->first_object);
764                                 crit_exit();
765                                 return (KERN_TRY_AGAIN);
766                         }
767
768                         /*
769                          * If reactivating a page from PQ_CACHE we may have
770                          * to rate-limit.
771                          */
772                         queue = fs->m->queue;
773                         vm_page_unqueue_nowakeup(fs->m);
774
775                         if ((queue - fs->m->pc) == PQ_CACHE && 
776                             vm_page_count_severe()) {
777                                 vm_page_activate(fs->m);
778                                 unlock_and_deallocate(fs);
779                                 vm_waitpfault();
780                                 crit_exit();
781                                 return (KERN_TRY_AGAIN);
782                         }
783
784                         /*
785                          * Mark page busy for other processes, and the 
786                          * pagedaemon.  If it still isn't completely valid
787                          * (readable), jump to readrest, else we found the
788                          * page and can return.
789                          *
790                          * We can release the spl once we have marked the
791                          * page busy.
792                          */
793                         vm_page_busy(fs->m);
794                         crit_exit();
795
796                         if (((fs->m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) &&
797                             fs->m->object != &kernel_object) {
798                                 goto readrest;
799                         }
800                         break; /* break to PAGE HAS BEEN FOUND */
801                 }
802
803                 /*
804                  * Page is not resident, If this is the search termination
805                  * or the pager might contain the page, allocate a new page.
806                  *
807                  * NOTE: We are still in a critical section.
808                  */
809                 if (TRYPAGER(fs) || fs->object == fs->first_object) {
810                         /*
811                          * If the page is beyond the object size we fail
812                          */
813                         if (pindex >= fs->object->size) {
814                                 crit_exit();
815                                 unlock_and_deallocate(fs);
816                                 return (KERN_PROTECTION_FAILURE);
817                         }
818
819                         /*
820                          * Ratelimit.
821                          */
822                         if (fs->didlimit == 0 && curproc != NULL) {
823                                 int limticks;
824
825                                 limticks = vm_fault_ratelimit(curproc->p_vmspace);
826                                 if (limticks) {
827                                         crit_exit();
828                                         unlock_and_deallocate(fs);
829                                         tsleep(curproc, 0, "vmrate", limticks);
830                                         fs->didlimit = 1;
831                                         return (KERN_TRY_AGAIN);
832                                 }
833                         }
834
835                         /*
836                          * Allocate a new page for this object/offset pair.
837                          */
838                         fs->m = NULL;
839                         if (!vm_page_count_severe()) {
840                                 fs->m = vm_page_alloc(fs->object, pindex,
841                                     (fs->vp || fs->object->backing_object) ? VM_ALLOC_NORMAL : VM_ALLOC_NORMAL | VM_ALLOC_ZERO);
842                         }
843                         if (fs->m == NULL) {
844                                 crit_exit();
845                                 unlock_and_deallocate(fs);
846                                 vm_waitpfault();
847                                 return (KERN_TRY_AGAIN);
848                         }
849                 }
850                 crit_exit();
851
852 readrest:
853                 /*
854                  * We have found a valid page or we have allocated a new page.
855                  * The page thus may not be valid or may not be entirely 
856                  * valid.
857                  *
858                  * Attempt to fault-in the page if there is a chance that the
859                  * pager has it, and potentially fault in additional pages
860                  * at the same time.
861                  *
862                  * We are NOT in splvm here and if TRYPAGER is true then
863                  * fs.m will be non-NULL and will be PG_BUSY for us.
864                  */
865
866                 if (TRYPAGER(fs)) {
867                         int rv;
868                         int reqpage;
869                         int ahead, behind;
870                         u_char behavior = vm_map_entry_behavior(fs->entry);
871
872                         if (behavior == MAP_ENTRY_BEHAV_RANDOM) {
873                                 ahead = 0;
874                                 behind = 0;
875                         } else {
876                                 behind = pindex;
877                                 if (behind > VM_FAULT_READ_BEHIND)
878                                         behind = VM_FAULT_READ_BEHIND;
879
880                                 ahead = fs->object->size - pindex;
881                                 if (ahead < 1)
882                                         ahead = 1;
883                                 if (ahead > VM_FAULT_READ_AHEAD)
884                                         ahead = VM_FAULT_READ_AHEAD;
885                         }
886
887                         if ((fs->first_object->type != OBJT_DEVICE) &&
888                             (behavior == MAP_ENTRY_BEHAV_SEQUENTIAL ||
889                                 (behavior != MAP_ENTRY_BEHAV_RANDOM &&
890                                 pindex >= fs->entry->lastr &&
891                                 pindex < fs->entry->lastr + VM_FAULT_READ))
892                         ) {
893                                 vm_pindex_t firstpindex, tmppindex;
894
895                                 if (first_pindex < 2 * VM_FAULT_READ)
896                                         firstpindex = 0;
897                                 else
898                                         firstpindex = first_pindex - 2 * VM_FAULT_READ;
899
900                                 /*
901                                  * note: partially valid pages cannot be 
902                                  * included in the lookahead - NFS piecemeal
903                                  * writes will barf on it badly.
904                                  *
905                                  * spl protection is required to avoid races
906                                  * between the lookup and an interrupt
907                                  * unbusy/free sequence occuring prior to
908                                  * our busy check.
909                                  */
910                                 crit_enter();
911                                 for (tmppindex = first_pindex - 1;
912                                     tmppindex >= firstpindex;
913                                     --tmppindex
914                                 ) {
915                                         vm_page_t mt;
916
917                                         mt = vm_page_lookup(fs->first_object, tmppindex);
918                                         if (mt == NULL || (mt->valid != VM_PAGE_BITS_ALL))
919                                                 break;
920                                         if (mt->busy ||
921                                                 (mt->flags & (PG_BUSY | PG_FICTITIOUS | PG_UNMANAGED)) ||
922                                                 mt->hold_count ||
923                                                 mt->wire_count) 
924                                                 continue;
925                                         if (mt->dirty == 0)
926                                                 vm_page_test_dirty(mt);
927                                         if (mt->dirty) {
928                                                 vm_page_protect(mt, VM_PROT_NONE);
929                                                 vm_page_deactivate(mt);
930                                         } else {
931                                                 vm_page_cache(mt);
932                                         }
933                                 }
934                                 crit_exit();
935
936                                 ahead += behind;
937                                 behind = 0;
938                         }
939
940                         /*
941                          * now we find out if any other pages should be paged
942                          * in at this time this routine checks to see if the
943                          * pages surrounding this fault reside in the same
944                          * object as the page for this fault.  If they do,
945                          * then they are faulted in also into the object.  The
946                          * array "marray" returned contains an array of
947                          * vm_page_t structs where one of them is the
948                          * vm_page_t passed to the routine.  The reqpage
949                          * return value is the index into the marray for the
950                          * vm_page_t passed to the routine.
951                          *
952                          * fs.m plus the additional pages are PG_BUSY'd.
953                          */
954                         faultcount = vm_fault_additional_pages(
955                             fs->m, behind, ahead, marray, &reqpage);
956
957                         /*
958                          * update lastr imperfectly (we do not know how much
959                          * getpages will actually read), but good enough.
960                          */
961                         fs->entry->lastr = pindex + faultcount - behind;
962
963                         /*
964                          * Call the pager to retrieve the data, if any, after
965                          * releasing the lock on the map.  We hold a ref on
966                          * fs.object and the pages are PG_BUSY'd.
967                          */
968                         unlock_map(fs);
969
970                         if (faultcount) {
971                                 rv = vm_pager_get_pages(fs->object, marray, 
972                                                         faultcount, reqpage);
973                         } else {
974                                 rv = VM_PAGER_FAIL;
975                         }
976
977                         if (rv == VM_PAGER_OK) {
978                                 /*
979                                  * Found the page. Leave it busy while we play
980                                  * with it.
981                                  */
982
983                                 /*
984                                  * Relookup in case pager changed page. Pager
985                                  * is responsible for disposition of old page
986                                  * if moved.
987                                  *
988                                  * XXX other code segments do relookups too.
989                                  * It's a bad abstraction that needs to be
990                                  * fixed/removed.
991                                  */
992                                 fs->m = vm_page_lookup(fs->object, pindex);
993                                 if (fs->m == NULL) {
994                                         unlock_and_deallocate(fs);
995                                         return (KERN_TRY_AGAIN);
996                                 }
997
998                                 ++fs->hardfault;
999                                 break; /* break to PAGE HAS BEEN FOUND */
1000                         }
1001
1002                         /*
1003                          * Remove the bogus page (which does not exist at this
1004                          * object/offset); before doing so, we must get back
1005                          * our object lock to preserve our invariant.
1006                          *
1007                          * Also wake up any other process that may want to bring
1008                          * in this page.
1009                          *
1010                          * If this is the top-level object, we must leave the
1011                          * busy page to prevent another process from rushing
1012                          * past us, and inserting the page in that object at
1013                          * the same time that we are.
1014                          */
1015                         if (rv == VM_PAGER_ERROR) {
1016                                 if (curproc)
1017                                         kprintf("vm_fault: pager read error, pid %d (%s)\n", curproc->p_pid, curproc->p_comm);
1018                                 else
1019                                         kprintf("vm_fault: pager read error, thread %p (%s)\n", curthread, curproc->p_comm);
1020                         }
1021                         /*
1022                          * Data outside the range of the pager or an I/O error
1023                          */
1024                         /*
1025                          * XXX - the check for kernel_map is a kludge to work
1026                          * around having the machine panic on a kernel space
1027                          * fault w/ I/O error.
1028                          */
1029                         if (((fs->map != &kernel_map) && (rv == VM_PAGER_ERROR)) ||
1030                                 (rv == VM_PAGER_BAD)) {
1031                                 vm_page_free(fs->m);
1032                                 fs->m = NULL;
1033                                 unlock_and_deallocate(fs);
1034                                 if (rv == VM_PAGER_ERROR)
1035                                         return (KERN_FAILURE);
1036                                 else
1037                                         return (KERN_PROTECTION_FAILURE);
1038                                 /* NOT REACHED */
1039                         }
1040                         if (fs->object != fs->first_object) {
1041                                 vm_page_free(fs->m);
1042                                 fs->m = NULL;
1043                                 /*
1044                                  * XXX - we cannot just fall out at this
1045                                  * point, m has been freed and is invalid!
1046                                  */
1047                         }
1048                 }
1049
1050                 /*
1051                  * We get here if the object has a default pager (or unwiring) 
1052                  * or the pager doesn't have the page.
1053                  */
1054                 if (fs->object == fs->first_object)
1055                         fs->first_m = fs->m;
1056
1057                 /*
1058                  * Move on to the next object.  Lock the next object before
1059                  * unlocking the current one.
1060                  */
1061                 pindex += OFF_TO_IDX(fs->object->backing_object_offset);
1062                 next_object = fs->object->backing_object;
1063                 if (next_object == NULL) {
1064                         /*
1065                          * If there's no object left, fill the page in the top
1066                          * object with zeros.
1067                          */
1068                         if (fs->object != fs->first_object) {
1069                                 vm_object_pip_wakeup(fs->object);
1070
1071                                 fs->object = fs->first_object;
1072                                 pindex = first_pindex;
1073                                 fs->m = fs->first_m;
1074                         }
1075                         fs->first_m = NULL;
1076
1077                         /*
1078                          * Zero the page if necessary and mark it valid.
1079                          */
1080                         if ((fs->m->flags & PG_ZERO) == 0) {
1081                                 vm_page_zero_fill(fs->m);
1082                         } else {
1083                                 mycpu->gd_cnt.v_ozfod++;
1084                         }
1085                         mycpu->gd_cnt.v_zfod++;
1086                         fs->m->valid = VM_PAGE_BITS_ALL;
1087                         break;  /* break to PAGE HAS BEEN FOUND */
1088                 } else {
1089                         if (fs->object != fs->first_object) {
1090                                 vm_object_pip_wakeup(fs->object);
1091                         }
1092                         KASSERT(fs->object != next_object, ("object loop %p", next_object));
1093                         fs->object = next_object;
1094                         vm_object_pip_add(fs->object, 1);
1095                 }
1096         }
1097
1098         KASSERT((fs->m->flags & PG_BUSY) != 0,
1099                 ("vm_fault: not busy after main loop"));
1100
1101         /*
1102          * PAGE HAS BEEN FOUND. [Loop invariant still holds -- the object lock
1103          * is held.]
1104          */
1105
1106         /*
1107          * If the page is being written, but isn't already owned by the
1108          * top-level object, we have to copy it into a new page owned by the
1109          * top-level object.
1110          */
1111         if (fs->object != fs->first_object) {
1112                 /*
1113                  * We only really need to copy if we want to write it.
1114                  */
1115                 if (fault_type & VM_PROT_WRITE) {
1116                         /*
1117                          * This allows pages to be virtually copied from a 
1118                          * backing_object into the first_object, where the 
1119                          * backing object has no other refs to it, and cannot
1120                          * gain any more refs.  Instead of a bcopy, we just 
1121                          * move the page from the backing object to the 
1122                          * first object.  Note that we must mark the page 
1123                          * dirty in the first object so that it will go out 
1124                          * to swap when needed.
1125                          */
1126                         if (fs->map_generation == fs->map->timestamp &&
1127                                 /*
1128                                  * Only one shadow object
1129                                  */
1130                                 (fs->object->shadow_count == 1) &&
1131                                 /*
1132                                  * No COW refs, except us
1133                                  */
1134                                 (fs->object->ref_count == 1) &&
1135                                 /*
1136                                  * No one else can look this object up
1137                                  */
1138                                 (fs->object->handle == NULL) &&
1139                                 /*
1140                                  * No other ways to look the object up
1141                                  */
1142                                 ((fs->object->type == OBJT_DEFAULT) ||
1143                                  (fs->object->type == OBJT_SWAP)) &&
1144                                 /*
1145                                  * We don't chase down the shadow chain
1146                                  */
1147                                 (fs->object == fs->first_object->backing_object) &&
1148
1149                                 /*
1150                                  * grab the lock if we need to
1151                                  */
1152                                 (fs->lookup_still_valid ||
1153                                  lockmgr(&fs->map->lock, LK_EXCLUSIVE|LK_NOWAIT) == 0)
1154                             ) {
1155                                 
1156                                 fs->lookup_still_valid = 1;
1157                                 /*
1158                                  * get rid of the unnecessary page
1159                                  */
1160                                 vm_page_protect(fs->first_m, VM_PROT_NONE);
1161                                 vm_page_free(fs->first_m);
1162                                 fs->first_m = NULL;
1163
1164                                 /*
1165                                  * grab the page and put it into the 
1166                                  * process'es object.  The page is 
1167                                  * automatically made dirty.
1168                                  */
1169                                 vm_page_rename(fs->m, fs->first_object, first_pindex);
1170                                 fs->first_m = fs->m;
1171                                 vm_page_busy(fs->first_m);
1172                                 fs->m = NULL;
1173                                 mycpu->gd_cnt.v_cow_optim++;
1174                         } else {
1175                                 /*
1176                                  * Oh, well, lets copy it.
1177                                  */
1178                                 vm_page_copy(fs->m, fs->first_m);
1179                         }
1180
1181                         if (fs->m) {
1182                                 /*
1183                                  * We no longer need the old page or object.
1184                                  */
1185                                 release_page(fs);
1186                         }
1187
1188                         /*
1189                          * fs->object != fs->first_object due to above 
1190                          * conditional
1191                          */
1192                         vm_object_pip_wakeup(fs->object);
1193
1194                         /*
1195                          * Only use the new page below...
1196                          */
1197
1198                         mycpu->gd_cnt.v_cow_faults++;
1199                         fs->m = fs->first_m;
1200                         fs->object = fs->first_object;
1201                         pindex = first_pindex;
1202                 } else {
1203                         /*
1204                          * If it wasn't a write fault avoid having to copy
1205                          * the page by mapping it read-only.
1206                          */
1207                         fs->prot &= ~VM_PROT_WRITE;
1208                 }
1209         }
1210
1211         /*
1212          * We may have had to unlock a map to do I/O.  If we did then
1213          * lookup_still_valid will be FALSE.  If the map generation count
1214          * also changed then all sorts of things could have happened while
1215          * we were doing the I/O and we need to retry.
1216          */
1217
1218         if (!fs->lookup_still_valid &&
1219             (fs->map->timestamp != fs->map_generation)) {
1220                 release_page(fs);
1221                 unlock_and_deallocate(fs);
1222                 return (KERN_TRY_AGAIN);
1223         }
1224
1225         /*
1226          * Put this page into the physical map. We had to do the unlock above
1227          * because pmap_enter may cause other faults.   We don't put the page
1228          * back on the active queue until later so that the page-out daemon
1229          * won't find us (yet).
1230          */
1231         if (fs->prot & VM_PROT_WRITE) {
1232                 vm_page_flag_set(fs->m, PG_WRITEABLE);
1233                 vm_object_set_writeable_dirty(fs->m->object);
1234
1235                 /*
1236                  * If the fault is a write, we know that this page is being
1237                  * written NOW so dirty it explicitly to save on 
1238                  * pmap_is_modified() calls later.
1239                  *
1240                  * If this is a NOSYNC mmap we do not want to set PG_NOSYNC
1241                  * if the page is already dirty to prevent data written with
1242                  * the expectation of being synced from not being synced.
1243                  * Likewise if this entry does not request NOSYNC then make
1244                  * sure the page isn't marked NOSYNC.  Applications sharing
1245                  * data should use the same flags to avoid ping ponging.
1246                  *
1247                  * Also tell the backing pager, if any, that it should remove
1248                  * any swap backing since the page is now dirty.
1249                  */
1250                 if (fs->entry->eflags & MAP_ENTRY_NOSYNC) {
1251                         if (fs->m->dirty == 0)
1252                                 vm_page_flag_set(fs->m, PG_NOSYNC);
1253                 } else {
1254                         vm_page_flag_clear(fs->m, PG_NOSYNC);
1255                 }
1256                 if (fs->fault_flags & VM_FAULT_DIRTY) {
1257                         crit_enter();
1258                         vm_page_dirty(fs->m);
1259                         vm_pager_page_unswapped(fs->m);
1260                         crit_exit();
1261                 }
1262         }
1263
1264         /*
1265          * Page had better still be busy.  We are still locked up and 
1266          * fs->object will have another PIP reference if it is not equal
1267          * to fs->first_object.
1268          */
1269         KASSERT(fs->m->flags & PG_BUSY,
1270                 ("vm_fault: page %p not busy!", fs->m));
1271
1272         /*
1273          * Sanity check: page must be completely valid or it is not fit to
1274          * map into user space.  vm_pager_get_pages() ensures this.
1275          */
1276         if (fs->m->valid != VM_PAGE_BITS_ALL) {
1277                 vm_page_zero_invalid(fs->m, TRUE);
1278                 kprintf("Warning: page %p partially invalid on fault\n", fs->m);
1279         }
1280
1281         return (KERN_SUCCESS);
1282 }
1283
1284 /*
1285  * quick version of vm_fault
1286  */
1287 int
1288 vm_fault_quick(caddr_t v, int prot)
1289 {
1290         int r;
1291
1292         if (prot & VM_PROT_WRITE)
1293                 r = subyte(v, fubyte(v));
1294         else
1295                 r = fubyte(v);
1296         return(r);
1297 }
1298
1299 /*
1300  * Wire down a range of virtual addresses in a map.  The entry in question
1301  * should be marked in-transition and the map must be locked.  We must
1302  * release the map temporarily while faulting-in the page to avoid a
1303  * deadlock.  Note that the entry may be clipped while we are blocked but
1304  * will never be freed.
1305  */
1306 int
1307 vm_fault_wire(vm_map_t map, vm_map_entry_t entry, boolean_t user_wire)
1308 {
1309         boolean_t fictitious;
1310         vm_offset_t start;
1311         vm_offset_t end;
1312         vm_offset_t va;
1313         vm_paddr_t pa;
1314         pmap_t pmap;
1315         int rv;
1316
1317         pmap = vm_map_pmap(map);
1318         start = entry->start;
1319         end = entry->end;
1320         fictitious = entry->object.vm_object &&
1321                         (entry->object.vm_object->type == OBJT_DEVICE);
1322
1323         vm_map_unlock(map);
1324         map->timestamp++;
1325
1326         /*
1327          * We simulate a fault to get the page and enter it in the physical
1328          * map.
1329          */
1330         for (va = start; va < end; va += PAGE_SIZE) {
1331                 if (user_wire) {
1332                         rv = vm_fault(map, va, VM_PROT_READ, 
1333                                         VM_FAULT_USER_WIRE);
1334                 } else {
1335                         rv = vm_fault(map, va, VM_PROT_READ|VM_PROT_WRITE,
1336                                         VM_FAULT_CHANGE_WIRING);
1337                 }
1338                 if (rv) {
1339                         while (va > start) {
1340                                 va -= PAGE_SIZE;
1341                                 if ((pa = pmap_extract(pmap, va)) == 0)
1342                                         continue;
1343                                 pmap_change_wiring(pmap, va, FALSE);
1344                                 if (!fictitious)
1345                                         vm_page_unwire(PHYS_TO_VM_PAGE(pa), 1);
1346                         }
1347                         vm_map_lock(map);
1348                         return (rv);
1349                 }
1350         }
1351         vm_map_lock(map);
1352         return (KERN_SUCCESS);
1353 }
1354
1355 /*
1356  * Unwire a range of virtual addresses in a map.  The map should be
1357  * locked.
1358  */
1359 void
1360 vm_fault_unwire(vm_map_t map, vm_map_entry_t entry)
1361 {
1362         boolean_t fictitious;
1363         vm_offset_t start;
1364         vm_offset_t end;
1365         vm_offset_t va;
1366         vm_paddr_t pa;
1367         pmap_t pmap;
1368
1369         pmap = vm_map_pmap(map);
1370         start = entry->start;
1371         end = entry->end;
1372         fictitious = entry->object.vm_object &&
1373                         (entry->object.vm_object->type == OBJT_DEVICE);
1374
1375         /*
1376          * Since the pages are wired down, we must be able to get their
1377          * mappings from the physical map system.
1378          */
1379         for (va = start; va < end; va += PAGE_SIZE) {
1380                 pa = pmap_extract(pmap, va);
1381                 if (pa != 0) {
1382                         pmap_change_wiring(pmap, va, FALSE);
1383                         if (!fictitious)
1384                                 vm_page_unwire(PHYS_TO_VM_PAGE(pa), 1);
1385                 }
1386         }
1387 }
1388
1389 /*
1390  * Reduce the rate at which memory is allocated to a process based
1391  * on the perceived load on the VM system. As the load increases
1392  * the allocation burst rate goes down and the delay increases. 
1393  *
1394  * Rate limiting does not apply when faulting active or inactive
1395  * pages.  When faulting 'cache' pages, rate limiting only applies
1396  * if the system currently has a severe page deficit.
1397  *
1398  * XXX vm_pagesupply should be increased when a page is freed.
1399  *
1400  * We sleep up to 1/10 of a second.
1401  */
1402 static int
1403 vm_fault_ratelimit(struct vmspace *vmspace)
1404 {
1405         if (vm_load_enable == 0)
1406                 return(0);
1407         if (vmspace->vm_pagesupply > 0) {
1408                 --vmspace->vm_pagesupply;
1409                 return(0);
1410         }
1411 #ifdef INVARIANTS
1412         if (vm_load_debug) {
1413                 kprintf("load %-4d give %d pgs, wait %d, pid %-5d (%s)\n",
1414                         vm_load, 
1415                         (1000 - vm_load ) / 10, vm_load * hz / 10000,
1416                         curproc->p_pid, curproc->p_comm);
1417         }
1418 #endif
1419         vmspace->vm_pagesupply = (1000 - vm_load) / 10;
1420         return(vm_load * hz / 10000);
1421 }
1422
1423 /*
1424  *      Routine:
1425  *              vm_fault_copy_entry
1426  *      Function:
1427  *              Copy all of the pages from a wired-down map entry to another.
1428  *
1429  *      In/out conditions:
1430  *              The source and destination maps must be locked for write.
1431  *              The source map entry must be wired down (or be a sharing map
1432  *              entry corresponding to a main map entry that is wired down).
1433  */
1434
1435 void
1436 vm_fault_copy_entry(vm_map_t dst_map, vm_map_t src_map,
1437     vm_map_entry_t dst_entry, vm_map_entry_t src_entry)
1438 {
1439         vm_object_t dst_object;
1440         vm_object_t src_object;
1441         vm_ooffset_t dst_offset;
1442         vm_ooffset_t src_offset;
1443         vm_prot_t prot;
1444         vm_offset_t vaddr;
1445         vm_page_t dst_m;
1446         vm_page_t src_m;
1447
1448 #ifdef  lint
1449         src_map++;
1450 #endif  /* lint */
1451
1452         src_object = src_entry->object.vm_object;
1453         src_offset = src_entry->offset;
1454
1455         /*
1456          * Create the top-level object for the destination entry. (Doesn't
1457          * actually shadow anything - we copy the pages directly.)
1458          */
1459         vm_map_entry_allocate_object(dst_entry);
1460         dst_object = dst_entry->object.vm_object;
1461
1462         prot = dst_entry->max_protection;
1463
1464         /*
1465          * Loop through all of the pages in the entry's range, copying each
1466          * one from the source object (it should be there) to the destination
1467          * object.
1468          */
1469         for (vaddr = dst_entry->start, dst_offset = 0;
1470             vaddr < dst_entry->end;
1471             vaddr += PAGE_SIZE, dst_offset += PAGE_SIZE) {
1472
1473                 /*
1474                  * Allocate a page in the destination object
1475                  */
1476                 do {
1477                         dst_m = vm_page_alloc(dst_object,
1478                                 OFF_TO_IDX(dst_offset), VM_ALLOC_NORMAL);
1479                         if (dst_m == NULL) {
1480                                 vm_wait();
1481                         }
1482                 } while (dst_m == NULL);
1483
1484                 /*
1485                  * Find the page in the source object, and copy it in.
1486                  * (Because the source is wired down, the page will be in
1487                  * memory.)
1488                  */
1489                 src_m = vm_page_lookup(src_object,
1490                         OFF_TO_IDX(dst_offset + src_offset));
1491                 if (src_m == NULL)
1492                         panic("vm_fault_copy_wired: page missing");
1493
1494                 vm_page_copy(src_m, dst_m);
1495
1496                 /*
1497                  * Enter it in the pmap...
1498                  */
1499
1500                 vm_page_flag_clear(dst_m, PG_ZERO);
1501                 pmap_enter(dst_map->pmap, vaddr, dst_m, prot, FALSE);
1502                 vm_page_flag_set(dst_m, PG_WRITEABLE|PG_MAPPED);
1503
1504                 /*
1505                  * Mark it no longer busy, and put it on the active list.
1506                  */
1507                 vm_page_activate(dst_m);
1508                 vm_page_wakeup(dst_m);
1509         }
1510 }
1511
1512
1513 /*
1514  * This routine checks around the requested page for other pages that
1515  * might be able to be faulted in.  This routine brackets the viable
1516  * pages for the pages to be paged in.
1517  *
1518  * Inputs:
1519  *      m, rbehind, rahead
1520  *
1521  * Outputs:
1522  *  marray (array of vm_page_t), reqpage (index of requested page)
1523  *
1524  * Return value:
1525  *  number of pages in marray
1526  */
1527 static int
1528 vm_fault_additional_pages(vm_page_t m, int rbehind, int rahead,
1529     vm_page_t *marray, int *reqpage)
1530 {
1531         int i,j;
1532         vm_object_t object;
1533         vm_pindex_t pindex, startpindex, endpindex, tpindex;
1534         vm_page_t rtm;
1535         int cbehind, cahead;
1536
1537         object = m->object;
1538         pindex = m->pindex;
1539
1540         /*
1541          * we don't fault-ahead for device pager
1542          */
1543         if (object->type == OBJT_DEVICE) {
1544                 *reqpage = 0;
1545                 marray[0] = m;
1546                 return 1;
1547         }
1548
1549         /*
1550          * if the requested page is not available, then give up now
1551          */
1552
1553         if (!vm_pager_has_page(object, pindex, &cbehind, &cahead)) {
1554                 return 0;
1555         }
1556
1557         if ((cbehind == 0) && (cahead == 0)) {
1558                 *reqpage = 0;
1559                 marray[0] = m;
1560                 return 1;
1561         }
1562
1563         if (rahead > cahead) {
1564                 rahead = cahead;
1565         }
1566
1567         if (rbehind > cbehind) {
1568                 rbehind = cbehind;
1569         }
1570
1571         /*
1572          * try to do any readahead that we might have free pages for.
1573          */
1574         if ((rahead + rbehind) >
1575                 ((vmstats.v_free_count + vmstats.v_cache_count) - vmstats.v_free_reserved)) {
1576                 pagedaemon_wakeup();
1577                 marray[0] = m;
1578                 *reqpage = 0;
1579                 return 1;
1580         }
1581
1582         /*
1583          * scan backward for the read behind pages -- in memory 
1584          *
1585          * Assume that if the page is not found an interrupt will not
1586          * create it.  Theoretically interrupts can only remove (busy)
1587          * pages, not create new associations.
1588          */
1589         if (pindex > 0) {
1590                 if (rbehind > pindex) {
1591                         rbehind = pindex;
1592                         startpindex = 0;
1593                 } else {
1594                         startpindex = pindex - rbehind;
1595                 }
1596
1597                 crit_enter();
1598                 for ( tpindex = pindex - 1; tpindex >= startpindex; tpindex -= 1) {
1599                         if (vm_page_lookup( object, tpindex)) {
1600                                 startpindex = tpindex + 1;
1601                                 break;
1602                         }
1603                         if (tpindex == 0)
1604                                 break;
1605                 }
1606
1607                 for(i = 0, tpindex = startpindex; tpindex < pindex; i++, tpindex++) {
1608
1609                         rtm = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL);
1610                         if (rtm == NULL) {
1611                                 crit_exit();
1612                                 for (j = 0; j < i; j++) {
1613                                         vm_page_free(marray[j]);
1614                                 }
1615                                 marray[0] = m;
1616                                 *reqpage = 0;
1617                                 return 1;
1618                         }
1619
1620                         marray[i] = rtm;
1621                 }
1622                 crit_exit();
1623         } else {
1624                 startpindex = 0;
1625                 i = 0;
1626         }
1627
1628         marray[i] = m;
1629         /* page offset of the required page */
1630         *reqpage = i;
1631
1632         tpindex = pindex + 1;
1633         i++;
1634
1635         /*
1636          * scan forward for the read ahead pages
1637          */
1638         endpindex = tpindex + rahead;
1639         if (endpindex > object->size)
1640                 endpindex = object->size;
1641
1642         crit_enter();
1643         for( ; tpindex < endpindex; i++, tpindex++) {
1644
1645                 if (vm_page_lookup(object, tpindex)) {
1646                         break;
1647                 }
1648
1649                 rtm = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL);
1650                 if (rtm == NULL) {
1651                         break;
1652                 }
1653
1654                 marray[i] = rtm;
1655         }
1656         crit_exit();
1657
1658         /* return number of bytes of pages */
1659         return i;
1660 }